diff -urdN ../Tekkotsu_2.3/Behaviors/BehaviorBase.cc ./Behaviors/BehaviorBase.cc
--- ../Tekkotsu_2.3/Behaviors/BehaviorBase.cc	Tue Jan  4 14:51:37 2005
+++ ./Behaviors/BehaviorBase.cc	Thu Jul  7 18:33:51 2005
@@ -1,15 +1,8 @@
 #include "BehaviorBase.h"
+#include "Events/EventRouter.h"
 
 std::set<BehaviorBase*> BehaviorBase::registry;
 
-/*! @deprecated, behavior constructors should take a name argument (which by default should be the name of the type of the class) */
-BehaviorBase::BehaviorBase()
-	: ReferenceCounter(), EventListener(), started(false),
-	  instanceName("?"), className("BehaviorBase")
-{
-	registry.insert(this);
-}
-
 BehaviorBase::BehaviorBase(const std::string& name)
 	: ReferenceCounter(), EventListener(), started(false),
 	  instanceName(name), className(name)
@@ -44,8 +37,8 @@
 BehaviorBase::~BehaviorBase() {
 	SetAutoDelete(false);
 	if(started)
-		DoStop();
-	//{ if(started) { references++; DoStop(); references--; } }
+		std::cerr << "Behavior " << getName() << " deleted while running: use 'RemoveReference', not 'delete'" << std::endl;
+	erouter->removeListener(this);
 	registry.erase(this);
 }
 
@@ -63,6 +56,8 @@
 	//std::cout << getName() << " stopped " << this << std::endl;
 	if(started) {
 		started=false;
+		erouter->removeListener(this);
+		erouter->removeTimer(this);
 		RemoveReference();
 	}
 }
@@ -72,9 +67,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2005/01/04 19:51:37 $
+ * $Date: 2005/07/07 22:33:51 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/BehaviorBase.h ./Behaviors/BehaviorBase.h
--- ../Tekkotsu_2.3/Behaviors/BehaviorBase.h	Tue Jan  4 14:51:37 2005
+++ ./Behaviors/BehaviorBase.h	Sat Apr 23 14:32:59 2005
@@ -16,7 +16,7 @@
  *  rely on the reference counting.
  *
  *  For an empty behavior boilerplate file to help you get started quickly, try
- *  <a href="http://cvs.tekkotsu.org/cgi-bin/viewcvs.cgi/Tekkotsu/docs/behavior_header.h?rev=HEAD&content-type=text/vnd.viewcvs-markup"><i>Tekkotsu</i><tt>/docs/behavior_header.h</tt></a>:
+ *  <a href="http://cvs.tekkotsu.org/cgi-bin/viewcvs.cgi/Tekkotsu/project/templates/behavior.h?rev=HEAD&content-type=text/vnd.viewcvs-markup"><i>project</i><tt>/templates/behavior.h</tt></a>:
  * 
  *  But it would probably still be a good idea to go through the "<a
  *  href="../FirstBehavior.html">First Behavior</a>" tutorial to get a better idea of
@@ -24,7 +24,7 @@
  */
 class BehaviorBase : public ReferenceCounter, public EventListener {
 public:
-	//! destructor - if is active when deleted, will call DoStop() first
+	//! destructor - if is active when deleted, will display a warning (don't delete directly - use RemoveReference())
 	virtual ~BehaviorBase();
 	
 	//! By default, merely adds to the reference counter (through AddReference()); Note you should still call this from your overriding methods
@@ -91,8 +91,6 @@
 	*/
 	
 protected:
-	//! deprecated, behavior constructors should take a name argument (which by default should be the name of the type of the class)
-	BehaviorBase() __attribute__((deprecated));
 	//! constructor, @a name is used as both instance name and class name
 	explicit BehaviorBase(const std::string& name);
 	//! constructor, allows different initial values for class name and instance name
@@ -113,10 +111,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.18 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.21 $
  * $State: Exp $
- * $Date: 2005/01/04 19:51:37 $
+ * $Date: 2005/04/23 18:32:59 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/CVS/Entries ./Behaviors/CVS/Entries
--- ../Tekkotsu_2.3/Behaviors/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,14 @@
+/BehaviorBase.cc/1.9/Thu Jul  7 22:33:51 2005//Ttekkotsu-2_4
+/BehaviorBase.h/1.21/Sat Apr 23 18:32:59 2005//Ttekkotsu-2_4
+/Controller.cc/1.45/Wed Jun  1 05:47:44 2005//Ttekkotsu-2_4
+/Controller.h/1.35/Thu Aug  4 04:37:55 2005//Ttekkotsu-2_4
+/README/1.1/Sat Mar  1 20:53:25 2003//Ttekkotsu-2_4
+/StateNode.cc/1.25/Fri Apr 15 21:30:55 2005//Ttekkotsu-2_4
+/StateNode.h/1.20/Sun Aug  7 04:11:02 2005//Ttekkotsu-2_4
+/Transition.cc/1.16/Wed Aug  3 18:47:58 2005//Ttekkotsu-2_4
+/Transition.h/1.12/Sun Aug  7 04:11:02 2005//Ttekkotsu-2_4
+D/Controls////
+D/Demos////
+D/Mon////
+D/Nodes////
+D/Transitions////
diff -urdN ../Tekkotsu_2.3/Behaviors/CVS/Repository ./Behaviors/CVS/Repository
--- ../Tekkotsu_2.3/Behaviors/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Behaviors
diff -urdN ../Tekkotsu_2.3/Behaviors/CVS/Root ./Behaviors/CVS/Root
--- ../Tekkotsu_2.3/Behaviors/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Behaviors/CVS/Tag ./Behaviors/CVS/Tag
--- ../Tekkotsu_2.3/Behaviors/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Behaviors/Controller.cc ./Behaviors/Controller.cc
--- ../Tekkotsu_2.3/Behaviors/Controller.cc	Wed Jan  5 15:28:34 2005
+++ ./Behaviors/Controller.cc	Wed Jun  1 01:47:44 2005
@@ -2,10 +2,10 @@
 #include "Motion/EmergencyStopMC.h"
 #include "Motion/LedMC.h"
 #include "Motion/MMAccessor.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Shared/WorldState.h"
 #include "Shared/get_time.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Events/TextMsgEvent.h"
 #include "Shared/ERS210Info.h"
 #include "Shared/ERS220Info.h"
@@ -48,11 +48,6 @@
 }
 
 void Controller::DoStop() {
-	motman->removeMotion(display);
-	//these two lines help prevent residual display in case that was the only MotionCommand using LEDs
-	for(unsigned int i=LEDOffset; i<LEDOffset+NumLEDs; i++)
-		motman->setOutput(NULL,i,0.f);
-	display=MotionManager::invalid_MC_ID;
 	sndman->ReleaseFile(config->controller.select_snd);
 	sndman->ReleaseFile(config->controller.next_snd);
 	sndman->ReleaseFile(config->controller.prev_snd);
@@ -60,6 +55,11 @@
 	sndman->ReleaseFile(config->controller.cancel_snd);
 	erouter->removeListener(this);
 	reset();
+	motman->removeMotion(display);
+	display=MotionManager::invalid_MC_ID;
+	//these two lines help prevent residual display in case that was the only MotionCommand using LEDs
+	for(unsigned int i=LEDOffset; i<LEDOffset+NumLEDs; i++)
+		motman->setOutput(NULL,i,0.f);
 	gui_comm->printf("goodbye\n");
 	wireless->setDaemon(gui_comm,false);
 	wireless->close(gui_comm);
@@ -303,6 +303,28 @@
 	}
 }
 
+bool Controller::select(ControlBase* item, const std::string& name) {
+  // Depth first
+  const std::vector<ControlBase*>& slots = item->getSlots();
+  for(unsigned int i=0; i<slots.size(); i++) {
+    if (slots[i] != NULL) {
+      if (slots[i]->getName() == name) { // sensitive to #Name
+	char in[10];
+	snprintf(in, 9, "%d", i); in[9]='\0';
+	ControlBase * ret = item->takeInput(in);
+	if(ret!=NULL) {
+	  setNext(ret);
+	  return true;
+	}
+      } else {
+	if (select(slots[i], name)) 
+	  return true;
+      }
+    }
+  }
+  return false;
+}
+
 void Controller::takeLine(const std::string& s) {
 	//	cout << "RECEIVED: " << s << endl;
 	if(s.size()==0)
@@ -342,13 +364,18 @@
 		} else if(args[0]=="!cancel") {
 			setNext(cmdstack.top()->doCancel());
 		} else if(args[0]=="!select") {
+		  if (args.size() == 1)
 			setNext(cmdstack.top()->doSelect());
+		  else {
+		    select(root, args[1].c_str());
+		    refresh();
+		  }
 		} else if(args[0]=="!next") {
 			setNext(cmdstack.top()->doNextItem());
 		} else if(args[0]=="!prev") {
 			setNext(cmdstack.top()->doPrevItem());
 		} else if(args[0]=="!dump_stack") {
-			theOneController->gui_comm->printf("stack_dump\n%d\n",cmdstack.size());
+			theOneController->gui_comm->printf("stack_dump\n%lu\n",(unsigned long)cmdstack.size());
 			//this is rather ugly - can't iterate a stack, have to unstack and restack it.  Oh well.
 			std::stack< ControlBase* > tmpstack;
 			while(!cmdstack.empty()) {
@@ -465,8 +492,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.41 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.45 $
  * $State: Exp $
- * $Date: 2005/01/05 20:28:34 $
+ * $Date: 2005/06/01 05:47:44 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Controller.h ./Behaviors/Controller.h
--- ../Tekkotsu_2.3/Behaviors/Controller.h	Wed Jan  5 15:28:35 2005
+++ ./Behaviors/Controller.h	Thu Aug  4 00:37:55 2005
@@ -21,7 +21,7 @@
  *	- '<tt>!reset</tt>' - return to the root control
  *	- '<tt>!next</tt>' - calls ControlBase::doNextItem() of the current control
  *	- '<tt>!prev</tt>' - calls ControlBase::doPrevItem() of the current control
- *	- '<tt>!select</tt>' - calls ControlBase::doSelect() of the current control
+ *	- '<tt>!select</tt> [<i>item</i>]' - calls ControlBase::doSelect() of the current control, unless <i>item</i> is specified, in which case it is searched for, starting at the root.
  *	- '<tt>!cancel</tt>' - calls ControlBase::doCancel() of the current control
  *	- '<tt>!dump_stack</tt>' - requests a dump of the current stack of submenus (useful if the GUI (re)connects and thus current robot state is unknown)
  *	- '<tt>!msg </tt><i>text</i>' - sends <i>text</i> out as a TextMsgEvent; also note that any text entered on the console port while a GUI is also connected will also be sent as a TextMsgEvent, without needing the !input.
@@ -103,10 +103,10 @@
 	Controller() : BehaviorBase("Controller"), EventTrapper(), display(MotionManager::invalid_MC_ID), estop_id(MotionManager::invalid_MC_ID), root(NULL), cmdstack(), last_time(0), cur_time(0), nextEv_val(0), nextEv_dur(0), prevEv_val(0), prevEv_dur(0), alreadyGotBoth(false), isControlling(false), gui_comm(NULL)  {init();}	//!< Constructor
 	Controller(ControlBase* r) : BehaviorBase("Controller"), EventTrapper(), display(MotionManager::invalid_MC_ID), estop_id(MotionManager::invalid_MC_ID), root(r), cmdstack(), last_time(0), cur_time(0), nextEv_val(0), nextEv_dur(0), prevEv_val(0), prevEv_dur(0), alreadyGotBoth(false), isControlling(false), gui_comm(NULL) { init(); } //!< Constructor, sets a default root control
 	virtual ~Controller() {
-		cout << "~Controller()..." << endl;
+		std::cout << "~Controller()..." << std::endl;
 		delete root;
 		theOneController=NULL;
-		cout << "~Controller()-DONE" << endl;
+		std::cout << "~Controller()-DONE" << std::endl;
 	} //!< Destructor
 
 	//@{
@@ -152,6 +152,9 @@
 	//! called with each line that's entered on the tekkotsu console or from the GUI
 	void takeLine(const std::string& s);
 
+	//! called with slots (options), a name to lookup; will select the named control
+	bool Controller::select(ControlBase* item, const std::string& name);
+	
 	//! sets a config value - some values may require additional processing (done here) to have the new values take effect
 	int setConfig(const char *str);
 
@@ -217,10 +220,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.32 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.35 $
  * $State: Exp $
- * $Date: 2005/01/05 20:28:35 $
+ * $Date: 2005/08/04 04:37:55 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/BatteryCheckControl.h ./Behaviors/Controls/BatteryCheckControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/BatteryCheckControl.h	Tue Jan 25 15:06:39 2005
+++ ./Behaviors/Controls/BatteryCheckControl.h	Tue Jan 25 15:06:39 2005
@@ -111,7 +111,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.10 $
  * $State: Exp $
  * $Date: 2005/01/25 20:06:39 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/BehaviorActivatorControl.h ./Behaviors/Controls/BehaviorActivatorControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/BehaviorActivatorControl.h	Thu Sep 25 11:26:10 2003
+++ ./Behaviors/Controls/BehaviorActivatorControl.h	Thu Sep 25 11:26:10 2003
@@ -62,7 +62,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Rel $
  * $Date: 2003/09/25 15:26:10 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/BehaviorReportControl.h ./Behaviors/Controls/BehaviorReportControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/BehaviorReportControl.h	Tue Jan 25 15:06:39 2005
+++ ./Behaviors/Controls/BehaviorReportControl.h	Sat Feb  5 02:27:26 2005
@@ -37,14 +37,14 @@
 		snprintf(format,100,"  %%-%ds   %%s\n",maxlen);
 
 		sout->printf("** Currently Instantiated Behavior Report **\n");
-		sout->printf("%d active, %d inactive, %d total\n\n",active.size(),inactive.size(),reg.size());
-		sout->printf("Active Behaviors (%d):\n",active.size());
+		sout->printf("%lu active, %lu inactive, %lu total\n\n",(unsigned long)active.size(),(unsigned long)inactive.size(),(unsigned long)reg.size());
+		sout->printf("Active Behaviors:\n");
 		sout->printf(format,"Class Name","Instance Name");
 		sout->printf(format,"------------","---------------");
 		for(behlist_t::const_iterator it=active.begin(); it!=active.end(); it++)
 			sout->printf(format,(*it)->getClassName().c_str(),(*it)->getName().c_str());
 		sout->printf("\n");
-		sout->printf("Inactive Behaviors (%d):\n",inactive.size());
+		sout->printf("Inactive Behaviors:\n");
 		sout->printf(format,"Class Name","Instance Name");
 		sout->printf(format,"------------","---------------");
 		for(behlist_t::const_iterator it=inactive.begin(); it!=inactive.end(); it++)
@@ -58,10 +58,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
  * $State: Exp $
- * $Date: 2005/01/25 20:06:39 $
+ * $Date: 2005/02/05 07:27:26 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/BehaviorSwitchActivatorControl.h ./Behaviors/Controls/BehaviorSwitchActivatorControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/BehaviorSwitchActivatorControl.h	Thu Sep 25 11:26:10 2003
+++ ./Behaviors/Controls/BehaviorSwitchActivatorControl.h	Thu Sep 25 11:26:10 2003
@@ -54,7 +54,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Rel $
  * $Date: 2003/09/25 15:26:10 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/BehaviorSwitchControl.h ./Behaviors/Controls/BehaviorSwitchControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/BehaviorSwitchControl.h	Thu Nov 11 19:05:03 2004
+++ ./Behaviors/Controls/BehaviorSwitchControl.h	Wed Jun 29 18:02:58 2005
@@ -223,13 +223,15 @@
 
 	virtual void startmine() {
 		if(!retained) {
-			mybeh=Al::construct();
+			Al allocator;
+			mybeh=allocator.construct();
 			mybeh->setName(getName());
 			if(behgrp!=NULL)
 				behgrp->curBehavior=mybeh;
 		} else {
 			if(mybeh==NULL) {
-				mybeh=Al::construct();
+				Al allocator;
+				mybeh=allocator.construct();
 				mybeh->setName(getName());
 				mybeh->AddReference();
 			}
@@ -265,10 +267,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2004/11/12 00:05:03 $
+ * $Date: 2005/06/29 22:02:58 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/CVS/Entries ./Behaviors/Controls/CVS/Entries
--- ../Tekkotsu_2.3/Behaviors/Controls/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Controls/CVS/Entries	Wed Aug 10 11:03:18 2005
@@ -0,0 +1,47 @@
+/BatteryCheckControl.h/1.10/Tue Jan 25 20:06:39 2005//Ttekkotsu-2_4
+/BehaviorActivatorControl.h/1.8/Thu Sep 25 15:26:10 2003//Ttekkotsu-2_4
+/BehaviorReportControl.h/1.6/Sat Feb  5 07:27:26 2005//Ttekkotsu-2_4
+/BehaviorSwitchActivatorControl.h/1.3/Thu Sep 25 15:26:10 2003//Ttekkotsu-2_4
+/BehaviorSwitchControl.h/1.15/Wed Jun 29 22:02:58 2005//Ttekkotsu-2_4
+/ControlBase.cc/1.13/Wed Jun  1 05:47:44 2005//Ttekkotsu-2_4
+/ControlBase.h/1.22/Thu Nov  4 03:01:31 2004//Ttekkotsu-2_4
+/DumpFileControl.h/1.2/Thu Sep 25 15:26:10 2003//Ttekkotsu-2_4
+/EventLogger.cc/1.18/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/EventLogger.h/1.7/Wed Jun  1 05:47:44 2005//Ttekkotsu-2_4
+/FileBrowserControl.cc/1.10/Wed Feb  2 18:20:27 2005//Ttekkotsu-2_4
+/FileBrowserControl.h/1.10/Wed Jan 14 20:43:44 2004//Ttekkotsu-2_4
+/FileInputControl.h/1.2/Tue Mar 23 00:55:01 2004//Ttekkotsu-2_4
+/FreeMemReportControl.cc/1.6/Sat Feb  5 07:27:26 2005//Ttekkotsu-2_4
+/FreeMemReportControl.h/1.8/Thu Nov 11 01:45:35 2004//Ttekkotsu-2_4
+/HelpControl.cc/1.10/Wed Jun  1 05:47:44 2005//Ttekkotsu-2_4
+/HelpControl.h/1.5/Mon Jan 19 22:03:58 2004//Ttekkotsu-2_4
+/LoadCalibration.h/1.5/Mon Jun  6 23:05:51 2005//Ttekkotsu-2_4
+/LoadPostureControl.h/1.16/Mon Jun  6 23:05:51 2005//Ttekkotsu-2_4
+/LoadWalkControl.h/1.9/Mon Jun  6 23:05:51 2005//Ttekkotsu-2_4
+/MCValueEditControl.h/1.3/Thu Sep 25 15:26:11 2003//Ttekkotsu-2_4
+/NetworkStatusControl.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/NullControl.h/1.2/Thu Sep 25 15:26:11 2003//Ttekkotsu-2_4
+/PlaySoundControl.h/1.8/Mon Jun  6 23:05:51 2005//Ttekkotsu-2_4
+/PostureEditor.cc/1.18/Tue Aug  2 22:24:20 2005//Ttekkotsu-2_4
+/PostureEditor.h/1.8/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/ProfilerCheckControl.h/1.6/Thu Nov 11 20:34:59 2004//Ttekkotsu-2_4
+/RebootControl.cc/1.4/Wed Feb  2 18:20:27 2005//Ttekkotsu-2_4
+/RebootControl.h/1.2/Thu Sep 25 15:26:11 2003//Ttekkotsu-2_4
+/RunSequenceControl.h/1.17/Mon Jun  6 23:05:51 2005//Ttekkotsu-2_4
+/SavePostureControl.h/1.12/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/SaveWalkControl.h/1.10/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/SensorObserverControl.cc/1.5/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/SensorObserverControl.h/1.5/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/ShutdownControl.cc/1.4/Wed Feb  2 18:20:27 2005//Ttekkotsu-2_4
+/ShutdownControl.h/1.3/Thu Sep 25 15:26:11 2003//Ttekkotsu-2_4
+/SimulatorAdvanceFrameControl.h/1.1/Thu Jun 23 22:37:28 2005//Ttekkotsu-2_4
+/StringInputControl.cc/1.5/Mon Jul 28 05:54:32 2003//Ttekkotsu-2_4
+/StringInputControl.h/1.5/Tue Mar 23 00:55:01 2004//Ttekkotsu-2_4
+/ToggleControl.h/1.4/Tue Mar 23 00:55:01 2004//Ttekkotsu-2_4
+/ValueEditControl.h/1.15/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/ValueSetControl.h/1.3/Sun Jan 18 10:16:56 2004//Ttekkotsu-2_4
+/WalkCalibration.cc/1.11/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/WalkCalibration.h/1.7/Wed Feb  2 18:47:23 2005//Ttekkotsu-2_4
+/WaypointWalkControl.cc/1.15/Mon Jun  6 23:05:51 2005//Ttekkotsu-2_4
+/WaypointWalkControl.h/1.6/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/CVS/Repository ./Behaviors/Controls/CVS/Repository
--- ../Tekkotsu_2.3/Behaviors/Controls/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Controls/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Behaviors/Controls
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/CVS/Root ./Behaviors/Controls/CVS/Root
--- ../Tekkotsu_2.3/Behaviors/Controls/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Controls/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/CVS/Tag ./Behaviors/Controls/CVS/Tag
--- ../Tekkotsu_2.3/Behaviors/Controls/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Controls/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ControlBase.cc ./Behaviors/Controls/ControlBase.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/ControlBase.cc	Wed Nov  3 22:01:31 2004
+++ ./Behaviors/Controls/ControlBase.cc	Wed Jun  1 01:47:44 2005
@@ -2,7 +2,7 @@
 #include "Motion/MMAccessor.h"
 #include "Motion/LedMC.h"
 #include "Shared/string_util.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Wireless/Wireless.h"
 #include <iomanip>
 #include <sstream>
@@ -331,6 +331,7 @@
 		refresh();
 		return this;		
 		}*/
+	return this; //should never get here, but gcc 4 thinks we can
 }
 
 bool ControlBase::validInput(const std::string& str) {
@@ -391,7 +392,7 @@
 
 void ControlBase::clearMenu() {
 	if(config->main.use_VT100) {
-		sout->printf("\r\33[%dA",(options.size()+1)); //moves cursor up to beginning of menu
+		sout->printf("\r\33[%luA",(unsigned long)(options.size()+1)); //moves cursor up to beginning of menu
 		sout->printf("\33[J"); //clears to end of screen
 	}
 }
@@ -411,9 +412,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.13 $
  * $State: Exp $
- * $Date: 2004/11/04 03:01:31 $
+ * $Date: 2005/06/01 05:47:44 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ControlBase.h ./Behaviors/Controls/ControlBase.h
--- ../Tekkotsu_2.3/Behaviors/Controls/ControlBase.h	Wed Nov  3 22:01:31 2004
+++ ./Behaviors/Controls/ControlBase.h	Wed Nov  3 22:01:31 2004
@@ -167,7 +167,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.22 $
  * $State: Exp $
  * $Date: 2004/11/04 03:01:31 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/DumpFileControl.h ./Behaviors/Controls/DumpFileControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/DumpFileControl.h	Thu Sep 25 11:26:10 2003
+++ ./Behaviors/Controls/DumpFileControl.h	Thu Sep 25 11:26:10 2003
@@ -40,7 +40,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Rel $
  * $Date: 2003/09/25 15:26:10 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/EventLogger.cc ./Behaviors/Controls/EventLogger.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/EventLogger.cc	Wed Dec 22 18:53:34 2004
+++ ./Behaviors/Controls/EventLogger.cc	Sun Aug  7 00:11:03 2005
@@ -6,10 +6,16 @@
 #include "StringInputControl.h"
 #include "NullControl.h"
 #include <sstream>
-#include "Events/LocomotionEvent.h"
-#include "Events/TextMsgEvent.h"
-#include "Events/VisionObjectEvent.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
+#include "Vision/FilterBankGenerator.h"
+#include "Shared/Base64.h"
+
+#include <libxml/xmlmemory.h>
+#include <libxml/parser.h>
+
+Socket* EventLogger::logSocket=NULL;
+unsigned int EventLogger::logSocketRefCount=0;
+int EventLogger::port=10080;
 
 EventLogger::EventLogger() : ControlBase("Event Logger","Allows you to see/log all of the un-trapped events as they are generated"), logfilePath(), logfile(), verbosity(0) {
 	for(unsigned int i=0; i<EventBase::numEGIDs; i++) {
@@ -20,6 +26,22 @@
 	pushSlot(new ValueEditControl<unsigned int>("Verbosity","Controls verbosity level: 0=(gen,source,type); 1=0+gen_id,source_id,type_id; 2=1+duration,timestamp; 3=2+magnitude; additional columns may be added for subclass info","Please enter a new verbosity level: 0=(gen,source,type); 1=0+gen_id,source_id,type_id; 2=1+duration,timestamp; 3=2+magnitude; additional columns may be added for subclass info",&verbosity));
 	pushSlot(new ControlBase("[X] Console Output","If selected, outputs events to the console"));
 	pushSlot(new StringInputControl("[ ] File Output","Please enter the filename to log to (in /ms/...)"));
+	if(logSocket==NULL) {
+		ASSERT(logSocketRefCount==0,"logSocket is NULL, ref count is non-zero");
+		logSocket=wireless->socket(SocketNS::SOCK_STREAM,1024,1<<15);
+		wireless->setDaemon(logSocket);
+		wireless->listen(logSocket,port);
+	}
+	logSocketRefCount++;
+}
+
+EventLogger::~EventLogger() {
+	clearSlots();
+	if(--logSocketRefCount==0) {
+		wireless->setDaemon(logSocket,false);
+		wireless->close(logSocket);
+		logSocket=NULL;
+	}
 }
 
 ControlBase* EventLogger::doSelect() {
@@ -67,11 +89,115 @@
 	std::string logdata = event.getDescription(true,verbosity);
 	if(options[EventBase::numEGIDs+2]->getName()[1]=='X')
 		sout->printf("EVENT: %s\n",logdata.c_str());
+	if(logSocket!=NULL && wireless->isConnected(logSocket->sock)) {
+		xmlDoc * doc = xmlNewDoc((const xmlChar*)"1.0");
+		xmlNode * cur = xmlNewNode(NULL,(const xmlChar*)"");
+		xmlSetProp(cur,(const xmlChar*)"type",(const xmlChar*)"log");
+		xmlNode * desc = xmlNewNode(NULL,(const xmlChar*)"param");
+		event.SaveXML(cur);
+		xmlAddChild(cur,desc);
+		xmlSetProp(desc,(const xmlChar*)"name",(const xmlChar*)"description");
+		xmlSetProp(desc,(const xmlChar*)"value",(const xmlChar*)event.getDescription(true,3).c_str());
+		xmlBuffer* buf=xmlBufferCreate();
+		int n=xmlNodeDump(buf,doc,cur,0,1);
+		xmlFreeDoc(doc);
+		byte * nbuf = logSocket->getWriteBuffer(n+1);
+		if(nbuf!=NULL) {
+			memcpy(nbuf,xmlBufferContent(buf),n);
+			nbuf[n]='\n';
+			logSocket->write(n+1);
+		}
+		xmlBufferFree(buf);
+	}
 	checkLogFile();
 	if(logfile)
 		logfile << logdata << endl;
 }
 
+void EventLogger::logImage(FilterBankGenerator& fbg, unsigned int layer, unsigned int channel, const BehaviorBase* source/*=NULL*/) {
+	if(logSocket!=NULL && wireless->isConnected(logSocket->sock)) {
+		fbg.selectSaveImage(layer,channel);
+		unsigned int len=fbg.getBinSize();
+		char * binbuf=new char[len];
+		fbg.SaveBuffer(binbuf,len);
+		string b64buf=base64::encode(binbuf,len);
+		
+		xmlDoc * doc = xmlNewDoc((const xmlChar*)"1.0");
+		xmlNode * cur = xmlNewNode(NULL,(const xmlChar*)"event");
+		xmlSetProp(cur,(const xmlChar*)"type",(const xmlChar*)"image");
+		if(source!=NULL)
+			xmlSetProp(cur,(const xmlChar*)"sid",(const xmlChar*)source->getName().c_str());
+		snprintf(binbuf,len,"%d",get_time());
+		xmlSetProp(cur,(const xmlChar*)"time",(const xmlChar*)binbuf);
+		delete [] binbuf;
+		xmlNodeSetContent(cur,(const xmlChar*)b64buf.c_str());
+		xmlBuffer* buf=xmlBufferCreate();
+		int n=xmlNodeDump(buf,doc,cur,0,1);
+		xmlFreeDoc(doc);
+		byte * nbuf = logSocket->getWriteBuffer(n+1);
+		if(nbuf!=NULL) {
+			memcpy(nbuf,xmlBufferContent(buf),n);
+			nbuf[n]='\n';
+			logSocket->write(n+1);
+		}
+		xmlBufferFree(buf);
+	}		
+}
+
+void EventLogger::logMessage(std::string msg, const BehaviorBase* source/*=NULL*/, const char* icon/*=NULL*/, unsigned int placement/*=0*/) {
+	if(logSocket!=NULL && wireless->isConnected(logSocket->sock)) {
+		xmlDoc * doc = xmlNewDoc((const xmlChar*)"1.0");
+		xmlNode * cur = xmlNewNode(NULL,(const xmlChar*)"event");
+		xmlSetProp(cur,(const xmlChar*)"type",(const xmlChar*)"userlog");
+		if(source!=NULL)
+			xmlSetProp(cur,(const xmlChar*)"sid",(const xmlChar*)source->getName().c_str());
+		if(icon!=NULL)
+			xmlSetProp(cur,(const xmlChar*)"icon",(const xmlChar*)icon);
+		const unsigned int len=20;
+		char sbuf[len];
+		snprintf(sbuf,len,"%d",placement);
+		xmlSetProp(cur,(const xmlChar*)"voff",(const xmlChar*)sbuf);
+		snprintf(sbuf,len,"%d",get_time());
+		xmlSetProp(cur,(const xmlChar*)"time",(const xmlChar*)sbuf);
+		xmlNodeSetContent(cur,(const xmlChar*)msg.c_str());
+		xmlBuffer* buf=xmlBufferCreate();
+		int n=xmlNodeDump(buf,doc,cur,0,1);
+		xmlFreeDoc(doc);
+		byte * nbuf = logSocket->getWriteBuffer(n+1);
+		if(nbuf!=NULL) {
+			memcpy(nbuf,xmlBufferContent(buf),n);
+			nbuf[n]='\n';
+			logSocket->write(n+1);
+		}
+		xmlBufferFree(buf);
+	}		
+}
+
+void EventLogger::logWebcam(const BehaviorBase* source/*=NULL*/) {
+	if(logSocket!=NULL && wireless->isConnected(logSocket->sock)) {
+		xmlDoc * doc = xmlNewDoc((const xmlChar*)"1.0");
+		xmlNode * cur = xmlNewNode(NULL,(const xmlChar*)"event");
+		xmlSetProp(cur,(const xmlChar*)"type",(const xmlChar*)"webcam");
+		if(source!=NULL)
+			xmlSetProp(cur,(const xmlChar*)"sid",(const xmlChar*)source->getName().c_str());
+		const unsigned int len=20;
+		char sbuf[len];
+		snprintf(sbuf,len,"%d",get_time());
+		xmlSetProp(cur,(const xmlChar*)"time",(const xmlChar*)sbuf);
+		xmlNodeSetContent(cur,(const xmlChar*)" ");
+		xmlBuffer* buf=xmlBufferCreate();
+		int n=xmlNodeDump(buf,doc,cur,0,1);
+		xmlFreeDoc(doc);
+		byte * nbuf = logSocket->getWriteBuffer(n+1);
+		if(nbuf!=NULL) {
+			memcpy(nbuf,xmlBufferContent(buf),n);
+			nbuf[n]='\n';
+			logSocket->write(n+1);
+		}
+		xmlBufferFree(buf);
+	}		
+}
+
 void EventLogger::clearSlots() {
 	erouter->removeListener(this);
 	ControlBase::clearSlots();
@@ -92,13 +218,13 @@
 		logfilePath=strin->getLastInput();
 		logfile.clear();
 		if(logfilePath.size()!=0) {
-			sout->printf("Opening `/ms/%s'\n",logfilePath.c_str());
-			logfile.open(("/ms/"+logfilePath).c_str());
+			sout->printf("Opening `%s'\n",(config->portPath(logfilePath)).c_str());
+			logfile.open((config->portPath(logfilePath)).c_str());
 			if(!logfile.fail()) {
 				setStatus(cur,'X');
 				strin->setName(strin->getName()+": "+logfilePath);
 			} else {
-				serr->printf("Opening `/ms/%s' failed\n",logfilePath.c_str());
+				serr->printf("Opening `%s' failed\n",(config->portPath(logfilePath)).c_str());
 			}
 		}
 	}
@@ -109,8 +235,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.16 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.18 $
  * $State: Exp $
- * $Date: 2004/12/22 23:53:34 $
+ * $Date: 2005/08/07 04:11:03 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/EventLogger.h ./Behaviors/Controls/EventLogger.h
--- ../Tekkotsu_2.3/Behaviors/Controls/EventLogger.h	Thu Oct  7 18:15:20 2004
+++ ./Behaviors/Controls/EventLogger.h	Wed Jun  1 01:47:44 2005
@@ -6,12 +6,15 @@
 #include "Events/EventListener.h"
 #include <fstream>
 
+class FilterBankGenerator;
+class BehaviorBase;
+
 //! allows logging of events to the console or a file
 class EventLogger : public ControlBase, public EventListener {
 public:
 	//!constructor
 	EventLogger();
-	virtual ~EventLogger() { clearSlots(); }
+	virtual ~EventLogger();
 
 	//!opens a custom (embedded) menu to toggle individual EGIDs
 	virtual ControlBase* doSelect();
@@ -21,6 +24,24 @@
 	//!sends all events received to stdout and/or logfile
 	virtual void processEvent(const EventBase& event);
 
+	//!returns #logSocket
+	static class Socket* getLogSocket() { return logSocket; }
+	
+	//! returns #port
+	static int getLogSocketPort() { return port; }
+	
+	//! sets #port
+	static void setLogSocketPort(int p) { port=p; }
+
+	//! send the current camera image over the log socket
+	static void logImage(FilterBankGenerator& fbg, unsigned int layer, unsigned int channel, const BehaviorBase* source=NULL);
+
+	//! send a string over the log socket
+	static void logMessage(std::string msg, const BehaviorBase* source=NULL, const char* icon=NULL, unsigned int placement=0);
+	
+	//! request that the desktop side take a picture with the webcam (if available)
+	static void logWebcam(const BehaviorBase* source=NULL);
+	
 protected:
 	virtual void clearSlots();
 
@@ -35,7 +56,16 @@
 
 	//!if a filename is given, events are logged to here
 	std::ofstream logfile;
-
+	
+	//! events which are logged will be sent over this port in an xml format.  See eventlog.dtd in the docs directory
+	static class Socket* logSocket;
+	
+	//! port number #logSocket will listen on
+	static int port;
+	
+	//! reference count for #logSocket -- when this hits 0, close the socket
+	static unsigned int logSocketRefCount;
+	
 	//!controls the level of verbosity - currently 0 through 2
 	unsigned int verbosity;
 };
@@ -45,10 +75,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
  * $State: Exp $
- * $Date: 2004/10/07 22:15:20 $
+ * $Date: 2005/06/01 05:47:44 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/FileBrowserControl.cc ./Behaviors/Controls/FileBrowserControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/FileBrowserControl.cc	Wed Jan 14 15:43:43 2004
+++ ./Behaviors/Controls/FileBrowserControl.cc	Wed Feb  2 13:20:27 2005
@@ -4,6 +4,8 @@
 #include <unistd.h>
 #include <dirent.h>
 
+using namespace std;
+
 ControlBase * FileBrowserControl::activate(MotionManager::MC_ID display, Socket * gui) {
 	rebuildmenu();
 	return ControlBase::activate(display,gui);
@@ -158,9 +160,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/01/14 20:43:43 $
+ * $Date: 2005/02/02 18:20:27 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/FileBrowserControl.h ./Behaviors/Controls/FileBrowserControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/FileBrowserControl.h	Wed Jan 14 15:43:44 2004
+++ ./Behaviors/Controls/FileBrowserControl.h	Wed Jan 14 15:43:44 2004
@@ -72,7 +72,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.10 $
  * $State: Exp $
  * $Date: 2004/01/14 20:43:44 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/FileInputControl.h ./Behaviors/Controls/FileInputControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/FileInputControl.h	Mon Mar 22 19:55:01 2004
+++ ./Behaviors/Controls/FileInputControl.h	Mon Mar 22 19:55:01 2004
@@ -48,7 +48,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Exp $
  * $Date: 2004/03/23 00:55:01 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/FreeMemReportControl.cc ./Behaviors/Controls/FreeMemReportControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/FreeMemReportControl.cc	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/FreeMemReportControl.cc	Sat Feb  5 02:27:26 2005
@@ -1,6 +1,8 @@
 #include "FreeMemReportControl.h"
-#include <AnalyzerAPI.h>
-#include <AnalyzerError.h>
+#ifdef PLATFORM_APERIOS
+#  include <AnalyzerAPI.h>
+#  include <AnalyzerError.h>
+#endif
 
 void FreeMemReportControl::processEvent(const EventBase& e) {
 	ASSERTRET(e.getGeneratorID()==EventBase::timerEGID,"Unexpected event");
@@ -11,7 +13,7 @@
 		if(freemem<low_mem) {
 			if(!isWarning) {
 				isWarning=true;
-				serr->printf("WARNING: Low memory: %d\n",freemem);
+				serr->printf("WARNING: Low memory: %lu\n",(unsigned long)freemem);
 			}
 		} else {
 			if(isWarning) {
@@ -25,7 +27,7 @@
 	
 void FreeMemReportControl::refresh() {
 	char tmp[256];
-	sprintf(tmp,"Free Mem: %d",freeMem());
+	sprintf(tmp,"Free Mem: %lu",(unsigned long)freeMem());
 	options[1]->setName(tmp);
 	ControlBase::refresh();
 	report();
@@ -35,18 +37,22 @@
 //! reports size of free memory - if this is below low_mem, also generates a warning
 void FreeMemReportControl::report() {
 	size_t freemem=freeMem();
-	sout->printf("%d bytes free\n",freemem);
+	sout->printf("%lu bytes free\n",(unsigned long)freemem);
 	if(freemem<low_mem)
 		if(isWarning)
-			serr->printf("WARNING: Low memory: %d\n",freemem);
+			serr->printf("WARNING: Low memory: %lu\n",(unsigned long)freemem);
 	resetTimerFreq();
 }
 
 //! returns the size of the free memory
 size_t FreeMemReportControl::freeMem() {
 	size_t freemem;
+#ifdef PLATFORM_APERIOS
 	if (AnalyzerGetSizeOfFreeMemory(&freemem)!=azrSUCCESS)
 		sout->printf("Aperios error: getsizeoffreememory failed\n");
+#else
+	freemem=-1U;
+#endif
 	return freemem;
 }
 
@@ -63,9 +69,9 @@
  * @author ejt (object), alokl (core function)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
- * $State: Rel $
- * $Date: 2003/09/25 15:26:11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
+ * $State: Exp $
+ * $Date: 2005/02/05 07:27:26 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/FreeMemReportControl.h ./Behaviors/Controls/FreeMemReportControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/FreeMemReportControl.h	Wed Nov 10 20:45:35 2004
+++ ./Behaviors/Controls/FreeMemReportControl.h	Wed Nov 10 20:45:35 2004
@@ -66,7 +66,7 @@
  * @author ejt (object), alokl (core function)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:35 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/HelpControl.cc ./Behaviors/Controls/HelpControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/HelpControl.cc	Wed Jan  5 15:35:41 2005
+++ ./Behaviors/Controls/HelpControl.cc	Wed Jun  1 01:47:44 2005
@@ -37,7 +37,7 @@
 	const std::string pre="  "+prefix;
 	unsigned int numlen=1;
 	if(slots.size()>1)
-		numlen=(int)(log(slots.size()-1)/log(10))+1;
+		numlen=(int)(log(slots.size()-1.0)/log(10.0))+1;
 #ifdef HelpControl_HTML_
 	unsigned int ngoodslots=0;
 	for(unsigned int i=0; i<slots.size(); i++)
@@ -107,9 +107,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2005/01/05 20:35:41 $
+ * $Date: 2005/06/01 05:47:44 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/HelpControl.h ./Behaviors/Controls/HelpControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/HelpControl.h	Mon Jan 19 17:03:58 2004
+++ ./Behaviors/Controls/HelpControl.h	Mon Jan 19 17:03:58 2004
@@ -45,7 +45,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/01/19 22:03:58 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/LoadCalibration.h ./Behaviors/Controls/LoadCalibration.h
--- ../Tekkotsu_2.3/Behaviors/Controls/LoadCalibration.h	Wed Feb 25 20:02:25 2004
+++ ./Behaviors/Controls/LoadCalibration.h	Mon Jun  6 19:05:51 2005
@@ -14,15 +14,15 @@
 
 	//!Constructor
 	LoadCalibration(WalkMC::CalibrationParam* calp)
-		: FileBrowserControl("Load Calibration...","","/ms/data/motion/"), cp(calp)
+		: FileBrowserControl("Load Calibration...","",config->portPath(config->motion.root)), cp(calp)
 	{ setFilter("*.txt"); }
 	//!Constructor
 	LoadCalibration(const std::string& n,WalkMC::CalibrationParam* calp)
-		: FileBrowserControl(n,"","/ms/data/motion/"), cp(calp)
+		: FileBrowserControl(n,"",config->portPath(config->motion.root)), cp(calp)
 	{ setFilter("*.txt"); }
 	//!Constructor
 	LoadCalibration(const std::string& n, const std::string& d,WalkMC::CalibrationParam* calp)
-		: FileBrowserControl(n,d,"/ms/data/motion/"), cp(calp)
+		: FileBrowserControl(n,d,config->portPath(config->motion.root)), cp(calp)
 	{ setFilter("*.txt"); }
 
 protected:
@@ -31,7 +31,7 @@
 
 	//!calls readData() for each of the matrices
 	virtual ControlBase* selectedFile(const std::string& f) {
-		FILE * file=fopen(f.c_str(),"r");
+		FILE * file=fopen(config->portPath(f).c_str(),"r");
 		if(readMaxs(file))
 			if(readData(file,cp->f_calibration))
 				readData(file,cp->b_calibration);
@@ -86,10 +86,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/02/26 01:02:25 $
+ * $Date: 2005/06/06 23:05:51 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/LoadPostureControl.h ./Behaviors/Controls/LoadPostureControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/LoadPostureControl.h	Fri Jan  7 14:34:22 2005
+++ ./Behaviors/Controls/LoadPostureControl.h	Mon Jun  6 19:05:51 2005
@@ -8,7 +8,7 @@
 #include "Motion/EmergencyStopMC.h"
 #include "Events/EventRouter.h"
 #include "Motion/LedMC.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include <string>
 
 //! Upon activation, loads a position from a file name read from cin (stored in ms/data/motion...)
@@ -17,7 +17,7 @@
  public:
 	//! Constructor
 	LoadPostureControl(const std::string& n, MotionManager::MC_ID estop_id)
-		: FileBrowserControl(n,"Loads a posture from user-selected file",config->motion.root),
+		: FileBrowserControl(n,"Loads a posture from user-selected file",config->portPath(config->motion.root)),
 			estopid(estop_id), ledid(MotionManager::invalid_MC_ID), file()
 	{
 		setFilter("*.pos");
@@ -74,10 +74,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.16 $
  * $State: Exp $
- * $Date: 2005/01/07 19:34:22 $
+ * $Date: 2005/06/06 23:05:51 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/LoadWalkControl.h ./Behaviors/Controls/LoadWalkControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/LoadWalkControl.h	Sat Jan 10 15:10:27 2004
+++ ./Behaviors/Controls/LoadWalkControl.h	Mon Jun  6 19:05:51 2005
@@ -12,14 +12,14 @@
 public:
 	//! constructor, pass the MC_ID of the WalkMC which you want to save
 	LoadWalkControl(const std::string& n, MotionManager::MC_ID w)
-		: FileBrowserControl(n,"Loads a set of walk parameters from a file specified by user",config->motion.root), walk_id(w), thewalk(NULL)
+		: FileBrowserControl(n,"Loads a set of walk parameters from a file specified by user",config->portPath(config->motion.root)), walk_id(w), thewalk(NULL)
 	{
 		setFilter("*.prm");
 	}
 
 	//! constructor, pass a pointer to the WalkMC which you want to save
 	LoadWalkControl(const std::string& n, WalkMC * awalk)
-		: FileBrowserControl(n,"Loads a set of walk parameters from a file specified by user",config->motion.root), walk_id(MotionManager::invalid_MC_ID), thewalk(awalk)
+		: FileBrowserControl(n,"Loads a set of walk parameters from a file specified by user",config->portPath(config->motion.root)), walk_id(MotionManager::invalid_MC_ID), thewalk(awalk)
 	{
 		setFilter("*.prm");
 	}
@@ -56,10 +56,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.8 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2004/01/10 20:10:27 $
+ * $Date: 2005/06/06 23:05:51 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/MCValueEditControl.h ./Behaviors/Controls/MCValueEditControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/MCValueEditControl.h	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/MCValueEditControl.h	Thu Sep 25 11:26:11 2003
@@ -29,7 +29,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Rel $
  * $Date: 2003/09/25 15:26:11 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/NetworkStatusControl.h ./Behaviors/Controls/NetworkStatusControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/NetworkStatusControl.h	Wed Jan 12 17:37:26 2005
+++ ./Behaviors/Controls/NetworkStatusControl.h	Sun Aug  7 00:11:03 2005
@@ -8,7 +8,10 @@
 #include "NullControl.h"
 #include "Events/EventRouter.h"
 #include "Wireless/Wireless.h"
-#include <ERA201D1.h>
+
+#ifdef PLATFORM_APERIOS
+#  include <ERA201D1.h>
+#endif
 
 //! will display current network status such as wireless signal strength
 class NetworkStatusControl : public ControlBase, public EventListener {
@@ -27,6 +30,7 @@
 	//! calls report()
 	virtual void refresh() {
 		erouter->addTimer(this,0,1000,true);
+#ifdef PLATFORM_APERIOS
 		EtherDriverGetWLANStatisticsMsg msg;
 		EtherStatus status = ERA201D1_GetWLANStatistics(&msg);
 		clearSlots();
@@ -52,14 +56,14 @@
 			pushSlot(new NullControl("Error Accessing wireless statistics",tmp));
 			serr->printf("%s",tmp);
 		}
-
+#endif
 		ControlBase::refresh();
 	}
-	//! stops listening for power events and sets display to invalid
 	virtual void deactivate() {
 		erouter->removeListener(this);
 		ControlBase::deactivate();
 	}
+	//! refresh the control whenever an event is received
 	virtual void processEvent(const EventBase& /*event*/) {
 		refresh();
 	}
@@ -73,10 +77,10 @@
  * @author ejt (UI repackaging)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.1 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
  * $State: Exp $
- * $Date: 2005/01/12 22:37:26 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/NullControl.h ./Behaviors/Controls/NullControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/NullControl.h	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/NullControl.h	Thu Sep 25 11:26:11 2003
@@ -32,7 +32,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Rel $
  * $Date: 2003/09/25 15:26:11 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/PlaySoundControl.h ./Behaviors/Controls/PlaySoundControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/PlaySoundControl.h	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/PlaySoundControl.h	Mon Jun  6 19:05:51 2005
@@ -3,14 +3,14 @@
 #define INCLUDED_PlaySoundControl_h_
 
 #include "FileBrowserControl.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 //! Upon activation, loads a position from a file name read from cin (stored in ms/data/motion...)
 class PlaySoundControl : public FileBrowserControl {
  public:
 	//! Constructor
 	PlaySoundControl(const std::string& n)
-		: FileBrowserControl(n,"Plays a sound from a user specified sound file",config->sound.root)
+		: FileBrowserControl(n,"Plays a sound from a user specified sound file",config->portPath(config->sound.root))
 	{
 		setFilter("*.wav");
 	}
@@ -32,10 +32,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
- * $State: Rel $
- * $Date: 2003/09/25 15:26:11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
+ * $State: Exp $
+ * $Date: 2005/06/06 23:05:51 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/PostureEditor.cc ./Behaviors/Controls/PostureEditor.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/PostureEditor.cc	Tue Jan 11 13:40:00 2005
+++ ./Behaviors/Controls/PostureEditor.cc	Tue Aug  2 18:24:20 2005
@@ -3,7 +3,7 @@
 #include "Motion/EmergencyStopMC.h"
 #include "Motion/MotionSequenceMC.h"
 #include "Motion/LedMC.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Events/EventRouter.h"
 #include "ValueEditControl.h"
 #include "NullControl.h"
@@ -16,7 +16,7 @@
 	  estopID(estop_ID), loadPose(NULL), disabledLoadPose(NULL), savePose(NULL), pauseCalled(false)
 {
 	// add load and save menus
-	pushSlot(loadPose=new FileInputControl("Load Posture","Select a posture to open",config->motion.root));
+	pushSlot(loadPose=new FileInputControl("Load Posture","Select a posture to open",config->portPath(config->motion.root)));
 	loadPose->setFilter("*.pos");
 	disabledLoadPose=new NullControl("[Load disabled by EStop]","Cannot load new postures while EStop is active");
 	pushSlot(savePose=new StringInputControl("Save Posture","Please enter the filename to save to (in "+config->motion.root+")"));
@@ -43,6 +43,8 @@
 ControlBase *
 PostureEditor::activate(MotionManager::MC_ID disp_id, Socket * gui) {
 	//cout << "activate" << endl;
+	if(reachID!=MotionManager::invalid_MC_ID) // was already activated
+		return ControlBase::activate(disp_id,gui); // happens when estop is turned on, causing "reactivation"
 	// start off with current pose
 	pose.takeSnapshot();
 	pose.setWeights(1);
@@ -90,24 +92,28 @@
 	//cout << "pause" << endl;
 	refresh(); //one last time, in case this pause is due to un-estop putting Controller into low-profile mode
 	pauseCalled=true;
-	erouter->removeListener(this,EventBase::timerEGID);
+	erouter->removeTimer(this);
+	ControlBase::pause();
 }
 
 void
 PostureEditor::deactivate() {
 	//cout << "deactivate" << endl;
+	//cout << "removeMotion(" << reachID << ")" << endl;
 	motman->removeMotion(reachID);
 	reachID=MotionManager::invalid_MC_ID;
 	erouter->removeListener(this);
+	erouter->removeTimer(this);
 	ControlBase::deactivate();
 }
 
 void
 PostureEditor::processEvent(const EventBase& e) {
+	//cout << "processEvent(" << e.getName() << ")" << endl;
 	if(e.getGeneratorID()==EventBase::estopEGID) {
 		if(e.getTypeID()==EventBase::deactivateETID) {
 			MMAccessor<SmallMotionSequenceMC>(reachID)->play();
-			erouter->removeListener(this,EventBase::timerEGID);
+			erouter->removeTimer(this);
 			if(!pauseCalled)
 				refresh();
 		} else {
@@ -138,6 +144,10 @@
 	//cout << "updatePose" << endl;
 	bool paused=isEStopped();
 	MMAccessor<SmallMotionSequenceMC> reach_acc(reachID);
+	if(paused) {
+		reach_acc->clear();
+		return;
+	}
 	PostureEngine curpose;
 	reach_acc->getPose(curpose);
 	reach_acc->clear();
@@ -149,11 +159,7 @@
 	//now move to desired posture
 	reach_acc->setTime(delay);
 	reach_acc->setPose(pose);
-	//run now or later?
-	if(paused)
-		reach_acc->pause();
-	else
-		reach_acc->play();
+	reach_acc->play();
 }
 
 
@@ -162,8 +168,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.18 $
  * $State: Exp $
- * $Date: 2005/01/11 18:40:00 $
+ * $Date: 2005/08/02 22:24:20 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/PostureEditor.h ./Behaviors/Controls/PostureEditor.h
--- ../Tekkotsu_2.3/Behaviors/Controls/PostureEditor.h	Thu Dec  2 13:48:56 2004
+++ ./Behaviors/Controls/PostureEditor.h	Sun Aug  7 00:11:03 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_PostureEditor_h_
 
 #include "ControlBase.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/PostureEngine.h"
 #include "Motion/MotionManager.h"
 #include "Events/EventListener.h"
@@ -38,7 +38,7 @@
 	static const unsigned int moveTime=1500; //!< number of milliseconds to take to load a posture - individual joint changes will be done in half the time
 	
 	bool isEStopped(); //!< called to check status of estop
-	void updatePose(unsigned int delay); //!< called anytime pose is modified; uses #reachID to move to #pose if estop is off, setting up #ledID otherwise
+	void updatePose(unsigned int delay); //!< called anytime pose is modified; uses #reachID to move to #pose if estop is off
 
 private:
 	PostureEditor(const PostureEditor& ); //!< don't call
@@ -50,10 +50,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/12/02 18:48:56 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ProfilerCheckControl.h ./Behaviors/Controls/ProfilerCheckControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/ProfilerCheckControl.h	Thu Nov 11 15:34:59 2004
+++ ./Behaviors/Controls/ProfilerCheckControl.h	Thu Nov 11 15:34:59 2004
@@ -24,7 +24,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.6 $
  * $State: Exp $
  * $Date: 2004/11/11 20:34:59 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/RebootControl.cc ./Behaviors/Controls/RebootControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/RebootControl.cc	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/RebootControl.cc	Wed Feb  2 13:20:27 2005
@@ -1,9 +1,13 @@
 #include "RebootControl.h"
-#include <OPENR/OPENRAPI.h>
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OPENRAPI.h>
+#endif
 
 ControlBase * RebootControl::doSelect()    {
+#ifdef PLATFORM_APERIOS
 	OBootCondition bc(obcbBOOT_TIMER, 0, obcbttRELATIVE);
 	OPENR::Shutdown(bc);
+#endif
 	return NULL;
 }
 
@@ -12,9 +16,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/09/25 15:26:11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/02/02 18:20:27 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/RebootControl.h ./Behaviors/Controls/RebootControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/RebootControl.h	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/RebootControl.h	Thu Sep 25 11:26:11 2003
@@ -23,7 +23,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Rel $
  * $Date: 2003/09/25 15:26:11 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/RunSequenceControl.h ./Behaviors/Controls/RunSequenceControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/RunSequenceControl.h	Fri Jan  7 14:34:51 2005
+++ ./Behaviors/Controls/RunSequenceControl.h	Mon Jun  6 19:05:51 2005
@@ -6,7 +6,7 @@
 #include "Motion/MotionSequenceMC.h"
 #include "Motion/EmergencyStopMC.h"
 #include "Motion/LedMC.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Motion/MMAccessor.h"
 #include "Shared/TimeET.h"
 #include "Shared/Config.h"
@@ -28,7 +28,7 @@
 public:
 	//! Constructor, sets filter to *.mot
 	RunSequenceControl(const std::string& n, MotionManager::MC_ID estop_id)
-		: FileBrowserControl(n,"Runs a motion sequence from a user-specified file",config->motion.root),
+		: FileBrowserControl(n,"Runs a motion sequence from a user-specified file",config->portPath(config->motion.root)),
 			estopid(estop_id), ledid(MotionManager::invalid_MC_ID), waitingFile()
 	{
 		setFilter("*.mot");
@@ -84,10 +84,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.15 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.17 $
  * $State: Exp $
- * $Date: 2005/01/07 19:34:51 $
+ * $Date: 2005/06/06 23:05:51 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/SavePostureControl.h ./Behaviors/Controls/SavePostureControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/SavePostureControl.h	Fri Jan  7 18:16:58 2005
+++ ./Behaviors/Controls/SavePostureControl.h	Wed Jun  1 01:47:45 2005
@@ -9,9 +9,9 @@
 class SavePostureControl : public StringInputControl {
  public:
 	//! Constructor
-	SavePostureControl() : StringInputControl("Save Posture","Saves current posture to filename read from user","Please enter name for posture file (in /ms/data/motion)...") {}
+	SavePostureControl() : StringInputControl("Save Posture","Saves current posture to filename read from user","Please enter name for posture file (in data/motion)...") {}
 	//! Constructor
-	SavePostureControl(const std::string& n) : StringInputControl(n,"Saves current posture to filename read from user","Please enter name for posture file (in /ms/data/motion)...") {}
+	SavePostureControl(const std::string& n) : StringInputControl(n,"Saves current posture to filename read from user","Please enter name for posture file (in data/motion)...") {}
 
 	virtual ControlBase * takeInput(const std::string& msg) {
 		if(msg.size()>0) {
@@ -33,10 +33,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.12 $
  * $State: Exp $
- * $Date: 2005/01/07 23:16:58 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/SaveWalkControl.h ./Behaviors/Controls/SaveWalkControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/SaveWalkControl.h	Thu Dec  2 16:29:45 2004
+++ ./Behaviors/Controls/SaveWalkControl.h	Wed Jun  1 01:47:45 2005
@@ -10,9 +10,9 @@
 class SaveWalkControl : public StringInputControl {
  public:
 	//! constructor, pass the MC_ID of the walk you want to save
-	SaveWalkControl(const std::string& n, MotionManager::MC_ID w) : StringInputControl(n,"Saves Walk parameters to filename read from user","Please enter name for posture file (in /ms/data/motion)..."), walk_id(w), thewalk(NULL) {}
+	SaveWalkControl(const std::string& n, MotionManager::MC_ID w) : StringInputControl(n,"Saves Walk parameters to filename read from user","Please enter name for posture file (in data/motion)..."), walk_id(w), thewalk(NULL) {}
 	//! constructor, pass a pointer to the walk you want to save
-	SaveWalkControl(const std::string& n, WalkMC * awalk) : StringInputControl(n,"Saves Walk parameters to filename read from user","Please enter name for posture file (in /ms/data/motion)..."), walk_id(MotionManager::invalid_MC_ID), thewalk(awalk) {}
+	SaveWalkControl(const std::string& n, WalkMC * awalk) : StringInputControl(n,"Saves Walk parameters to filename read from user","Please enter name for posture file (in data/motion)..."), walk_id(MotionManager::invalid_MC_ID), thewalk(awalk) {}
 	//! destructor
 	virtual ~SaveWalkControl() {}
 
@@ -49,9 +49,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/12/02 21:29:45 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/SensorObserverControl.cc ./Behaviors/Controls/SensorObserverControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/SensorObserverControl.cc	Tue Jan 11 18:49:04 2005
+++ ./Behaviors/Controls/SensorObserverControl.cc	Wed Jun  1 01:47:45 2005
@@ -7,7 +7,7 @@
 #include "Events/TextMsgEvent.h"
 #include "Events/VisionObjectEvent.h"
 #include "Shared/WorldState.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 SensorObserverControl::SensorObserverControl()
 	: ControlBase("Sensor Observer","Allows you to see/log the sensor data"), logfilePath(), logfile(), helpCtl(NULL), sensorCtl(NULL), buttonCtl(NULL), outputCtl(NULL), dutyCtl(NULL), consoleCtl(NULL), fileCtl(NULL), rtCtl(NULL), rtFreqCtl(NULL), numListeners(0)
@@ -122,14 +122,14 @@
 		logfilePath=fileCtl->getLastInput();
 		logfile.clear();
 		if(logfilePath.size()!=0) {
-			sout->printf("Opening `/ms/%s'\n",logfilePath.c_str());
-			logfile.open(("/ms/"+logfilePath).c_str());
+			sout->printf("Opening `%s'\n",config->portPath(logfilePath).c_str());
+			logfile.open(config->portPath(logfilePath).c_str());
 			if(!logfile.fail()) {
 				std::string tmp=fileCtl->getName();
 				tmp[1]='X';
 				fileCtl->setName(tmp+": "+logfilePath);
 			} else {
-				serr->printf("Opening `/ms/%s' failed\n",logfilePath.c_str());
+				serr->printf("Opening `%s' failed\n",config->portPath(logfilePath).c_str());
 			}
 		}
 	}
@@ -209,8 +209,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2005/01/11 23:49:04 $
+ * $Date: 2005/06/01 05:47:45 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/SensorObserverControl.h ./Behaviors/Controls/SensorObserverControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/SensorObserverControl.h	Tue Jan 11 18:49:04 2005
+++ ./Behaviors/Controls/SensorObserverControl.h	Sun Aug  7 00:11:03 2005
@@ -30,11 +30,11 @@
 	void updateRT();
 
 	//! The real time view for SensorObserverControl is split into a separate class for more straightfoward handling of refreshes
-	friend class RTViewControl : public ControlBase, public EventListener {
+	class RTViewControl : public ControlBase, public EventListener {
 	public:
-		//constructor, pass pointer to SensorObserverControl which contains it
+		//!constructor, pass pointer to SensorObserverControl which contains it
 		RTViewControl(SensorObserverControl* p) : ControlBase("Real-time View"), EventListener(), parent(p), period(500) {}
-		virtual void processEvent(const EventBase& /*event*/) { refresh(); }
+		virtual void processEvent(const EventBase& /*event*/) { refresh(); } //!< causes control to refresh whenever an event (i.e. timer) is received
 		virtual void refresh();
 		virtual void pause();
 		virtual void deactivate();
@@ -46,6 +46,7 @@
 		RTViewControl(const RTViewControl& ); //!< don't call
 		RTViewControl& operator=(const RTViewControl& ); //!< don't call
 	};
+	friend class RTViewControl;
 	
 	//!address of the logfile, if any (empty string is no logfile)
 	std::string logfilePath;
@@ -76,10 +77,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2005/01/11 23:49:04 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ShutdownControl.cc ./Behaviors/Controls/ShutdownControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/ShutdownControl.cc	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/ShutdownControl.cc	Wed Feb  2 13:20:27 2005
@@ -1,9 +1,13 @@
 #include "ShutdownControl.h"
-#include <OPENR/OPENRAPI.h>
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OPENRAPI.h>
+#endif
 
 ControlBase * ShutdownControl::doSelect()    {
+#ifdef PLATFORM_APERIOS
 	OBootCondition bc(0);
 	OPENR::Shutdown(bc);
+#endif
 	return NULL;
 }
 
@@ -12,9 +16,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/09/25 15:26:11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/02/02 18:20:27 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ShutdownControl.h ./Behaviors/Controls/ShutdownControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/ShutdownControl.h	Thu Sep 25 11:26:11 2003
+++ ./Behaviors/Controls/ShutdownControl.h	Thu Sep 25 11:26:11 2003
@@ -23,7 +23,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Rel $
  * $Date: 2003/09/25 15:26:11 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/SimulatorAdvanceFrameControl.h ./Behaviors/Controls/SimulatorAdvanceFrameControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/SimulatorAdvanceFrameControl.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Controls/SimulatorAdvanceFrameControl.h	Thu Jun 23 18:37:28 2005
@@ -0,0 +1,66 @@
+//-*-c++-*-
+#ifndef INCLUDED_SimulatorAdvanceFrameControl_h
+#define INCLUDED_SimulatorAdvanceFrameControl_h
+
+#include "Behaviors/Controls/NullControl.h"
+#ifdef PLATFORM_APERIOS
+#  warning SimulatorAdvanceFrameControl is only useful when running in simulation!
+#else
+#  include "local/sim/Main.h"
+#endif
+
+//! Requests the next camera frame and sensor data, for use when running in simulation
+/*! There are a number of options regarding control of input data and
+ *  flow of time.  This is only applicable when using a non-realtime
+ *  source (such as loading logged data from disk) and the simulator's
+ *  AdvanceOnAccess is 'false' (this is "advance on request" -- the
+ *  same data may be accessed multiple times until you manually
+ *  request the next frame) */
+class SimulatorAdvanceFrameControl : public NullControl {
+
+public:
+	//! default constructor
+	SimulatorAdvanceFrameControl()
+		: NullControl("SimulatorAdvanceFrameControl","Requests the next camera frame and sensor data, for use when running in simulation")
+	{}
+	//! constructor which allows a custom name
+	SimulatorAdvanceFrameControl(const std::string& n)
+		: NullControl(n,"Requests the next camera frame and sensor data, for use when running in simulation")
+	{}
+
+	//can't do anything if we're running on aperios
+#ifndef PLATFORM_APERIOS
+
+	virtual ControlBase * activate(MotionManager::MC_ID disp_id, Socket * gui) {
+		Main::advanceVision();
+		Main::advanceSensor();
+		return NullControl::activate(disp_id,gui);
+	}
+
+	virtual std::string getName() const {
+		if(Main::canManuallyAdvance())
+			return NullControl::getName();
+		return "[Auto-Advancing]";
+	}
+
+	virtual std::string getDescription() const {
+		if(Main::canManuallyAdvance())
+			return NullControl::getDescription();
+		return "Cannot manually advance when in realtime mode, or when AdvanceOnAccess is enabled";
+	}
+	
+#endif
+
+};
+
+/*! @file
+ * @brief Defines SimulatorAdvanceFrameControl, which requests the next camera frame and sensor data, for use when running in simulation
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.1 $
+ * $State: Exp $
+ * $Date: 2005/06/23 22:37:28 $
+ */
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/StringInputControl.cc ./Behaviors/Controls/StringInputControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/StringInputControl.cc	Mon Jul 28 01:54:32 2003
+++ ./Behaviors/Controls/StringInputControl.cc	Mon Jul 28 01:54:32 2003
@@ -42,7 +42,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Rel $
  * $Date: 2003/07/28 05:54:32 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/StringInputControl.h ./Behaviors/Controls/StringInputControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/StringInputControl.h	Mon Mar 22 19:55:01 2004
+++ ./Behaviors/Controls/StringInputControl.h	Mon Mar 22 19:55:01 2004
@@ -44,7 +44,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/03/23 00:55:01 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ToggleControl.h ./Behaviors/Controls/ToggleControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/ToggleControl.h	Mon Mar 22 19:55:01 2004
+++ ./Behaviors/Controls/ToggleControl.h	Mon Mar 22 19:55:01 2004
@@ -141,7 +141,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Exp $
  * $Date: 2004/03/23 00:55:01 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ValueEditControl.h ./Behaviors/Controls/ValueEditControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/ValueEditControl.h	Wed Dec 15 23:50:48 2004
+++ ./Behaviors/Controls/ValueEditControl.h	Sun Aug  7 00:11:03 2005
@@ -146,7 +146,7 @@
 	/*!@name Copies
 	 * accessors for the copies vector, so you can assign the same value to several places if you need to */
 	virtual std::vector<T*>& getCopies() { return copies; } //!< returns a reference to the vector #copies
-	virtual ValueEditControl& addCopy(T* t) { copies.push_back(t); return *this; } //!< #copies.push_back(t)
+	virtual ValueEditControl& addCopy(T* t) { copies.push_back(t); return *this; } //!< copies.push_back(t)
 	//@}
 
 	//! shows current value
@@ -167,10 +167,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2004/12/16 04:50:48 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/ValueSetControl.h ./Behaviors/Controls/ValueSetControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/ValueSetControl.h	Sun Jan 18 05:16:56 2004
+++ ./Behaviors/Controls/ValueSetControl.h	Sun Jan 18 05:16:56 2004
@@ -50,7 +50,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Exp $
  * $Date: 2004/01/18 10:16:56 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/WalkCalibration.cc ./Behaviors/Controls/WalkCalibration.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/WalkCalibration.cc	Wed Nov  3 22:01:32 2004
+++ ./Behaviors/Controls/WalkCalibration.cc	Wed Jun  1 01:47:45 2005
@@ -6,8 +6,11 @@
 #include "Behaviors/Controller.h"
 #include "Shared/WorldState.h"
 #include "Shared/string_util.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include <stdlib.h>
+#include <fstream>
+
+using namespace std;
 
 char * WalkCalibration::datanames[WalkCalibration::NUM_SRC] = { "fs","fr","sr","br","bs","rr" };
 
@@ -160,8 +163,8 @@
 	help->pushSlot(new NullControl("next reboot."));
 
 
-	load=new FileInputControl("Load Data Set","Load data files - select any file from the set, all will be loaded","/ms");
-	save=new StringInputControl("Save Data Set","Saves current data (/ms)","Enter the base name (up to 6 char)");
+	load=new FileInputControl("Load Data Set","Load data files - select any file from the set, all will be loaded","/");
+	save=new StringInputControl("Save Data Set","Saves current data","Enter the base name (up to 6 char)");
 	measure=new NullControl("Take Measurements","Begins the data gathering process");
 	measure->pushSlot(new NullControl());
 	clear=new NullControl("Clear Data","Clear the current data and start over");
@@ -384,7 +387,7 @@
 }
 
 void WalkCalibration::saveData(const std::string& n, const std::vector<float*>& dat) {
-	std::string p=( n.substr(0,3)=="/ms/" ? n : "/ms/"+n );
+	std::string p=config->portPath(n);
 	sout->printf("Saving data to '%s'...\n",p.c_str());
 	std::ofstream out(p.c_str());
 	if(!out) {
@@ -874,24 +877,6 @@
 		return;
 }
 
-
-void WalkCalibration::addSample(std::vector<float*>& dat, unsigned int row, float sol) {
-	float * d=new float[13];
-	dat.push_back(d);
-	for(unsigned int i=0; i<12; i++)
-		d[i]=0;
-	
-	d[row*4+0]=old_x;
-	d[row*4+1]=old_y;
-	d[row*4+2]=old_a;
-	d[row*4+3]=1;
-	d[12]=sol/(stopTime-startTime);
-
-	for(unsigned int i=0; i<13; i++)
-		cout << d[i] << ' ';
-	cout << endl;
-}
-
 void WalkCalibration::addSample(std::vector<float*>& dat, float x, float y, float a) {
 	float * d=new float[6];
 	dat.push_back(d);
@@ -913,9 +898,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/11/04 03:01:32 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/WalkCalibration.h ./Behaviors/Controls/WalkCalibration.h
--- ../Tekkotsu_2.3/Behaviors/Controls/WalkCalibration.h	Thu Oct  7 15:07:04 2004
+++ ./Behaviors/Controls/WalkCalibration.h	Wed Feb  2 13:47:23 2005
@@ -85,7 +85,6 @@
 
 	float arclen(float d, float a, float sign); //!< calculates arc distance corresponding to a displacement and angle, negated if necessary to match @a sign
 	void addSample(); //!< adds data point corresponding to measurements stored in #firstIn and #secondIn
-	void addSample(std::vector<float*>& dat, unsigned int row, float sol); //!< adds data point to @a dat at row with solution (deprecated)
 	void addSample(std::vector<float*>& dat, float x, float y, float a); //!< adds data point to @a dat for a given x,y,a (and #old_x, #old_y, #old_a)
 	static void report(unsigned int row, float cmd, float actual); //!< reports data as they are being taken
 	static void err(const std::string& str); //!< pops up an error message on the controller and also displays it on the console
@@ -124,10 +123,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
  * $State: Exp $
- * $Date: 2004/10/07 19:07:04 $
+ * $Date: 2005/02/02 18:47:23 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/WaypointWalkControl.cc ./Behaviors/Controls/WaypointWalkControl.cc
--- ../Tekkotsu_2.3/Behaviors/Controls/WaypointWalkControl.cc	Thu Dec  2 16:29:45 2004
+++ ./Behaviors/Controls/WaypointWalkControl.cc	Mon Jun  6 19:05:51 2005
@@ -8,7 +8,7 @@
 #include "Motion/WaypointWalkMC.h"
 #include "Motion/WalkMC.h"
 #include "Motion/MMAccessor.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 WaypointWalkControl::WaypointWalkControl()
 	: ControlBase("WaypointWalkControl","Allows interactive control and execution of a set of waypoints"),
@@ -21,7 +21,7 @@
 	pushSlot(addEgoWPCtl=new NullControl("Add Egocentric Waypoint","Appends a new egocentric waypoint (heading and location relative) at the end of the list"));
 	pushSlot(addOffWPCtl=new NullControl("Add Offset Waypoint","Appends a new offset waypoint (location relative) at the end of the list"));
 	pushSlot(addAbsWPCtl=new NullControl("Add Absolute Waypoint","Appends a new absolute waypoint at the end of the list"));
-	pushSlot(loadCtl=new FileInputControl("Load Waypoints","Reads a path from a file",config->motion.root));
+	pushSlot(loadCtl=new FileInputControl("Load Waypoints","Reads a path from a file",config->portPath(config->motion.root)));
 	loadCtl->setFilter("*.wyp");
 	pushSlot(saveCtl=new StringInputControl("Save Waypoints","Writes the current path to a file"));
 	pushSlot(localizationCtl=new StringInputControl("Drift Error Correction","Enter 3 numbers 'x y a' reprenting current error"));
@@ -247,9 +247,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.13 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2004/12/02 21:29:45 $
+ * $Date: 2005/06/06 23:05:51 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Controls/WaypointWalkControl.h ./Behaviors/Controls/WaypointWalkControl.h
--- ../Tekkotsu_2.3/Behaviors/Controls/WaypointWalkControl.h	Tue Jul 27 10:33:28 2004
+++ ./Behaviors/Controls/WaypointWalkControl.h	Sun Aug  7 00:11:03 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_WaypointWalkControl_h_
 
 #include "ControlBase.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 
 class NullControl;
 class ToggleControl;
@@ -16,13 +16,13 @@
 	//!constructor
 	WaypointWalkControl();
 
-	//! add #walk to ::motman
+	//! add #walk_id to ::motman
 	virtual ControlBase * activate(MotionManager::MC_ID disp_id, Socket * gui);
 
 	//!will be called after each waypoint is reached so we can update the menu
 	virtual void refresh();
 
-	//! remove the #walk from ::motman
+	//! remove the #walk_id from ::motman
 	virtual void deactivate(); 
 
 	//!handles selection of menu items
@@ -51,7 +51,7 @@
 	};
 
 protected:
-	bool isRunning; //!< true if #walk is currently running
+	bool isRunning; //!< true if #walk_id is currently running
 	NullControl * startstopCtl; //!< start and stop waypoint running
 	ToggleControl * loopCtl; //!< repeat waypoints
 	NullControl * addEgoWPCtl; //!< start and stop waypoint running
@@ -75,10 +75,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
  * $State: Exp $
- * $Date: 2004/07/27 14:33:28 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/ASCIIVisionBehavior.cc ./Behaviors/Demos/ASCIIVisionBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/ASCIIVisionBehavior.cc	Tue Jan  4 14:51:41 2005
+++ ./Behaviors/Demos/ASCIIVisionBehavior.cc	Wed Jun  1 01:47:45 2005
@@ -3,24 +3,22 @@
 #include "Vision/RawCameraGenerator.h"
 #include "Wireless/Socket.h"
 
-const char ASCIIVisionBehavior::charMap[ASCIIVisionBehavior::charMapSize] = {
-	' ','.',',','\'','~','-','"','^',':',';','!','i','l','I','>','+','?',')',
-	'1',']','|','/','t','f','j','r','n','u','v','c','z','x','Y','U','J','C','L','Q',
-	'0','O','Z','X','m','w','q','p','d','b','k','h','a','o','*','#','M','W','&','8',
-	'%','B','$','@'
-};
+const char ASCIIVisionBehavior::charMap[ASCIIVisionBehavior::charMapSize+1] = 
+" .,-+=ioxwfkHN8M#@";
 
 
 void
 ASCIIVisionBehavior::processEvent(const EventBase& e) {
 	const FilterBankEvent& fbkevt=dynamic_cast<const FilterBankEvent&>(e);
 
-	unsigned int layer = 1;
+	unsigned int layer = 2;
 
 	char charimg[(fbkevt.getWidth(layer)+1)*fbkevt.getHeight(layer)+1];
 	char * curchar=charimg;
 	unsigned char * image = fbkevt.getImage(layer, RawCameraGenerator::CHAN_Y);
-	for (unsigned int y = 0; y < fbkevt.getHeight(layer); y++) {
+	for (unsigned int y = 0; y < fbkevt.getHeight(layer); y+=2) {
+		//notice 'y+=2' above -- skip every other row, makes "image" look more square (letters are taller than wide)
+		//normally, if you want to process every pixel, use y++ instead ;)
 		unsigned char * row = image + (y * fbkevt.getStride(layer));
 		for (unsigned int x = 0; x < fbkevt.getWidth(layer); x++) {
 			unsigned char * pixel = row + (x * fbkevt.getIncrement(layer));
@@ -38,8 +36,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2005/01/04 19:51:41 $
+ * $Date: 2005/06/01 05:47:45 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/ASCIIVisionBehavior.h ./Behaviors/Demos/ASCIIVisionBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/ASCIIVisionBehavior.h	Tue Jan  4 14:51:41 2005
+++ ./Behaviors/Demos/ASCIIVisionBehavior.h	Wed Jun  1 01:47:45 2005
@@ -15,8 +15,8 @@
 	//! constructor
 	ASCIIVisionBehavior() : BehaviorBase("ASCIIVisionBehavior") {}
 
-	static const unsigned int charMapSize=62;  //!< the number of available characters for levels of "gray"
-	static const char charMap[charMapSize]; //!< the included characters sorted in order of darkness - could be improved... (less is more sometimes)
+	static const unsigned int charMapSize=18;  //!< the number of available characters for levels of "gray"
+	static const char charMap[charMapSize+1]; //!< the included characters sorted in order of darkness - could be improved... (less is more sometimes)
 
 	virtual void DoStart() {
 		BehaviorBase::DoStart(); // do this first
@@ -42,10 +42,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
  * $State: Exp $
- * $Date: 2005/01/04 19:51:41 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/AlanBehavior.h ./Behaviors/Demos/AlanBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/AlanBehavior.h	Wed Nov 10 20:45:35 2004
+++ ./Behaviors/Demos/AlanBehavior.h	Wed Jun  1 01:47:45 2005
@@ -5,7 +5,7 @@
 #include "Behaviors/BehaviorBase.h"
 #include "Motion/MotionManager.h"
 #include "Motion/MMAccessor.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Shared/WorldState.h"
 #include "Events/EventRouter.h"
 #include "Motion/PostureMC.h"
@@ -115,10 +115,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.12 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.13 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:35 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/AutoGetupBehavior.h ./Behaviors/Demos/AutoGetupBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/AutoGetupBehavior.h	Tue Dec 21 15:29:07 2004
+++ ./Behaviors/Demos/AutoGetupBehavior.h	Wed Jun  1 01:47:45 2005
@@ -5,11 +5,11 @@
 #include "Behaviors/BehaviorBase.h"
 #include "Shared/WorldState.h"
 #include "Events/EventRouter.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/MotionManager.h"
 #include "Motion/MotionSequenceMC.h"
 #include "Shared/Config.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 //! a little background behavior to keep the robot on its feet
 class AutoGetupBehavior : public BehaviorBase {
@@ -74,10 +74,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2004/12/21 20:29:07 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/BanditMachine.h ./Behaviors/Demos/BanditMachine.h
--- ../Tekkotsu_2.3/Behaviors/Demos/BanditMachine.h	Tue Dec 21 16:49:50 2004
+++ ./Behaviors/Demos/BanditMachine.h	Wed Jun  1 01:47:45 2005
@@ -4,14 +4,14 @@
 
 #include "Behaviors/StateNode.h"
 #include "Behaviors/Demos/StareAtBallBehavior.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/PostureMC.h"
 #include "Motion/MotionSequenceMC.h"
 #include "Motion/LedMC.h"
 #include "Behaviors/Transitions/TimeOutTrans.h"
 #include "Behaviors/Transitions/SmoothCompareTrans.h"
 #include "Behaviors/Nodes/OutputNode.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Shared/ProjectInterface.h"
 
 #include "Behaviors/Demos/karmedbandit.h"
@@ -61,7 +61,7 @@
 		StateNode::DoStart();
 		stare->DoStart();
 		start->DoStart();
-		SharedObject<PostureMC> lie("/ms/data/motion/liedown.pos");
+		SharedObject<PostureMC> lie("liedown.pos");
 		lie->setOutputCmd(LFrLegOffset+RotatorOffset,.77);
 		lie->setOutputCmd(RFrLegOffset+RotatorOffset,.73);
 		lie->setOutputCmd(LFrLegOffset+KneeOffset,.6);
@@ -214,10 +214,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.24 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.25 $
  * $State: Exp $
- * $Date: 2004/12/21 21:49:50 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/BatteryMonitorBehavior.h ./Behaviors/Demos/BatteryMonitorBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/BatteryMonitorBehavior.h	Wed Nov 10 20:45:35 2004
+++ ./Behaviors/Demos/BatteryMonitorBehavior.h	Wed Jun  1 01:47:45 2005
@@ -6,7 +6,7 @@
 #include "Shared/debuget.h"
 #include "Shared/WorldState.h"
 #include "Events/EventRouter.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/MotionManager.h"
 #include "Motion/PostureMC.h"
 #include "Motion/LedMC.h"
@@ -156,10 +156,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.20 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.21 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:35 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/CVS/Entries ./Behaviors/Demos/CVS/Entries
--- ../Tekkotsu_2.3/Behaviors/Demos/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/CVS/Entries	Wed Aug 10 11:03:18 2005
@@ -0,0 +1,46 @@
+/ASCIIVisionBehavior.cc/1.4/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/ASCIIVisionBehavior.h/1.7/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/AlanBehavior.h/1.13/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/AutoGetupBehavior.h/1.15/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/BanditMachine.h/1.25/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/BatteryMonitorBehavior.h/1.21/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/CameraBehavior.cc/1.10/Fri Aug  5 21:55:43 2005//Ttekkotsu-2_4
+/CameraBehavior.h/1.8/Thu Nov 11 01:45:35 2004//Ttekkotsu-2_4
+/ChaseBallBehavior.cc/1.11/Sun Oct 17 01:16:10 2004//Ttekkotsu-2_4
+/ChaseBallBehavior.h/1.5/Thu Nov 11 01:45:35 2004//Ttekkotsu-2_4
+/CrashTestBehavior.h/1.3/Thu Nov 11 01:45:35 2004//Ttekkotsu-2_4
+/DrawSkeletonBehavior.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/DrawVisObjBoundBehavior.h/1.4/Thu Aug  4 21:09:26 2005//Ttekkotsu-2_4
+/DriveMeBehavior.cc/1.11/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/DriveMeBehavior.h/1.8/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/ExploreMachine.cc/1.1/Sat Dec  4 00:10:38 2004//Ttekkotsu-2_4
+/ExploreMachine.h/1.23/Mon Jan 24 22:23:46 2005//Ttekkotsu-2_4
+/FlashIPAddrBehavior.cc/1.3/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/FlashIPAddrBehavior.h/1.4/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/FollowHeadBehavior.cc/1.9/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/FollowHeadBehavior.h/1.5/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/FreezeTestBehavior.h/1.2/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/GroundPlaneBehavior.h/1.8/Thu Dec 23 01:47:06 2004//Ttekkotsu-2_4
+/HeadLevelBehavior.h/1.10/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/HelloWorldBehavior.h/1.5/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/KinematicSampleBehavior.h/1.10/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/KinematicSampleBehavior2.h/1.13/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/LookForSoundBehavior.h/1.8/Thu Dec 23 01:47:06 2004//Ttekkotsu-2_4
+/MCRepeater.h/1.6/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/MotionStressTestBehavior.h/1.8/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/PaceTargetsMachine.cc/1.18/Wed Aug  3 19:11:58 2005//Ttekkotsu-2_4
+/PaceTargetsMachine.h/1.9/Mon Jan 24 22:23:46 2005//Ttekkotsu-2_4
+/RelaxBehavior.h/1.7/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/SimpleChaseBallBehavior.h/1.11/Tue May  3 16:30:29 2005//Ttekkotsu-2_4
+/SoundTestBehavior.h/1.12/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/StareAtBallBehavior.cc/1.10/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/StareAtBallBehavior.h/1.6/Fri Nov 12 00:05:03 2004//Ttekkotsu-2_4
+/StareAtPawBehavior2.cc/1.3/Thu Aug  4 21:09:26 2005//Ttekkotsu-2_4
+/StareAtPawBehavior2.h/1.21/Thu Jul  7 20:25:56 2005//Ttekkotsu-2_4
+/StepTest.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/ToggleHeadLightBehavior.h/1.5/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/WallTestBehavior.cc/1.12/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/WallTestBehavior.h/1.4/Tue Nov 16 00:11:46 2004//Ttekkotsu-2_4
+/WorldStateVelDaemon.h/1.5/Wed Jun 29 22:00:03 2005//Ttekkotsu-2_4
+/karmedbandit.h/1.3/Thu Sep 18 22:40:27 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/CVS/Repository ./Behaviors/Demos/CVS/Repository
--- ../Tekkotsu_2.3/Behaviors/Demos/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Behaviors/Demos
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/CVS/Root ./Behaviors/Demos/CVS/Root
--- ../Tekkotsu_2.3/Behaviors/Demos/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/CVS/Tag ./Behaviors/Demos/CVS/Tag
--- ../Tekkotsu_2.3/Behaviors/Demos/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/CameraBehavior.cc ./Behaviors/Demos/CameraBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/CameraBehavior.cc	Tue Jan 25 18:50:55 2005
+++ ./Behaviors/Demos/CameraBehavior.cc	Fri Aug  5 17:55:43 2005
@@ -1,11 +1,12 @@
 #include "CameraBehavior.h"
 #include "Events/EventRouter.h"
+#include "Events/TextMsgEvent.h"
 #include "Shared/ERS210Info.h"
 #include "Shared/ERS220Info.h"
 #include "Shared/ERS7Info.h"
 #include "Wireless/Socket.h"
 #include "Shared/WorldState.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Shared/Config.h"
 #include "Shared/ProjectInterface.h"
 #include "Motion/LedMC.h"
@@ -35,6 +36,7 @@
 	sndman->LoadFile("camera.wav");
 	ledID=motman->addPersistentMotion(SharedObject<LedMC>());
 	erouter->addListener(this,camera_click);
+	erouter->addListener(this,EventBase::textmsgEGID);
 }
 
 void CameraBehavior::DoStop() {
@@ -51,7 +53,11 @@
  */
 void
 CameraBehavior::processEvent(const EventBase& e) {
-	if(e.shorterThan(camera_click))
+	if(e.getGeneratorID()==EventBase::textmsgEGID) {
+		const TextMsgEvent * txt=dynamic_cast<const TextMsgEvent*>(&e);
+		if(txt==NULL || txt->getText()!="camera")
+			return;
+	} else if(e.shorterThan(camera_click))
 		return;
 
 	{
@@ -156,17 +162,18 @@
 std::string
 CameraBehavior::getNextName(const std::string& ext) {
 	char tmp[100];
-	snprintf(tmp,100,"/ms/data/img%05d%s",index++,ext.c_str());
-	sout->printf("Saving %s...",tmp);
-	return tmp;
+	snprintf(tmp,100,"data/img%05d%s",index++,ext.c_str());
+	std::string ans=config->portPath(tmp);
+	sout->printf("Saving `%s'...",ans.c_str());
+	return ans;
 }
 
 void
 CameraBehavior::initIndex() {
-	std::string path="/ms/data/";
+	std::string path=config->portPath("data/");
 	DIR* dir=opendir(path.c_str());
 	if(dir==NULL) {
-		serr->printf("bad path: %s\n",path.c_str());
+		serr->printf("bad path: `%s'\n",path.c_str());
 		return;
 	}
 	struct dirent * ent=readdir(dir);
@@ -196,9 +203,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.8 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2005/01/25 23:50:55 $
+ * $Date: 2005/08/05 21:55:43 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/CameraBehavior.h ./Behaviors/Demos/CameraBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/CameraBehavior.h	Wed Nov 10 20:45:35 2004
+++ ./Behaviors/Demos/CameraBehavior.h	Wed Nov 10 20:45:35 2004
@@ -61,7 +61,7 @@
  * @author ejt (rewrite for new vision system)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:35 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/ChaseBallBehavior.cc ./Behaviors/Demos/ChaseBallBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/ChaseBallBehavior.cc	Sat Oct 16 21:16:10 2004
+++ ./Behaviors/Demos/ChaseBallBehavior.cc	Sat Oct 16 21:16:10 2004
@@ -64,7 +64,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.11 $
  * $State: Exp $
  * $Date: 2004/10/17 01:16:10 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/ChaseBallBehavior.h ./Behaviors/Demos/ChaseBallBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/ChaseBallBehavior.h	Wed Nov 10 20:45:35 2004
+++ ./Behaviors/Demos/ChaseBallBehavior.h	Wed Nov 10 20:45:35 2004
@@ -37,7 +37,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:35 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/CrashTestBehavior.h ./Behaviors/Demos/CrashTestBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/CrashTestBehavior.h	Wed Nov 10 20:45:35 2004
+++ ./Behaviors/Demos/CrashTestBehavior.h	Wed Nov 10 20:45:35 2004
@@ -37,7 +37,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:35 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/DrawSkeletonBehavior.h ./Behaviors/Demos/DrawSkeletonBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/DrawSkeletonBehavior.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/DrawSkeletonBehavior.h	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,123 @@
+//-*-c++-*-
+#ifndef INCLUDED_DrawSkeletonBehavior_h_
+#define INCLUDED_DrawSkeletonBehavior_h_
+
+#include "Behaviors/BehaviorBase.h"
+#include "Events/EventRouter.h"
+
+#include "Shared/ProjectInterface.h"
+#include "Events/VisionObjectEvent.h"
+#include "Events/FilterBankEvent.h"
+#include "Vision/Graphics.h"
+#include "Shared/Config.h"
+#include "Vision/RawCameraGenerator.h"
+#include "Behaviors/Mon/RawCamBehavior.h"
+#include "Motion/Kinematics.h"
+#include "Shared/newmat/newmatio.h"
+
+//! Draws the kinematics "skeleton" on the camera frame
+class DrawSkeletonBehavior : public BehaviorBase {
+public:
+	//! constructor
+	DrawSkeletonBehavior() : BehaviorBase("DrawSkeletonBehavior") {}
+
+	virtual void DoStart() {
+		BehaviorBase::DoStart(); // do this first (required)
+		erouter->addListener(this, EventBase::visRawCameraEGID,ProjectInterface::visRawCameraSID,EventBase::statusETID);
+	}
+
+	virtual void DoStop() {
+		erouter->removeListener(this); //generally a good idea, unsubscribe all
+		BehaviorBase::DoStop(); // do this last (required)
+	}
+
+	virtual void processEvent(const EventBase& e) {
+		//We're assuming e is a filter bank event and that its source is not null...
+		//You could add error checking code for that.
+		const FilterBankEvent& fbe=dynamic_cast<const FilterBankEvent&>(e);
+
+		unsigned int chan=RawCameraGenerator::CHAN_U;
+		unsigned int layer=RawCamBehavior::getSourceLayer(chan,fbe.getNumLayers());
+		unsigned char color=48;
+		float originBoxSize=.1;
+		
+		Graphics g(*fbe.getSource(),layer,chan);
+		g.setColor(color);
+
+		NEWMAT::ColumnVector p=Kinematics::pack(0,0,0);
+		for(unsigned int leg=0; leg<NumLegs; leg++) {
+			float lastx,lasty,curx,cury;
+			bool lastFront=false;
+			bool front=getCameraPoint(LegOffset+leg*JointsPerLeg+ElevatorOffset,p,lastx,lasty);
+			if(front) {
+				g.setColor(-color);
+				g.drawRect(lastx-originBoxSize/2,lasty-originBoxSize/2,originBoxSize,originBoxSize);
+			}
+			for(unsigned int j=KneeOffset; j<JointsPerLeg; j++) {
+				//actually, there's only one more joint for this loop to process, but just for generality...
+				lastFront=front;
+				front=getCameraPoint(LegOffset+leg*JointsPerLeg+j,p,curx,cury);
+				if(lastFront) {
+					g.setColor(front?color:-color);
+					g.drawLine(lastx,lasty,curx,cury);
+				}
+				if(front) {
+					g.setColor(-color);
+					g.drawRect(curx-originBoxSize/2,cury-originBoxSize/2,originBoxSize,originBoxSize);
+				}
+				lastx=curx;
+				lasty=cury;
+			}
+			lastFront=front;
+			front=getCameraPoint(PawFrameOffset+leg,p,curx,cury);
+			if(lastFront) {
+				g.setColor(front?color:-color);
+				g.drawLine(lastx,lasty,curx,cury);
+			}
+			if(front) {
+				g.setColor(-color);
+				g.drawRect(curx-originBoxSize/2,cury-originBoxSize/2,originBoxSize,originBoxSize);
+			}
+			lastx=curx;
+			lasty=cury;
+		}
+	}
+
+	static std::string getClassDescription() { return "Draws the kinematics \"skeleton\" on the camera frame"; }
+	virtual std::string getDescription() const { return getClassDescription(); }
+	
+
+protected:
+	//! returns the @a x and @a y coordinates with the camera image corresponding to a point (@a p) in 3d space (relative to @a jointOffset)
+	bool getCameraPoint(unsigned int jointOffset, NEWMAT::ColumnVector& p, float& x, float& y) {
+		NEWMAT::Matrix T = kine->linkToJoint(jointOffset,CameraFrameOffset);
+		NEWMAT::ColumnVector o=T*p; //o is now the position of point p on the link, relative to the camera
+		bool front=o(3)>=0;
+		config->vision.computePixel(o(1),o(2),o(3),x,y);
+		//cout << jointOffset << ' ' << o.t() << " -> " << x << ' ' << y << endl;
+		return front;
+	}
+
+	
+private:
+	// Providing declarations for these functions will avoid a compiler warning if
+	// you have any class members which are pointers.  However, as it is, an error
+	// will result if you inadvertantly cause a call to either (which is probably
+	// a good thing, unless you really intended to copy/assign a behavior, in
+	// which case simply provide implementations for the functions)
+	DrawSkeletonBehavior(const DrawSkeletonBehavior&); //!< don't call (copy constructor)
+	DrawSkeletonBehavior& operator=(const DrawSkeletonBehavior&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines DrawSkeletonBehavior, which draws the kinematics "skeleton" on the camera frame
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/DrawVisObjBoundBehavior.h ./Behaviors/Demos/DrawVisObjBoundBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/DrawVisObjBoundBehavior.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/DrawVisObjBoundBehavior.h	Thu Aug  4 17:09:26 2005
@@ -0,0 +1,107 @@
+//-*-c++-*-
+#ifndef INCLUDED_DrawVisObjBoundBehavior_h_
+#define INCLUDED_DrawVisObjBoundBehavior_h_
+
+#include "Behaviors/BehaviorBase.h"
+#include "Events/EventRouter.h"
+#include "Shared/ProjectInterface.h"
+#include "Events/VisionObjectEvent.h"
+#include "Events/FilterBankEvent.h"
+#include "Vision/Graphics.h"
+#include "Shared/Config.h"
+#include "Vision/RawCameraGenerator.h"
+
+//! Draws a boundary box in camera frame around all detected vision object events
+class DrawVisObjBoundBehavior : public BehaviorBase {
+public:
+	//! constructor
+	DrawVisObjBoundBehavior() : BehaviorBase("DrawVisObjBoundBehavior"), objs(), drawn(0) {}
+
+	virtual void DoStart() {
+		BehaviorBase::DoStart(); // do this first (required)
+		erouter->addListener(this, EventBase::visObjEGID);
+		erouter->addListener(this, EventBase::visRawCameraEGID,ProjectInterface::visRawCameraSID,EventBase::statusETID);
+		erouter->addListener(this, EventBase::visSegmentEGID,ProjectInterface::visSegmentSID,EventBase::statusETID);
+		//This part isn't done -- we can't draw into RLE images until RLEGraphics is written
+		//  erouter->addListener(this, EventBase::visRLEEGID,ProjectInterface::visRLESID,EventBase::statusETID);
+	}
+
+	virtual void DoStop() {
+		erouter->removeListener(this); //generally a good idea, unsubscribe all
+		BehaviorBase::DoStop(); // do this last (required)
+	}
+
+	virtual void processEvent(const EventBase& e) {
+		if(e.getGeneratorID()==EventBase::visObjEGID) {
+			if(drawn>=2) {
+				objs.clear();
+				drawn=0;
+			}
+			if(e.getTypeID()!=EventBase::deactivateETID) {
+				const VisionObjectEvent& vis=dynamic_cast<const VisionObjectEvent&>(e);
+				Rect r={vis.getLeft(),vis.getTop(),vis.getWidth(),vis.getHeight()};
+				objs.push_back(r);
+			}
+		} else {
+			//cache current layer, channel, and pen color (depends on whether we're handling the seg cam or the raw cam
+			unsigned int layer, chan;
+			unsigned char color;
+			const FilterBankEvent& fbe=dynamic_cast<const FilterBankEvent&>(e);
+			if(e.getGeneratorID()==EventBase::visRawCameraEGID) {
+				layer=fbe.getNumLayers()-1-config->vision.rawcam_y_skip;
+				chan=RawCameraGenerator::CHAN_Y;
+				color=255;
+			} else if(e.getGeneratorID()==EventBase::visSegmentEGID) {
+				layer=fbe.getNumLayers()-1-config->vision.rlecam_skip;
+				chan=config->vision.rlecam_channel;
+				color=7;
+			}
+
+			//do the drawing
+			Graphics g(*fbe.getSource(),layer,chan);
+			g.setColor(color);
+			for(std::vector<Rect>::const_iterator it=objs.begin(); it!=objs.end(); ++it)
+				g.drawRect(it->x,it->y,it->w,it->h);
+			
+			//this is only needed until RLEGraphics is in place
+			//  in the mean time, we trigger the RLE generator to recompress the modified seg cam image
+			if(config->vision.rlecam_compression==Config::vision_config::COMPRESS_RLE)
+				ProjectInterface::defRLEGenerator->invalidateCaches();
+			
+			drawn++;
+		}
+	}
+
+	static std::string getClassDescription() { return "Draws a boundary box in camera frame around all detected vision object events"; }
+	virtual std::string getDescription() const { return getClassDescription(); }
+	
+
+protected:
+	//! a simple structure for storing bounding box info for each detected object
+	struct Rect {
+		float x; //!< left edge, in resolution-independent coordinates
+		float y; //!< top edge, in resolution-independent coordinates
+		float w; //!< width, in resolution-independent coordinates
+		float h; //!< height, in resolution-independent coordinates
+	};
+
+	std::vector<Rect> objs; //!< vector of boundary boxes from the current frame
+	unsigned int drawn; //!< a counter of the number of frames that have been updated, when this hits 2, the next vision object will clear the list
+	
+private:
+	DrawVisObjBoundBehavior(const DrawVisObjBoundBehavior&); //!< don't call (copy constructor)
+	DrawVisObjBoundBehavior& operator=(const DrawVisObjBoundBehavior&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines DrawVisObjBoundBehavior, which draws a boundary box in camera frame around all detected vision object events
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/08/04 21:09:26 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/DriveMeBehavior.cc ./Behaviors/Demos/DriveMeBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/DriveMeBehavior.cc	Tue Dec 21 16:49:50 2004
+++ ./Behaviors/Demos/DriveMeBehavior.cc	Wed Jun  1 01:47:45 2005
@@ -2,7 +2,7 @@
 #include "Motion/WalkMC.h"
 #include "Motion/MotionSequenceMC.h"
 #include "Motion/PostureEngine.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Events/EventRouter.h"
 #include "Events/EventBase.h"
 
@@ -26,7 +26,7 @@
 {
   // Construct the standing up motion that the aibo does after it's done moving
   stand->setTime(700); // 700 milliseconds to stand up
-  stand->setPose(PostureEngine("/ms/data/motion/stand.pos"));
+  stand->setPose(PostureEngine("stand.pos"));
 }
 
 void DriveMeBehavior::DoStart()
@@ -109,9 +109,9 @@
  * @author tss (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.10 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/12/21 21:49:50 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/DriveMeBehavior.h ./Behaviors/Demos/DriveMeBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/DriveMeBehavior.h	Tue Dec 21 15:29:07 2004
+++ ./Behaviors/Demos/DriveMeBehavior.h	Wed Jun  1 01:47:45 2005
@@ -5,7 +5,7 @@
 #include "Behaviors/BehaviorBase.h"
 #include "Motion/MotionManager.h"
 #include "Motion/MotionSequenceMC.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 
 //! A very simple behavior that asks the user for WalkMC walking parameters and a walk duration.
 /*! The AIBO walks accordingly and then stands up, then asks again. And so on and so on.\n
@@ -39,10 +39,10 @@
  * @author tss (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/12/21 20:29:07 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/ExploreMachine.cc ./Behaviors/Demos/ExploreMachine.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/ExploreMachine.cc	Fri Dec  3 19:10:38 2004
+++ ./Behaviors/Demos/ExploreMachine.cc	Fri Dec  3 19:10:38 2004
@@ -72,7 +72,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.1 $
  * $State: Exp $
  * $Date: 2004/12/04 00:10:38 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/ExploreMachine.h ./Behaviors/Demos/ExploreMachine.h
--- ../Tekkotsu_2.3/Behaviors/Demos/ExploreMachine.h	Mon Jan 24 17:23:46 2005
+++ ./Behaviors/Demos/ExploreMachine.h	Mon Jan 24 17:23:46 2005
@@ -47,7 +47,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.23 $
  * $State: Exp $
  * $Date: 2005/01/24 22:23:46 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/FlashIPAddrBehavior.cc ./Behaviors/Demos/FlashIPAddrBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/FlashIPAddrBehavior.cc	Fri Jan 28 19:56:58 2005
+++ ./Behaviors/Demos/FlashIPAddrBehavior.cc	Wed Jun  1 01:47:45 2005
@@ -5,7 +5,7 @@
 #include "Motion/LedEngine.h"
 #include "Shared/WorldState.h"
 #include "Shared/Config.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Wireless/Wireless.h"
 
 void FlashIPAddrBehavior::DoStart() {
@@ -180,8 +180,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.2 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
  * $State: Exp $
- * $Date: 2005/01/29 00:56:58 $
+ * $Date: 2005/06/01 05:47:45 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/FlashIPAddrBehavior.h ./Behaviors/Demos/FlashIPAddrBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/FlashIPAddrBehavior.h	Thu Jan 27 00:39:42 2005
+++ ./Behaviors/Demos/FlashIPAddrBehavior.h	Sun Aug  7 00:11:03 2005
@@ -6,7 +6,7 @@
 #include "Motion/MotionManager.h"
 #include "Motion/MotionSequenceMC.h"
 
-//! Displays IP address by flashing a series of numbers on the LED face panel
+//! Displays IP address by speaking the digits and flashing a series of numbers on the LED face panel
 /*! Will only run the display on DoStart() if the flash_on_start
  *  config variable is set.  Otherwise you will need to hold down the
  *  buttons specified by #button1 and #button2 to trigger the display.
@@ -36,7 +36,7 @@
 	virtual std::string getDescription() const { return getClassDescription(); }
 	
 protected:
-	typedef XLargeMotionSequenceMC MSMC_t;
+	typedef XLargeMotionSequenceMC MSMC_t; //!< used to flash the LEDs to report the IP address
 
 	void loadSounds();    //!< loads the numeric sounds into memory
 	void releaseSounds(); //!< releases the numeric sounds
@@ -58,10 +58,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.2 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2005/01/27 05:39:42 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/FollowHeadBehavior.h ./Behaviors/Demos/FollowHeadBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/FollowHeadBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/FollowHeadBehavior.h	Wed Nov 10 20:45:36 2004
@@ -54,7 +54,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/FreezeTestBehavior.h ./Behaviors/Demos/FreezeTestBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/FreezeTestBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/FreezeTestBehavior.h	Wed Nov 10 20:45:36 2004
@@ -42,7 +42,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/GroundPlaneBehavior.h ./Behaviors/Demos/GroundPlaneBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/GroundPlaneBehavior.h	Wed Dec 22 20:47:06 2004
+++ ./Behaviors/Demos/GroundPlaneBehavior.h	Wed Dec 22 20:47:06 2004
@@ -85,7 +85,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Exp $
  * $Date: 2004/12/23 01:47:06 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/HeadLevelBehavior.h ./Behaviors/Demos/HeadLevelBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/HeadLevelBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/HeadLevelBehavior.h	Wed Nov 10 20:45:36 2004
@@ -85,7 +85,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.10 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/HelloWorldBehavior.h ./Behaviors/Demos/HelloWorldBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/HelloWorldBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/HelloWorldBehavior.h	Wed Nov 10 20:45:36 2004
@@ -50,7 +50,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/KinematicSampleBehavior.h ./Behaviors/Demos/KinematicSampleBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/KinematicSampleBehavior.h	Wed Dec 22 20:47:06 2004
+++ ./Behaviors/Demos/KinematicSampleBehavior.h	Wed Jun  1 01:47:45 2005
@@ -6,7 +6,7 @@
 #include "Motion/PIDMC.h"
 #include "Motion/PostureMC.h"
 #include "Motion/MotionManager.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/roboop/robot.h"
 #include "Shared/Config.h"
 #include "Motion/Kinematics.h"
@@ -113,10 +113,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:06 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/KinematicSampleBehavior2.h ./Behaviors/Demos/KinematicSampleBehavior2.h
--- ../Tekkotsu_2.3/Behaviors/Demos/KinematicSampleBehavior2.h	Wed Dec 22 20:47:06 2004
+++ ./Behaviors/Demos/KinematicSampleBehavior2.h	Wed Jun  1 01:47:45 2005
@@ -6,7 +6,7 @@
 #include "Motion/PIDMC.h"
 #include "Motion/PostureMC.h"
 #include "Motion/MotionManager.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/roboop/robot.h"
 #include "Shared/Config.h"
 #include "Motion/Kinematics.h"
@@ -163,10 +163,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.12 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.13 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:06 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/LookForSoundBehavior.h ./Behaviors/Demos/LookForSoundBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/LookForSoundBehavior.h	Wed Dec 22 20:47:06 2004
+++ ./Behaviors/Demos/LookForSoundBehavior.h	Wed Dec 22 20:47:06 2004
@@ -74,7 +74,7 @@
  * @author Paris Smaragdis (paris AT media mit edu) (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Exp $
  * $Date: 2004/12/23 01:47:06 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/MCRepeater.h ./Behaviors/Demos/MCRepeater.h
--- ../Tekkotsu_2.3/Behaviors/Demos/MCRepeater.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/MCRepeater.h	Wed Jun  1 01:47:45 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_MCRepeater_h_
 
 #include "Behaviors/BehaviorBase.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/MotionManager.h"
 #include "Events/EventRouter.h"
 
@@ -46,10 +46,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/MotionStressTestBehavior.h ./Behaviors/Demos/MotionStressTestBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/MotionStressTestBehavior.h	Wed Dec 22 20:47:07 2004
+++ ./Behaviors/Demos/MotionStressTestBehavior.h	Sun Aug  7 00:11:03 2005
@@ -60,6 +60,7 @@
 		}
 	}
 
+	//! creates and adds a new MotionSequenceMC
 	void addMS(LegOrder_t leg,unsigned int delay=0) {
 		unsigned int index=leg*JointsPerLeg+RotatorOffset;
 		SharedObject<SmallMotionSequenceMC> ms;
@@ -87,10 +88,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/PaceTargetsMachine.cc ./Behaviors/Demos/PaceTargetsMachine.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/PaceTargetsMachine.cc	Fri Jan 21 17:50:33 2005
+++ ./Behaviors/Demos/PaceTargetsMachine.cc	Wed Aug  3 15:11:58 2005
@@ -8,30 +8,38 @@
 #include "Behaviors/Nodes/OutputNode.h"
 #include "Behaviors/Nodes/MotionSequenceNode.h"
 #include "Behaviors/Nodes/GroupNode.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 void PaceTargetsMachine::setup() {
 	StateNode::setup();
 
-	WalkNode * turnAround = new WalkNode(0,0,1);
+	const float turnAroundSpeed=1; //1 rad/sec
+	//explore and chase have their own built-in speeds
+
+	//*****  NODE SETUP *****//
+
+	//turns in place
+	WalkNode * turnAround = new WalkNode(0,0,turnAroundSpeed);
 	turnAround->setName(getName()+"::TurnAround");
 	addNode(turnAround);
 
+	//two nodes running together -- explore will wander around, panhead will look around
 	GroupNode * explGrp = new GroupNode(getName()+"::ExplGroup");
 	addNode(explGrp);
 	{
 		ExploreMachine * explore = new ExploreMachine(explGrp->getName()+"::Explore");
 		explGrp->addNode(explore);
-		SmallMotionSequenceNode * panhead = new SmallMotionSequenceNode(explGrp->getName()+"::PanHead","/ms/data/motion/pan_head.mot",true);
+		SmallMotionSequenceNode * panhead = new SmallMotionSequenceNode(explGrp->getName()+"::PanHead","pan_head.mot",true);
 		explGrp->addNode(panhead);
 	}
 
+	//follow the ball
 	WalkToTargetNode * chase = new WalkToTargetNode(ProjectInterface::visPinkBallSID);
 	chase->setName(getName()+"::Chase");
 	addNode(chase);
 
-	//starts out exploring
-	start=explGrp;
+
+	//*****  TRANSITION SETUP *****//
 
 	Transition * tmptrans=NULL;
 
@@ -48,7 +56,7 @@
 	tmptrans->setSound("fart.wav");
 	
 	//once you've turned around, explore
-	turnAround->addTransition(tmptrans=new TimeOutTrans(explGrp,3500));
+	turnAround->addTransition(tmptrans=new TimeOutTrans(explGrp,(unsigned int)(M_PI/turnAroundSpeed*1000))); //turn 180 degrees (aka PI radians)
 	tmptrans->setSound("barkmed.wav");
 	
 	//preload the sounds so we don't pause on tranisitions
@@ -56,6 +64,9 @@
 	sndman->LoadFile("barkmed.wav");
 	sndman->LoadFile("whimper.wav");
 	sndman->LoadFile("fart.wav");
+
+	//starts out exploring
+	start=explGrp;
 }
 
 void PaceTargetsMachine::DoStart() {
@@ -77,9 +88,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.16 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.18 $
  * $State: Exp $
- * $Date: 2005/01/21 22:50:33 $
+ * $Date: 2005/08/03 19:11:58 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/PaceTargetsMachine.h ./Behaviors/Demos/PaceTargetsMachine.h
--- ../Tekkotsu_2.3/Behaviors/Demos/PaceTargetsMachine.h	Mon Jan 24 17:23:46 2005
+++ ./Behaviors/Demos/PaceTargetsMachine.h	Mon Jan 24 17:23:46 2005
@@ -35,7 +35,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.9 $
  * $State: Exp $
  * $Date: 2005/01/24 22:23:46 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/RelaxBehavior.h ./Behaviors/Demos/RelaxBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/RelaxBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/RelaxBehavior.h	Wed Jun  1 01:47:45 2005
@@ -5,7 +5,7 @@
 #include <iostream>
 #include "Behaviors/BehaviorBase.h"
 #include "Motion/PIDMC.h"
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/MotionManager.h"
 
 using namespace std;
@@ -50,8 +50,8 @@
  * @author ejt (Modifications)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/06/01 05:47:45 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/SimpleChaseBallBehavior.h ./Behaviors/Demos/SimpleChaseBallBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/SimpleChaseBallBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/SimpleChaseBallBehavior.h	Tue May  3 12:30:29 2005
@@ -27,7 +27,7 @@
 	//! adds a headpointer and a walker, and a listens for vision events
 	virtual void DoStart() {
 		BehaviorBase::DoStart();
-		walker_id = motman->addPersistentMotion(SharedObject<WalkMC>()); //the 'false' prevents autopruning
+		walker_id = motman->addPersistentMotion(SharedObject<WalkMC>());
 		erouter->addListener(this,EventBase::visObjEGID);
 	}
 
@@ -41,10 +41,17 @@
 	//! sets the head to point at the object and sets the body to move where the head points
 	virtual void processEvent(const EventBase& event) {
 		if(event.getGeneratorID()==EventBase::visObjEGID && event.getTypeID()==EventBase::statusETID) {
-			//in case the head isn't pointing straight forward, we'll straife
+			//x and y are the direction to walk; positive x is forward and positive y is left
+			//so these calculations walk the direction the head is pointing (at 120 mm/sec)
 			float x=120.0f*cos(state->outputs[HeadOffset+PanOffset]);
 			float y=120.0f*sin(state->outputs[HeadOffset+PanOffset]);
+
+			//z is the amount to turn in radians; conveniently enough, we can use the
+			//x parameter from the vision event as the speed to turn -- you could
+			//scale this up or down to make it be more or less sensitive
 			float z=-static_cast<const VisionObjectEvent*>(&event)->getCenterX();
+
+			//now pass these values to the walk motion command:
 			MMAccessor<WalkMC>(walker_id)->setTargetVelocity(x,y,z);
 		}
 	}
@@ -58,10 +65,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.10 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/05/03 16:30:29 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/SoundTestBehavior.h ./Behaviors/Demos/SoundTestBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/SoundTestBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/SoundTestBehavior.h	Wed Jun  1 01:47:45 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_SoundTestBehavior_h_
 
 #include "Behaviors/BehaviorBase.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Shared/ERS210Info.h"
 #include "Shared/ERS220Info.h"
 #include "Shared/ERS7Info.h"
@@ -14,7 +14,7 @@
  *  up and then played successively once the chin button is released.
  *
  *  Notice that this doesn't preload all needed sounds:\n
- *  - @c barkmed.wav is listed in /ms/config/tekkotsu.cfg as a preloaded system sound
+ *  - @c barkmed.wav is listed in ms/config/tekkotsu.cfg as a preloaded system sound
  *  - @c growl.wav will be loaded before being played automatically - notice the
  *    hiccup this can cause.
  */
@@ -121,10 +121,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.12 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/StareAtBallBehavior.cc ./Behaviors/Demos/StareAtBallBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/StareAtBallBehavior.cc	Sat Oct 16 21:16:10 2004
+++ ./Behaviors/Demos/StareAtBallBehavior.cc	Wed Jun  1 01:47:45 2005
@@ -37,18 +37,17 @@
 
 	//cout << horiz << ' ' << vert << endl;
 
+	// Very simple visual servoing control -- move the head in the direction of the target
 	double tilt=state->outputs[HeadOffset+TiltOffset]-vert*M_PI/7;
 	double pan=state->outputs[HeadOffset+PanOffset]-horiz*M_PI/6;
-	if(tilt<DtoR(-70))
-		tilt=DtoR(-70);
-	if(tilt>DtoR(40))
-		tilt=DtoR(40);
-	if(pan>DtoR(80))
-		pan=DtoR(80);
-	if(pan<DtoR(-80))
-		pan=DtoR(-80);
 	HeadPointerMC * headpointer= (HeadPointerMC*)motman->checkoutMotion(headpointer_id);
+#ifdef TGT_ERS7
+	//on an ers-7, we want to set the nod joint to look up, since tilt can only look down
+	headpointer->setJoints(tilt,pan,outputRanges[HeadOffset+NodOffset][MaxRange]);
+#else
+	//on other models (we'll just assume ers-2xx), center the roll joint
 	headpointer->setJoints(tilt,pan,0);
+#endif
 	motman->checkinMotion(headpointer_id);
 }
 			
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/StareAtBallBehavior.h ./Behaviors/Demos/StareAtBallBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/StareAtBallBehavior.h	Thu Nov 11 19:05:03 2004
+++ ./Behaviors/Demos/StareAtBallBehavior.h	Thu Nov 11 19:05:03 2004
@@ -36,7 +36,7 @@
  * @author tss (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.6 $
  * $State: Exp $
  * $Date: 2004/11/12 00:05:03 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/StareAtPawBehavior.h ./Behaviors/Demos/StareAtPawBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/StareAtPawBehavior.h	Wed Dec 22 20:47:07 2004
+++ ./Behaviors/Demos/StareAtPawBehavior.h	Wed Dec 31 19:00:00 1969
@@ -1,102 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_StareAtPawBehavior_h_
-#define INCLUDED_StareAtPawBehavior_h_
-
-#include "Behaviors/BehaviorBase.h"
-#include "Motion/OldKinematics.h"
-#include "Motion/PIDMC.h"
-#include "Motion/HeadPointerMC.h"
-#include "Motion/MotionManager.h"
-#include "Shared/SharedObject.h"
-
-
-//! Uses CMPack kinematics to track the paw which last received a button press with the camera
-/*! This is the "old" way of doing things, using CMPack kinematics... compare to StareAtPawBehavior2 for new-style kinematics */
-class StareAtPawBehavior : public BehaviorBase {
-public:
-	//! constructor
-	StareAtPawBehavior()
-		: BehaviorBase("StareAtPawBehavior"), lastLeg(LFrLegOrder), pointID(MotionManager::invalid_MC_ID)
-	{ }
-
-	virtual void DoStart() {
-		BehaviorBase::DoStart(); // do this first
-		for(unsigned int i=0; i<NumHeadJoints; i++)
-			head_angles[i]=state->outputs[HeadOffset+i];
-		pointID=motman->addPersistentMotion(SharedObject<HeadPointerMC>());
-		erouter->addListener(this,EventBase::sensorEGID);
-		erouter->addListener(this,EventBase::buttonEGID);
-	}
-
-	virtual void DoStop() {
-		motman->removeMotion(pointID);
-		pointID=MotionManager::invalid_MC_ID;
-		erouter->removeListener(this);
-		BehaviorBase::DoStop(); // do this last
-	}
-
-	virtual void processEvent(const EventBase& e) {
-		if(e.getGeneratorID()==EventBase::buttonEGID) {
-
-			if(e.getSourceID()==LFrPawOffset)
-				lastLeg=LFrLegOrder;
-			else if(e.getSourceID()==RFrPawOffset)
-				lastLeg=RFrLegOrder;
-			else
-				return;
-			if(e.getTypeID()==EventBase::activateETID) {
-				unsigned int lastlegoff=LegOffset+lastLeg*JointsPerLeg;
-				SharedObject<PIDMC> relaxLeg(lastlegoff,lastlegoff+JointsPerLeg,0);
-				motman->addPrunableMotion(relaxLeg);
-			} else if(e.getTypeID()==EventBase::deactivateETID) {
-				unsigned int lastlegoff=LegOffset+lastLeg*JointsPerLeg;
-				SharedObject<PIDMC> tightLeg(lastlegoff,lastlegoff+JointsPerLeg,1);
-				motman->addPrunableMotion(tightLeg);
-			}
-
-		} else if(e.getGeneratorID()==EventBase::sensorEGID) {
-
-			double leg_angles[JointsPerLeg];
-			for(unsigned int i=0; i<JointsPerLeg; i++)
-				leg_angles[i]=state->outputs[LegOffset+lastLeg*JointsPerLeg+i];
-			vector3d paw;
-			GetLegPosition(paw,leg_angles,lastLeg);
-			paw-=body_to_neck; //target should be neck-relative
-			paw.z+=body_to_neck.z; // but body-height relative (#@%&$)
-			GetHeadAngles(head_angles,paw,0,0);
-			/*{
-				double tmp[JointsPerLeg];
-				GetLegAngles(tmp,paw,lastLeg);
-				sout->printf("Leg: (%g,%g,%g) (%g,%g,%g) (%g,%g,%g)\n",leg_angles[0],leg_angles[1],leg_angles[2],paw.x,paw.y,paw.z,tmp[0],tmp[1],tmp[2]);
-				vector3d tmp2;
-				tmp2=RunForwardModel(head_angles,0,0,vector3d(0,0,0));
-				sout->printf("Head: (%g,%g,%g) (%g,%g,%g) (%g,%g,%g)\n",tmp2.x,tmp2.y,tmp2.z,head_angles[0],head_angles[1],head_angles[2],state->outputs[HeadOffset+0],state->outputs[HeadOffset+1],state->outputs[HeadOffset+2]);
-				}*/
-			MMAccessor<HeadPointerMC>(pointID)->setJoints(head_angles[0],head_angles[1],head_angles[2]);
-			
-		} else {
-			serr->printf("StareAtPawBehavior: Unhandled event %s\n",e.getName().c_str());
-		}
-	}
-
-	static std::string getClassDescription() { return "Uses kinematics to track the paw which last received a button press with the camera"; }
-	virtual std::string getDescription() const { return getClassDescription(); }
-	
-protected:
-	LegOrder_t lastLeg; //!< last leg to have it's button pressed, i.e. the one we are looking at
-	MotionManager::MC_ID pointID; //!< the HeadPointerMC we are using to do the looking
-	double head_angles[JointsPerLeg]; //!< temporary storage of the head angles we desire
-};
-
-/*! @file
- * @brief Defines StareAtPawBehavior, which uses CMPack kinematics to track the paw which last received a button press with the camera
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
- * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
- */
-
-#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/StareAtPawBehavior2.cc ./Behaviors/Demos/StareAtPawBehavior2.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/StareAtPawBehavior2.cc	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/StareAtPawBehavior2.cc	Thu Aug  4 17:09:26 2005
@@ -0,0 +1,137 @@
+#include "StareAtPawBehavior2.h"
+
+#include "Events/EventRouter.h"
+#include "Shared/WorldState.h"
+#include "Motion/MMAccessor.h"
+#include "Motion/PIDMC.h"
+#include "Motion/HeadPointerMC.h"
+#include "Motion/PostureMC.h"
+#include "IPC/SharedObject.h"
+#include "Motion/roboop/robot.h"
+#include "Shared/Config.h"
+#include "Motion/Kinematics.h"
+
+// these are for drawing into the camera frame
+#include "Shared/ProjectInterface.h"
+#include "Vision/Graphics.h"
+#include "Events/FilterBankEvent.h"
+#include "Vision/RawCameraGenerator.h"
+#include "Behaviors/Mon/RawCamBehavior.h"
+
+//better to put this here instead of the header
+using namespace std; 
+
+void StareAtPawBehavior2::DoStart() {
+	BehaviorBase::DoStart(); // do this first
+
+	pointID=motman->addPersistentMotion(SharedObject<HeadPointerMC>());
+
+	//sensorEGID to update head pointer whenever we get new info about joint positions
+	erouter->addListener(this,EventBase::sensorEGID);
+	//buttonEGID to switch the target when the LFr or RFr button is pressed (ignores the others)
+	erouter->addListener(this,EventBase::buttonEGID);
+	//visRawCameraEGID to draw a dot on the camera image where we think the toe is
+	erouter->addListener(this,EventBase::visRawCameraEGID,ProjectInterface::visRawCameraSID,EventBase::statusETID);
+		
+	if(state->robotDesign == WorldState::ERS7Mask)
+		sout->printf("NOTICE: The ERS-7 has a rather \"sticky\" nod joint\n"
+								 "(the upper tilt joint).  This can cause it to hesitate\n"
+								 "or altogether fail to precisely center the target position\n"
+								 "vertically in the center of the image...\n");
+}
+
+void StareAtPawBehavior2::DoStop() {
+	motman->removeMotion(pointID);
+	pointID=MotionManager::invalid_MC_ID;
+	erouter->removeListener(this);
+	BehaviorBase::DoStop(); // do this last
+}
+	
+void StareAtPawBehavior2::processEvent(const EventBase& e) {
+	if(e.getGeneratorID()==EventBase::buttonEGID) {
+		//*******************************//
+		//*** Switch the "active" toe ***//
+		//*******************************//
+
+		if(e.getSourceID()==LFrPawOffset) {
+			lastLeg=LFrLegOrder;
+		} else if(e.getSourceID()==RFrPawOffset) {
+			lastLeg=RFrLegOrder;
+		} else
+			return;
+		if(e.getTypeID()==EventBase::activateETID) {
+			unsigned int lastlegoff=LegOffset+lastLeg*JointsPerLeg;
+			SharedObject<PIDMC> relaxLeg(lastlegoff,lastlegoff+JointsPerLeg,0);
+			motman->addPrunableMotion(relaxLeg);
+		} else if(e.getTypeID()==EventBase::deactivateETID) {
+			unsigned int lastlegoff=LegOffset+lastLeg*JointsPerLeg;
+			SharedObject<PIDMC> tightLeg(lastlegoff,lastlegoff+JointsPerLeg,1);
+			motman->addPrunableMotion(tightLeg);
+		}
+
+
+	} else if(e.getGeneratorID()==EventBase::sensorEGID) {
+		//***************************************************************************//
+		//*** Update the position of the head based on new information on the toe ***//
+		//***************************************************************************//
+
+		//Which paw do we want?
+		const char * ipname= (lastLeg==LFrLegOrder) ? "ToeLFrPaw" : "ToeRFrPaw";
+
+		//Ask kinematics for current location of that paw (this is the "objective" aka target)
+		NEWMAT::ColumnVector Pobj=kine->getJointInterestPoint(BaseFrameOffset,ipname);
+
+		//Now point the head there
+		MMAccessor<HeadPointerMC>(pointID)->lookAtPoint(Pobj(1),Pobj(2),Pobj(3)); //keep head as far away as possible
+		//Alternative method:
+		// MMAccessor<HeadPointerMC>(pointID)->lookAtPoint(Pobj(1),Pobj(2),Pobj(3),80); //keep head 80mm away
+
+
+	} else if(e.getGeneratorID()==EventBase::visRawCameraEGID) {
+		//**************************************************************//
+		//*** Draw into the camera frame to put a box around the toe ***//
+		//**************************************************************//
+			
+		//same as above, but get the toe position relative to the camera
+		const char * ipname= (lastLeg==LFrLegOrder) ? "ToeLFrPaw" : "ToeRFrPaw";
+		NEWMAT::ColumnVector Pobj=kine->getJointInterestPoint(CameraFrameOffset,ipname);
+		float x,y;
+		config->vision.computePixel(Pobj(1),Pobj(2),Pobj(3),x,y);
+		y*=config->vision.aspectRatio;
+		float r=atan2(10.f,sqrt(Pobj.SumSquare()))/CameraHorizFOV/2;
+			
+		//draw into the layer which will be sent to the gui
+		//not doing any error checking on the type of the event or its source... cross your fingers ;)
+		const FilterBankEvent& fbe=dynamic_cast<const FilterBankEvent&>(e);
+		unsigned chan=RawCameraGenerator::CHAN_Y;
+		unsigned int layer=RawCamBehavior::getSourceLayer(chan,fbe.getNumLayers());
+		Graphics g(*fbe.getSource(), layer, chan);
+		g.setColor(255);
+		g.drawRect(x-r,y-r,r*2,r*2);
+			
+		/*
+		//this method of drawing gets the pixel coordinates without applying
+		// camera calibration via config->vision.computePixel
+		g.setColor(192);
+		r=atan2(5.f,sqrt(Pobj.SumSquare()))/CameraHorizFOV/2; //draws a half-size rectangle
+		x=Pobj(1)/(Pobj(3)*tan(CameraHorizFOV/2));
+		y=Pobj(2)/(Pobj(3)*tan(CameraVertFOV/2));
+		y*=config->vision.aspectRatio;
+		g.drawRect(x-r,y-r,r*2,r*2);
+		*/
+
+	} else {
+		serr->printf("StareAtPawBehavior2: Unhandled event %s\n",e.getName().c_str());
+	}
+}
+
+/*! @file
+ * @brief Implements StareAtPawBehavior2, which uses new-style ROBOOP kinematics to track the paw which last received a button press with the camera
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/04 21:09:26 $
+ */
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/StareAtPawBehavior2.h ./Behaviors/Demos/StareAtPawBehavior2.h
--- ../Tekkotsu_2.3/Behaviors/Demos/StareAtPawBehavior2.h	Wed Dec 22 20:47:07 2004
+++ ./Behaviors/Demos/StareAtPawBehavior2.h	Thu Jul  7 16:25:56 2005
@@ -3,15 +3,7 @@
 #define INCLUDED_StareAtPawBehavior2_h_
 
 #include "Behaviors/BehaviorBase.h"
-#include "Motion/PIDMC.h"
-#include "Motion/HeadPointerMC.h"
-#include "Motion/PostureMC.h"
 #include "Motion/MotionManager.h"
-#include "Shared/SharedObject.h"
-#include "Motion/roboop/robot.h"
-#include "Shared/Config.h"
-#include "Motion/Kinematics.h"
-
 
 //! Uses new-style ROBOOP kinematics to track the paw which last received a button press with the camera
 class StareAtPawBehavior2 : public BehaviorBase {
@@ -21,61 +13,9 @@
 		: BehaviorBase("StareAtPawBehavior2"), lastLeg(LFrLegOrder), pointID(MotionManager::invalid_MC_ID)
 	{ }
 
-	virtual void DoStart() {
-		BehaviorBase::DoStart(); // do this first
-		pointID=motman->addPersistentMotion(SharedObject<HeadPointerMC>());
-		erouter->addListener(this,EventBase::sensorEGID);
-		erouter->addListener(this,EventBase::buttonEGID);
-		if(state->robotDesign == WorldState::ERS7Mask)
-			sout->printf("NOTICE: The ERS-7 has a rather \"sticky\" nod joint\n"
-									 "(the upper tilt joint).  This can cause it to hesitate\n"
-									 "or altogether fail to precisely center the target position\n"
-									 "vertically in the center of the image...\n");
-	}
-
-	virtual void DoStop() {
-		motman->removeMotion(pointID);
-		pointID=MotionManager::invalid_MC_ID;
-		erouter->removeListener(this);
-		BehaviorBase::DoStop(); // do this last
-	}
-
-	virtual void processEvent(const EventBase& e) {
-		if(e.getGeneratorID()==EventBase::buttonEGID) {
-
-			if(e.getSourceID()==LFrPawOffset) {
-				lastLeg=LFrLegOrder;
-			} else if(e.getSourceID()==RFrPawOffset) {
-				lastLeg=RFrLegOrder;
-			} else
-				return;
-			if(e.getTypeID()==EventBase::activateETID) {
-				unsigned int lastlegoff=LegOffset+lastLeg*JointsPerLeg;
-				SharedObject<PIDMC> relaxLeg(lastlegoff,lastlegoff+JointsPerLeg,0);
-				motman->addPrunableMotion(relaxLeg);
-			} else if(e.getTypeID()==EventBase::deactivateETID) {
-				unsigned int lastlegoff=LegOffset+lastLeg*JointsPerLeg;
-				SharedObject<PIDMC> tightLeg(lastlegoff,lastlegoff+JointsPerLeg,1);
-				motman->addPrunableMotion(tightLeg);
-			}
-
-		} else if(e.getGeneratorID()==EventBase::sensorEGID) {
-
-			//Which paw do we want?
-			const char * ipname= (lastLeg==LFrLegOrder) ? "ToeLFrPaw" : "ToeRFrPaw";
-
-			//Ask kinematics for current location of that paw (this is the "objective" aka target)
-			NEWMAT::ColumnVector Pobj=kine->getJointInterestPoint(BaseFrameOffset,ipname);
-
-			//Now point the head there
-			MMAccessor<HeadPointerMC>(pointID)->lookAtPoint(Pobj(1),Pobj(2),Pobj(3)); //keep head as far away as possible
-			//Alternative method:
-			// MMAccessor<HeadPointerMC>(pointID)->lookAtPoint(Pobj(1),Pobj(2),Pobj(3),80); //keep head 80mm away
-
-		} else {
-			serr->printf("StareAtPawBehavior2: Unhandled event %s\n",e.getName().c_str());
-		}
-	}
+	virtual void DoStart();
+	virtual void DoStop();
+	virtual void processEvent(const EventBase& e);
 
 	static std::string getClassDescription() { return "Uses kinematics to track the paw which last received a button press with the camera"; }
 	virtual std::string getDescription() const { return getClassDescription(); }
@@ -86,14 +26,14 @@
 };
 
 /*! @file
- * @brief Defines StareAtPawBehavior2, which uses new-style ROBOOP kinematics to track the paw which last received a button press with the camera
+ * @brief Describes StareAtPawBehavior2, which uses new-style ROBOOP kinematics to track the paw which last received a button press with the camera
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.18 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.21 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/07/07 20:25:56 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/StepTest.h ./Behaviors/Demos/StepTest.h
--- ../Tekkotsu_2.3/Behaviors/Demos/StepTest.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Demos/StepTest.h	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,75 @@
+//-*-c++-*-
+#ifndef INCLUDED_StepTest_h_
+#define INCLUDED_StepTest_h_
+
+#include "Behaviors/BehaviorBase.h"
+#include "Motion/WalkMC.h"
+#include "Motion/MotionManager.h"
+#include "Motion/MMAccessor.h"
+#include "Events/TextMsgEvent.h"
+#include "Wireless/Socket.h"
+
+//! tests taking a certain number of steps
+class StepTest : public BehaviorBase {
+public:
+	//! constructor
+	StepTest() : BehaviorBase("StepTest"), walk_id(MotionManager::invalid_MC_ID) {}
+
+	virtual void DoStart() {
+		BehaviorBase::DoStart(); // do this first
+		walk_id=motman->addPersistentMotion(SharedObject<WalkMC>());
+		erouter->addListener(this,EventBase::textmsgEGID);
+	}
+
+	virtual void DoStop() {
+		motman->removeMotion(walk_id);
+		walk_id=MotionManager::invalid_MC_ID;
+		erouter->removeListener(this);
+		BehaviorBase::DoStop(); // do this last
+	}
+
+	virtual void processEvent(const EventBase& e) {
+		const TextMsgEvent * txt = dynamic_cast<const TextMsgEvent*>(&e);
+		if(txt==NULL)
+			serr->printf("WARNING: Illegal event in StepTest '%s'\n",e.getName().c_str());
+		else {
+			std::string s=txt->getText();
+			if(s.find("StepTest ")==0) {
+				float dx,dy,da;
+				int n;
+				int numread=sscanf(s.c_str(),"StepTest %f %f %f %d",&dx,&dy,&da,&n);
+				//sout->printf("numread=%d: %f %f %f %d\n",numread,dx,dy,da,n);
+				if(numread==1) {
+					MMAccessor<WalkMC> walk_acc(walk_id);
+					walk_acc->setStepThreshold(dx);
+				} else if(numread<4) {
+					serr->printf("ERROR: StepTest needs four values 'dx dy da steps'\n");
+					return;
+				} else {
+					MMAccessor<WalkMC> walk_acc(walk_id);
+					walk_acc->setTargetDisplacement(dx*n,dy*n,da*n,n);
+					sout->printf("resulting velocity: %f %f %f\n",walk_acc->getTargetVelocity().x,walk_acc->getTargetVelocity().y,walk_acc->getTargetVelocity().z);
+				}
+			}
+		}
+	}
+
+	static std::string getClassDescription() { return "tests taking a certain number of steps"; }
+	virtual std::string getDescription() const { return getClassDescription(); }
+	
+protected:
+	MotionManager::MC_ID walk_id; //!< the WalkMC to use for the stepping
+};
+
+/*! @file
+ * @brief Defines StepTest, which tests taking a certain number of steps
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/ToggleHeadLightBehavior.h ./Behaviors/Demos/ToggleHeadLightBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/ToggleHeadLightBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/ToggleHeadLightBehavior.h	Wed Jun  1 01:47:45 2005
@@ -2,7 +2,7 @@
 #ifndef INCLUDED_ToggleHeadLightBehavior_h_
 #define INCLUDED_ToggleHeadLightBehavior_h_
 
-#include "Shared/SharedObject.h"
+#include "IPC/SharedObject.h"
 #include "Motion/PostureMC.h"
 #include "Shared/ERS220Info.h"
 
@@ -39,10 +39,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/06/01 05:47:45 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/WallTestBehavior.cc ./Behaviors/Demos/WallTestBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Demos/WallTestBehavior.cc	Tue Dec 21 18:51:15 2004
+++ ./Behaviors/Demos/WallTestBehavior.cc	Wed Jun  1 01:47:45 2005
@@ -12,28 +12,42 @@
 void
 WallTestBehavior::DoStart() {
 	BehaviorBase::DoStart(); // do this first
+	
+	// We'll set these two variables to the time at which we should
+	// start and stop recording ir values
 	int startrec,stoprec;
+	
+	// This motion sequence will rotate the head left, then right, then back to the middle.
 	SharedObject<SmallMotionSequenceMC> pan;
-	pan->setTime(startrec=reposTime);
+	// stand up, and move the head to the left, taking `reposTime` to do it
+	pan->setTime(startrec=reposTime); // reposTime is defined in the header file
 	pan->setPose(PostureEngine(config->motion.makePath("stand.pos").c_str()));
 	pan->setOutputCmd(HeadOffset+TiltOffset,0);
 	pan->setOutputCmd(HeadOffset+PanOffset,outputRanges[HeadOffset+PanOffset][MaxRange]);
 	pan->setOutputCmd(HeadOffset+RollOffset,0);
+	// now pan to the right, taking `panTime`
 	stoprec=pan->advanceTime(panTime);
 	pan->setOutputCmd(HeadOffset+TiltOffset,0);
 	pan->setOutputCmd(HeadOffset+PanOffset,outputRanges[HeadOffset+PanOffset][MinRange]);
 	pan->setOutputCmd(HeadOffset+RollOffset,0);
+	// center the head
 	pan->advanceTime(reposTime);
 	pan->setOutputCmd(HeadOffset+TiltOffset,0);
 	pan->setOutputCmd(HeadOffset+PanOffset,0);
 	pan->setOutputCmd(HeadOffset+RollOffset,0);
+	// this second repetition simply forces the head to stay still for a little longer
 	pan->advanceTime(reposTime);
 	pan->setOutputCmd(HeadOffset+TiltOffset,0);
 	pan->setOutputCmd(HeadOffset+PanOffset,0);
 	pan->setOutputCmd(HeadOffset+RollOffset,0);
+	// now we add the motion sequence to the motion manager
+	// this will cause it to start executing
 	motman->addPrunableMotion(pan);
-	erouter->addTimer(this,0,startrec+lagTime,false);
-	erouter->addTimer(this,1,stoprec+lagTime,false);
+	
+	// add timers to start and stop sensor recording at the
+	// times we stored in startrec and stoprec
+	erouter->addTimer(this,0,startrec+lagTime,false); // SID==0 start recording
+	erouter->addTimer(this,1,stoprec+lagTime,false);  // SID==1 stop recording
 }
 
 void
@@ -45,9 +59,18 @@
 void
 WallTestBehavior::processEvent(const EventBase& e) {
 	if(e.getGeneratorID()==EventBase::sensorEGID) {
+		// The ERS-7 has different IR sensors than the 2xx series
+		// So we need to do a bit of different code depending on the target model
 #ifdef TGT_ERS7
 		float nd = state->sensors[NearIRDistOffset];
-		if(false && nd<350) //force always use the far sensor - near is crappy(ier); without the 'false', would use either one
+		/* This code tried to be smart by picking between near or far
+		 * However, without additional calibration work, the two are
+		 * inconsistent.  Current calibration handles direction of the
+		 * beam, but we don't (yet) have any calibration of measurement
+		 * error due to sensor reading long (or short).
+		 * Instead, the following 'false' causes only the 'far' sensor
+		 * to be used */
+		if(false && nd<350)
 			usedNear.push_back(true);
 		else {
 			nd=state->sensors[FarIRDistOffset];
@@ -58,21 +81,29 @@
 #endif //not TGT_ERS7
 		float na = state->outputs[HeadOffset+PanOffset];
 		//cout << nd << ' ' << na << endl;
+		// Just store the measurements for later analysis
 		d.push_back(nd);
 		a.push_back(na);
 
 	} else if(e.getSourceID()==0) {
+		// must be a timer event -- SID 0 indicates start of recording
+		// so start subscribing to sensor events
 		erouter->addListener(this,EventBase::sensorEGID,SensorSourceID::UpdatedSID);
+
 	} else if(e.getSourceID()==1) {
+		// must be a timer event -- SID 1 indicates stop of recording
+		// so stop subscribing to sensor events
 		erouter->removeListener(this,EventBase::sensorEGID);
 				
 		PostureEngine pose;
 		pose.clear();
 		//float legheight=NEWMAT::ColumnVector(pose.getJointInterestPoint(BaseFrameOffset,"LFrPaw"))(3);
 
+		/* Extremely simplistic estimation.
+		 * Assumes all readings are relative to the center of head rotation */
 		cout << "Logging Non-Kinematic calculations to /data/raw_xy.txt" << endl;
 		{
-			ofstream rawxy("/ms/data/raw_xy.txt");
+			ofstream rawxy(config->portPath("data/raw_xy.txt").c_str());
 			if(!rawxy) {
 				cout << "Could not open file" << endl;
 			} else {
@@ -82,20 +113,24 @@
 			}
 		}
 
+		/* Less simplistic estimation.
+		 * Uses interest point information to determine location of
+		 * IR sensor from center of rotation, but doesn't make use
+		 * of information regarding direction of the beam */
 		cout << "Logging uncalibrated kinematic calculations to /data/k_xyz.txt" << endl;
-		//assumes IR is parallel to camera
 		{
-			ofstream kxys("/ms/data/k_xyz.txt");
+			ofstream kxys(config->portPath("data/k_xyz.txt").c_str());
 			if(!kxys) {
 				cout << "Could not open file" << endl;
 			} else {
+				// `off` will store the offset of the sensor from center of rotation
 #ifdef TGT_ERS7
 				cout << "Columns are:\tx\ty\tz\tis_using_near" << endl;
 				float off=NEWMAT::ColumnVector(pose.getJointInterestPoint(CameraFrameOffset,"NearIR"))(3);
 #else //not TGT_ERS7
 				cout << "Columns are:\tx\ty\tz" << endl;
 				float off=NEWMAT::ColumnVector(pose.getJointInterestPoint(CameraFrameOffset,"IR"))(3);
-#endif //not TGT_ERS7
+#endif //TGT_ERS7 check
 				for(unsigned int i=0; i<d.size(); i++) {
 					pose(HeadOffset+PanOffset)=a[i];
 					NEWMAT::ColumnVector hit=pose.jointToBase(CameraFrameOffset)*Kinematics::pack(0,0,d[i]+off);
@@ -103,14 +138,23 @@
 					kxys << hit(1) << '\t' << hit(2) << '\t' << hit(3) << '\t' << usedNear[i] << '\n';
 #else //not TGT_ERS7
 					kxys << hit(1) << '\t' << hit(2) << '\t' << hit(3) << '\n';
-#endif //not TGT_ERS7
+#endif //TGT_ERS7 check
 				}
 			}
 		}
 
+		/* Decent estimation.
+		 * Uses full kinematic information to determine 3D location
+		 * of the point in space being measured.  These measurements
+		 * can be then projected into the ground plane to get a more
+		 * accurate estimation from the walls.
+		 * However, still doesn't take into account any sensor error,
+		 * such as offsets or scaling issues. (unless such calibration
+		 * has been added into WorldState itself after the time of this
+		 * writing...) */
 		cout << "Logging calibrated kinematic calculations to /data/ck_xyz.txt" << endl;
 		{
-			ofstream ckxys("/ms/data/ck_xyz.txt");
+			ofstream ckxys(config->portPath("data/ck_xyz.txt").c_str());
 			if(!ckxys) {
 				cout << "Could not open file" << endl;
 			} else {
@@ -134,6 +178,9 @@
 		}
 
 		//find data regions
+		// This sections the angle of the head into left, forward,
+		// and right regions, which assumes the walls will be roughly
+		// orthogonal
 		unsigned int start[3];
 		unsigned int stop[3];
 		start[0]=stop[0]=0;
@@ -151,6 +198,7 @@
 			cout << start[i] << "-" << stop[i] << (i==2?"":", ");
 		cout << endl;
 
+		//now process each of those regions independently
 		for(int w=0; w<3; w++) {
 			cout << "Wall "<<w<<": ";
 			//convert radial coordinates to x,y coordinates
@@ -177,6 +225,11 @@
 				continue;
 			}
 
+
+			// Now that we've done some setup and sanity checking, do
+			// the actual linear least squares computation to fit a line
+			// There's two methods we'll test, one using QR factorization
+			// and the other using SVD decomposition.
 			float x0=0,x1=0;
 			TimeET t;
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/WallTestBehavior.h ./Behaviors/Demos/WallTestBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Demos/WallTestBehavior.h	Mon Nov 15 19:11:46 2004
+++ ./Behaviors/Demos/WallTestBehavior.h	Mon Nov 15 19:11:46 2004
@@ -46,7 +46,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Exp $
  * $Date: 2004/11/16 00:11:46 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/WorldStateVelDaemon.h ./Behaviors/Demos/WorldStateVelDaemon.h
--- ../Tekkotsu_2.3/Behaviors/Demos/WorldStateVelDaemon.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Demos/WorldStateVelDaemon.h	Wed Jun 29 18:00:03 2005
@@ -29,6 +29,7 @@
 
 	virtual void DoStop() {
 		erouter->removeListener(this);
+		erouter->removeTrapper(this);
 		BehaviorBase::DoStop(); // do this last
 	}
 
@@ -85,10 +86,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/06/29 22:00:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Demos/karmedbandit.h ./Behaviors/Demos/karmedbandit.h
--- ../Tekkotsu_2.3/Behaviors/Demos/karmedbandit.h	Thu Sep 18 18:40:27 2003
+++ ./Behaviors/Demos/karmedbandit.h	Thu Sep 18 18:40:27 2003
@@ -132,7 +132,7 @@
  * @author ejt (Creator)
  *
  * $Author: neilh $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Rel $
  * $Date: 2003/09/18 22:40:27 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/Aibo3DControllerBehavior.h ./Behaviors/Mon/Aibo3DControllerBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/Aibo3DControllerBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/Aibo3DControllerBehavior.h	Wed Nov 10 20:45:36 2004
@@ -131,7 +131,7 @@
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.6 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/CVS/Entries ./Behaviors/Mon/CVS/Entries
--- ../Tekkotsu_2.3/Behaviors/Mon/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/CVS/Entries	Wed Aug 10 11:03:18 2005
@@ -0,0 +1,31 @@
+/Aibo3DControllerBehavior.h/1.6/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/EStopControllerBehavior.cc/1.4/Thu Oct  7 19:07:04 2004//Ttekkotsu-2_4
+/EStopControllerBehavior.h/1.5/Fri Dec 10 23:18:10 2004//Ttekkotsu-2_4
+/EchoBehavior.cc/1.3/Mon Aug  1 23:17:59 2005//Ttekkotsu-2_4
+/EchoBehavior.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/HeadPointControllerBehavior.cc/1.8/Fri Jun 10 19:18:59 2005//Ttekkotsu-2_4
+/HeadPointControllerBehavior.h/1.5/Fri Jun 10 19:18:59 2005//Ttekkotsu-2_4
+/MicrophoneServer.cc/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/MicrophoneServer.h/1.2/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/RawCamBehavior.cc/1.21/Fri Jul 29 18:35:05 2005//Ttekkotsu-2_4
+/RawCamBehavior.h/1.15/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/RegionCamBehavior.cc/1.1/Fri Aug  5 19:44:22 2005//Ttekkotsu-2_4
+/RegionCamBehavior.h/1.1/Fri Aug  5 19:44:22 2005//Ttekkotsu-2_4
+/SegCamBehavior.cc/1.14/Fri Jul 29 18:35:04 2005//Ttekkotsu-2_4
+/SegCamBehavior.h/1.9/Fri Jul 29 18:35:05 2005//Ttekkotsu-2_4
+/SpeakerServer.cc/1.1/Fri Nov 12 22:07:39 2004//Ttekkotsu-2_4
+/SpeakerServer.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/SpiderMachineBehavior.cc/1.4/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/SpiderMachineBehavior.h/1.9/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/StewartPlatformBehavior.cc/1.2/Wed Jun  1 05:47:45 2005//Ttekkotsu-2_4
+/StewartPlatformBehavior.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/UPennWalkControllerBehavior.cc/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/UPennWalkControllerBehavior.h/1.1/Sat Apr 23 18:33:26 2005//Ttekkotsu-2_4
+/ViewWMVarsBehavior.h/1.3/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/WMMonitorBehavior.cc/1.3/Fri Apr 16 20:17:22 2004//Ttekkotsu-2_4
+/WMMonitorBehavior.h/1.9/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/WalkControllerBehavior.cc/1.10/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/WalkControllerBehavior.h/1.4/Thu Nov 11 01:45:36 2004//Ttekkotsu-2_4
+/WorldStateSerializerBehavior.cc/1.5/Mon Feb 21 08:05:57 2005//Ttekkotsu-2_4
+/WorldStateSerializerBehavior.h/1.6/Mon Feb 21 08:05:57 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/CVS/Repository ./Behaviors/Mon/CVS/Repository
--- ../Tekkotsu_2.3/Behaviors/Mon/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Behaviors/Mon
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/CVS/Root ./Behaviors/Mon/CVS/Root
--- ../Tekkotsu_2.3/Behaviors/Mon/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/CVS/Tag ./Behaviors/Mon/CVS/Tag
--- ../Tekkotsu_2.3/Behaviors/Mon/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/EStopControllerBehavior.cc ./Behaviors/Mon/EStopControllerBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/EStopControllerBehavior.cc	Thu Oct  7 15:07:04 2004
+++ ./Behaviors/Mon/EStopControllerBehavior.cc	Thu Oct  7 15:07:04 2004
@@ -72,7 +72,7 @@
  * @author tss (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Exp $
  * $Date: 2004/10/07 19:07:04 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/EStopControllerBehavior.h ./Behaviors/Mon/EStopControllerBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/EStopControllerBehavior.h	Fri Dec 10 18:18:10 2004
+++ ./Behaviors/Mon/EStopControllerBehavior.h	Fri Dec 10 18:18:10 2004
@@ -66,7 +66,7 @@
  * @author tss (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/12/10 23:18:10 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/EchoBehavior.cc ./Behaviors/Mon/EchoBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/EchoBehavior.cc	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/EchoBehavior.cc	Mon Aug  1 19:17:59 2005
@@ -0,0 +1,215 @@
+#include "EchoBehavior.h"
+#include "Wireless/Wireless.h"
+#include "Shared/string_util.h"
+#include "Events/TextMsgEvent.h"
+#include <vector>
+#include <string>
+
+using namespace std;
+
+EchoBehavior* EchoBehavior::theOne=NULL;
+unsigned short EchoBehavior::port=11011;
+const char * const EchoBehavior::routeNames[EchoBehavior::NUM_ROUTE] = 
+{
+	"TCP Server", "UDP Server","TCP Client","UDP Client"
+};
+
+void EchoBehavior::DoStart() {
+	BehaviorBase::DoStart(); // do this first (required)
+	setupNetwork();
+	erouter->addListener(this,EventBase::textmsgEGID);
+}
+
+void EchoBehavior::DoStop() {
+	erouter->removeListener(this);
+	teardownNetwork();
+	BehaviorBase::DoStop(); // do this last (required)
+}
+
+void EchoBehavior::setupNetwork() {
+	sockets[STCP]=wireless->socket(SocketNS::SOCK_STREAM);
+	sockets[SUDP]=wireless->socket(SocketNS::SOCK_DGRAM);
+	socks[STCP]=sockets[STCP]->sock;
+	socks[SUDP]=sockets[SUDP]->sock;
+	wireless->setDaemon(sockets[STCP],true);
+	wireless->setDaemon(sockets[SUDP],true);
+	wireless->setReceiver(sockets[STCP]->sock, server_callbackT);
+	wireless->setReceiver(sockets[SUDP]->sock, server_callbackU);
+	wireless->listen(sockets[STCP]->sock, port);
+	wireless->listen(sockets[SUDP]->sock, port);
+}
+
+void EchoBehavior::teardownNetwork() {
+	wireless->setDaemon(sockets[STCP],false);
+	wireless->setDaemon(sockets[SUDP],false);
+	wireless->close(sockets[STCP]);
+	wireless->close(sockets[SUDP]);
+	if(sockets[CTCP]!=NULL && wireless->isConnected(socks[CTCP]))
+		wireless->close(sockets[CTCP]);
+	if(sockets[CUDP]!=NULL && wireless->isConnected(socks[CUDP]))
+		wireless->close(sockets[CUDP]);
+	for(unsigned int i=0; i<NUM_ROUTE; i++)
+		sockets[i]=NULL;
+}
+
+void EchoBehavior::processEvent(const EventBase& e) {
+	//Check for connections which have just been closed
+	for(unsigned int i=0; i<NUM_ROUTE; i++)
+		if(sockets[i]!=NULL && !sockets[i]->getDaemon() && !wireless->isConnected(socks[i]))
+			sockets[i]=NULL;
+
+	//handle the event
+	if(const TextMsgEvent * msg = dynamic_cast<const TextMsgEvent*>(&e)) {
+		vector<string> args;
+		vector<unsigned int> offs;
+		string_util::parseArgs(msg->getText(),args,offs);
+		if(args.size()==0)
+			return;
+		if(args[0]=="open") {
+			if(args.size()<4) {
+				serr->printf("syntax: %s (tcp|udp) host port\n",args[0].c_str());
+				return;
+			}
+			if(string_util::makeLower(args[1])=="tcp") {
+				if(sockets[CTCP]==NULL) {
+					sockets[CTCP]=wireless->socket(SocketNS::SOCK_STREAM);
+					socks[CTCP]=sockets[CTCP]->sock;
+					wireless->setReceiver(sockets[CTCP], client_callbackT);
+				}
+				wireless->connect(sockets[CTCP],args[2].c_str(),atoi(args[3].c_str()));
+			} else if(string_util::makeLower(args[1])=="udp") {
+				if(sockets[CUDP]==NULL) {
+					sockets[CUDP]=wireless->socket(SocketNS::SOCK_DGRAM);
+					socks[CUDP]=sockets[CUDP]->sock;
+					wireless->setReceiver(sockets[CUDP], client_callbackU);
+				}
+				wireless->connect(sockets[CUDP],args[2].c_str(),atoi(args[3].c_str()));
+			} else {
+				serr->printf("syntax: %s (tcp|udp) host port\n",args[0].c_str());
+				serr->printf("  first argument '%s' must be either 'tcp' or 'udp'\n",args[1].c_str());
+				return;
+			}
+		} else if(args[0]=="status") {
+			cout << "Listening on port " << port << endl;
+			for(unsigned int i=0; i<NUM_ROUTE; i++)
+				cout << routeNames[i] << ": " << (sockets[i]!=NULL && wireless->isConnected(socks[i]) ? "Connected" : "Not Connected") << endl;
+			for(unsigned int i=0; i<NUM_ROUTE; i++) {
+				cout << "Route from " << routeNames[i] << ": ";
+				for(unsigned int j=0; j<NUM_ROUTE; j++)
+					cout << route[i][j] << ' ';
+				cout << endl;
+			}
+		} else if(args[0]=="relay" || args[0]=="unlink") {
+			unsigned char from=-1U;
+			unsigned char to=-1U;
+			bool val = (args[0]=="relay");
+			unsigned int i=1;
+			for(; i<args.size(); i++) {
+				if(string_util::makeLower(args[i])=="to")
+					break;
+				intersect(from,args[i]);
+			}
+			if(i==args.size()) {
+				serr->printf("syntax: %s [udp|tcp|client|server]* to [udp|tcp|client|server]*\n",args[0].c_str());
+				return;
+			}
+			i++;
+			for(; i<args.size(); i++)
+				intersect(to,args[i]);
+			for(unsigned int r=0; r<NUM_ROUTE; r++) {
+				if(from & (1<<r))
+					for(unsigned int j=0; j<NUM_ROUTE; j++)
+						if(to & (1<<j))
+							route[r][j]=val;
+			}
+		} else if(args[0]=="port") {
+			int p=atoi(args[1].c_str());
+			if(p==0) {
+				serr->printf("invalid port value\n");
+				return;
+			}
+			port=p;
+			teardownNetwork();
+			setupNetwork();
+		} else {
+			for(unsigned int i=0; i<NUM_ROUTE; i++)
+				if(sockets[i]!=NULL)
+					sockets[i]->printf("%s\n",msg->getText().c_str());
+		}
+	} else {
+		serr->printf("Bad event received: %s\n",e.getName().c_str());
+	}
+}
+
+void EchoBehavior::intersect(unsigned char& bits, std::string arg) {
+	arg=string_util::makeLower(arg);
+	unsigned char mask=0;
+	if(arg=="server")
+		mask = (1<<SUDP) | (1<<STCP) ;
+	else if(arg=="client")
+		mask = (1<<CUDP) | (1<<CTCP) ;
+	else if(arg=="tcp")
+		mask = (1<<STCP) | (1<<CTCP) ;
+	else if(arg=="udp")
+		mask = (1<<SUDP) | (1<<CUDP) ;
+	else
+		cerr << "Unknown argument '" << arg << "'" << endl;
+	bits&=mask;
+}
+
+void EchoBehavior::processCallback(EchoBehavior::routeIndex_t src, char *buf, int bytes) {
+	buf[bytes]='\0'; //hack - better hope it's not a full buffer
+	sout->printf("From %s:%d\n",sockets[src]->getPeerAddressAsString().c_str(),sockets[src]->getPeerPort());
+	sout->printf("Message is: '%s'\n",buf);
+	
+	//udp server doesn't automatically connect
+	if(src==SUDP && sockets[SUDP]!=NULL && !wireless->isConnected(socks[SUDP])) {
+		for(unsigned int i=0; i<NUM_ROUTE; i++)
+			if(route[i][SUDP]) {
+				//we found someone who wants to send output to the udp server, so we'd better connect it
+				wireless->connect(sockets[SUDP],sockets[SUDP]->getPeerAddressAsString().c_str(),sockets[SUDP]->getPeerPort());
+				break;
+			}
+	} 
+	
+	for(unsigned int i=0; i<NUM_ROUTE; i++) {
+		if(route[src][i] && sockets[i]!=NULL) {
+			if(wireless->isConnected(socks[i]))
+				sockets[i]->write((byte*)buf,bytes);
+			else if(!sockets[i]->getDaemon())
+				sockets[i]=NULL;
+		}
+	}
+}
+int EchoBehavior::server_callbackT(char *buf, int bytes) {
+	cout << "TCP Server received " << bytes << " bytes" << endl;
+	theOne->processCallback(STCP,buf,bytes);
+	return 0;
+}
+int EchoBehavior::client_callbackT(char *buf, int bytes) {
+	cout << "TCP Client received " << bytes << " bytes" << endl;
+	theOne->processCallback(CTCP,buf,bytes);
+	return 0;
+}
+int EchoBehavior::server_callbackU(char *buf, int bytes) {
+	cout << "UDP Server received " << bytes << " bytes" << endl;
+	theOne->processCallback(SUDP,buf,bytes);
+	return 0;
+}
+int EchoBehavior::client_callbackU(char *buf, int bytes) {
+	cout << "UDP Client received " << bytes << " bytes" << endl;
+	theOne->processCallback(CUDP,buf,bytes);
+	return 0;
+}
+
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/01 23:17:59 $
+ */
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/EchoBehavior.h ./Behaviors/Mon/EchoBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/EchoBehavior.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/EchoBehavior.h	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,82 @@
+//-*-c++-*-
+#ifndef INCLUDED_EchoBehavior_h_
+#define INCLUDED_EchoBehavior_h_
+
+#include "Behaviors/BehaviorBase.h"
+#include "Events/EventRouter.h"
+
+//! Waits for a connection, echos any data received back to the sender
+class EchoBehavior : public BehaviorBase {
+public:
+	static EchoBehavior * theOne; //!< the singleton object (only one of these objects can be active at a time or they would conflict over ports)
+	static unsigned short port; //! the port to listen on for incoming UDP and TCP connections
+	static int server_callbackT(char *buf, int bytes); //!< called by wireless when there's new data
+	static int client_callbackT(char *buf, int bytes); //!< called by wireless when there's new data
+	static int server_callbackU(char *buf, int bytes); //!< called by wireless when there's new data
+	static int client_callbackU(char *buf, int bytes); //!< called by wireless when there's new data
+	
+	//! constructor
+	EchoBehavior()
+		: BehaviorBase("EchoBehavior")
+	{
+			theOne=this;
+			bzero((char*)route,sizeof(route));
+			for(unsigned int i=0; i<NUM_ROUTE; i++) {
+				sockets[i]=NULL;
+				socks[i]=-1;
+				route[i][i]=true;				
+			}
+	}
+	~EchoBehavior() { theOne=NULL; }
+
+	virtual void DoStart();
+	virtual void DoStop();	
+	virtual void processEvent(const EventBase& e);
+	
+	static std::string getClassDescription() {
+		char tmp[20];
+		sprintf(tmp,"%d",port);
+		return std::string("Waits for a connection, echos any data received back to the sender, using port ")+tmp;
+	}
+	virtual std::string getDescription() const { return getClassDescription(); }
+
+protected:
+	enum routeIndex_t {
+		STCP=0,  //!< server TCP
+		SUDP, //!< server UDP
+		CTCP, //!< client TCP
+		CUDP, //!< client UDP
+		NUM_ROUTE //!< total number of different connections available
+	};
+	static const char * const routeNames[NUM_ROUTE]; //!< a user-readable name for each incoming or outgoing route
+
+	class Socket * sockets[NUM_ROUTE]; //!< an array of sockets, one for each incoming or outgoing route
+	int socks[NUM_ROUTE]; //!< the system socket number for each of #sockets, used to detect when a socket has been closed
+	bool route[NUM_ROUTE][NUM_ROUTE]; //!< a table of bools indicating how data should be echoed -- if route[from][to] is set, route it
+	void setupNetwork(); //!< initialize server ports
+	void teardownNetwork(); //!< close open connections
+	void processCallback(routeIndex_t src, char * buf, int bytes); //!< called by one of the wireless callbacks to do processing
+	void intersect(unsigned char& bits, std::string arg); //!< unsets bits of @a bits which aren't represented by @a arg
+	
+private:
+	// Providing declarations for these functions will avoid a compiler warning if
+	// you have any class members which are pointers.  However, as it is, an error
+	// will result if you inadvertantly cause a call to either (which is probably
+	// a good thing, unless you really intended to copy/assign a behavior, in
+	// which case simply provide implementations for the functions)
+	EchoBehavior(const EchoBehavior&); //!< don't call (copy constructor)
+	EchoBehavior& operator=(const EchoBehavior&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines EchoBehavior, which waits for a connection, echos any data received back to the sender
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/HeadPointControllerBehavior.cc ./Behaviors/Mon/HeadPointControllerBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/HeadPointControllerBehavior.cc	Sat Oct 16 21:16:10 2004
+++ ./Behaviors/Mon/HeadPointControllerBehavior.cc	Fri Jun 10 15:18:59 2005
@@ -44,17 +44,11 @@
 			head->setJoints(t,p,r);
 		}
 	}
-
-	// Reset the stop-if-no-heartbeat timer -- if we don't
-	// hear from the mothership in three seconds, stop immediately.
-	erouter->addTimer(this, 0, 3000, false);
 }
 
 void HeadPointControllerBehavior::DoStart() {
 	// Behavior startup
 	BehaviorBase::DoStart();
-	// We listen to timers
-	erouter->addListener(this, EventBase::timerEGID);
 	// Enable head control
 	head_id = motman->addPersistentMotion(SharedObject<HeadPointerMC>());
 	// Turn on wireless
@@ -124,9 +118,9 @@
  * @author tss (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/10/17 01:16:10 $
+ * $Date: 2005/06/10 19:18:59 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/HeadPointControllerBehavior.h ./Behaviors/Mon/HeadPointControllerBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/HeadPointControllerBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/HeadPointControllerBehavior.h	Fri Jun 10 15:18:59 2005
@@ -66,9 +66,6 @@
 
 	virtual void DoStop();
 
-	//! The only event we could possibly receive is the stop-if-no-heartbeat timer.
-	virtual void processEvent(const EventBase &) {}
-
 	static std::string getClassDescription() {
 		char tmp[20];
 		sprintf(tmp,"%d",config->main.headControl_port);
@@ -82,10 +79,10 @@
  * @author tss (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/06/10 19:18:59 $
  */
 
 #endif 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/MicrophoneServer.cc ./Behaviors/Mon/MicrophoneServer.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/MicrophoneServer.cc	Fri Nov 12 17:07:39 2004
+++ ./Behaviors/Mon/MicrophoneServer.cc	Sun Aug  7 00:11:03 2005
@@ -5,7 +5,10 @@
 #include "Shared/Config.h"
 #include "Wireless/Wireless.h"
 
-#include <OPENR/OPENRAPI.h>
+#include "Shared/ODataFormats.h"
+#ifdef PLATFORM_APERIOS
+#  include "OPENR/OPENRAPI.h"
+#endif
 
 MicrophoneServer* MicrophoneServer::instance = 0;
 const char* const MicrophoneServer::MIC_LOCATOR = "PRM:/r1/c1/c2/c3/m1-Mic:M1";
@@ -212,6 +215,7 @@
 	}
 }
 
+#ifdef PLATFORM_APERIOS
 bool MicrophoneServer::SetMicrophoneUnidirectional(bool unidirectional) {
 	OPrimitiveID micID;
 	OStatus result = OPENR::OpenPrimitive(MIC_LOCATOR, &micID);
@@ -224,10 +228,13 @@
 	if (result != oSUCCESS) {
 		return false;
 	}
-	
+#else
+bool MicrophoneServer::SetMicrophoneUnidirectional(bool /*unidirectional*/) {
+#endif
 	return true;
 }
 
+#ifdef PLATFORM_APERIOS
 bool MicrophoneServer::SetMicrophoneAlcEnabled(bool enabled) {
 	OPrimitiveID micID;
 	OStatus result = OPENR::OpenPrimitive(MIC_LOCATOR, &micID);
@@ -240,6 +247,8 @@
 	if (result != oSUCCESS) {
 		return false;
 	}
-	
+#else
+bool MicrophoneServer::SetMicrophoneAlcEnabled(bool /*enabled*/) {
+#endif	
 	return true;
 }
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/MicrophoneServer.h ./Behaviors/Mon/MicrophoneServer.h
--- ../Tekkotsu_2.3/Behaviors/Mon/MicrophoneServer.h	Fri Nov 12 17:07:39 2004
+++ ./Behaviors/Mon/MicrophoneServer.h	Sun Aug  7 00:11:03 2005
@@ -8,8 +8,9 @@
 //! Streams audio from the microphone over the network
 class MicrophoneServer : public BehaviorBase {
 	public:
+		//!enforces singleton status
 		static MicrophoneServer* GetInstance();
-		virtual ~MicrophoneServer();
+		virtual ~MicrophoneServer(); //!< destructor
 		
 		virtual void DoStart();
 		virtual void DoStop();
@@ -21,9 +22,9 @@
 	private:
 		static const unsigned int SEND_BUFFER_SIZE = 2048 + 16;
 	
-		MicrophoneServer();
-		MicrophoneServer(const MicrophoneServer& rhs);
-		MicrophoneServer& operator=(const MicrophoneServer& rhs);
+		MicrophoneServer(); //!< constructor
+		MicrophoneServer(const MicrophoneServer& rhs); //!< don't call
+		MicrophoneServer& operator=(const MicrophoneServer& rhs); //!< don't call
 		static MicrophoneServer* instance;
 		
 		unsigned int GetResampledFrameSize(
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/RawCamBehavior.cc ./Behaviors/Mon/RawCamBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/RawCamBehavior.cc	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/RawCamBehavior.cc	Fri Jul 29 14:35:05 2005
@@ -8,13 +8,12 @@
 #include "Shared/ProjectInterface.h"
 
 RawCamBehavior::RawCamBehavior()
-	: BehaviorBase("RawCamBehavior"), visRaw(NULL), packet(NULL), cur(NULL), avail(0), max_buf(0)
+	: BehaviorBase("RawCamBehavior"), visRaw(NULL), packet(NULL), cur(NULL), avail(0), max_buf(0), lastProcessedTime(0)
 {}
 
 void
 RawCamBehavior::DoStart() {
 	BehaviorBase::DoStart();
-	
 	std::vector<std::string> args;
 	args.push_back("raw");
 	char port[50];
@@ -37,14 +36,16 @@
 	
 	Controller::loadGUI("org.tekkotsu.mon.VisionGUI","RawVisionGUI",config->vision.rawcam_port,args);
 
-	erouter->addListener(this,EventBase::visRawCameraEGID,ProjectInterface::visRawCameraSID);
-	erouter->addListener(this,EventBase::visJPEGEGID,ProjectInterface::visColorJPEGSID);
-	erouter->addListener(this,EventBase::visJPEGEGID,ProjectInterface::visGrayscaleJPEGSID);
+	erouter->addListener(this,EventBase::visRawCameraEGID,ProjectInterface::visRawCameraSID,EventBase::deactivateETID);
+	erouter->addListener(this,EventBase::visJPEGEGID,ProjectInterface::visColorJPEGSID,EventBase::deactivateETID);
+	erouter->addListener(this,EventBase::visJPEGEGID,ProjectInterface::visGrayscaleJPEGSID,EventBase::deactivateETID);
 }
 
 void
 RawCamBehavior::DoStop() {
 	erouter->removeListener(this);
+	if(wireless->isConnected(visRaw->sock))
+		sendCloseConnectionPacket();
 	Controller::closeGUI("RawVisionGUI");
 
 	// this could be considered a bug in our wireless - if we don't setDaemon(...,false)
@@ -60,6 +61,9 @@
 		return;
 	const FilterBankEvent* fbke=dynamic_cast<const FilterBankEvent*>(&e);
 	ASSERTRET(fbke!=NULL,"unexpected event");
+	if ((get_time() - lastProcessedTime) < config->vision.rawcam_interval) {// not enough time has gone by
+	  return;
+	}
 	/* // turning these off enables individual channel compression
 		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE && e.getGeneratorID()!=EventBase::visRawCameraEGID)
 		return;
@@ -71,8 +75,45 @@
 	} else if(config->vision.rawcam_encoding==Config::vision_config::ENCODE_SINGLE_CHANNEL) {
 		bool succ=writeSingleChannel(*fbke);
 		ASSERTRET(succ,"serialization failed");
+	} else {
+		serr->printf("%s: Bad rawcam_encoding setting\n",getName().c_str());
+	}
+}
+
+unsigned int RawCamBehavior::getSourceLayer(unsigned int chan, unsigned int numLayers) {
+	if(config->vision.rawcam_encoding==Config::vision_config::ENCODE_SINGLE_CHANNEL) {
+		if(config->vision.rawcam_channel!=(int)chan)
+			return -1U;
+		return numLayers-1-config->vision.rawcam_y_skip;
+	}
+	// must be full-color
+	switch(chan) {
+	case RawCameraGenerator::CHAN_Y:
+		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_JPEG) {
+			if(config->vision.rawcam_y_skip-config->vision.rawcam_uv_skip == 1)
+				return numLayers-1-config->vision.rawcam_uv_skip;
+		}
+		return numLayers-1-config->vision.rawcam_y_skip;
+	case RawCameraGenerator::CHAN_U:
+	case RawCameraGenerator::CHAN_V:
+		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_JPEG) {
+			if(config->vision.rawcam_uv_skip-config->vision.rawcam_y_skip == 1)
+				return numLayers-1-config->vision.rawcam_y_skip;
+		}
+		return numLayers-1-config->vision.rawcam_uv_skip;
+	default: // other channels, i.e. Y-derivatives
+		return -1U;
 	}
 }
+unsigned int RawCamBehavior::getSourceYLayer(unsigned int numLayers) {
+	return getSourceLayer(RawCameraGenerator::CHAN_Y,numLayers);
+}
+unsigned int RawCamBehavior::getSourceULayer(unsigned int numLayers) {
+	return getSourceLayer(RawCameraGenerator::CHAN_U,numLayers);
+}
+unsigned int RawCamBehavior::getSourceVLayer(unsigned int numLayers) {
+	return getSourceLayer(RawCameraGenerator::CHAN_V,numLayers);
+}
 
 bool
 RawCamBehavior::openPacket(FilterBankGenerator& fbkgen, unsigned int time, unsigned int layer) {
@@ -121,8 +162,8 @@
 	unsigned int uv_layer=fbkgen.getNumLayers()-1-config->vision.rawcam_uv_skip;
 
 	if(config->vision.rawcam_channel==-1) {
-		if(NULL!=dynamic_cast<const RawCameraGenerator*>(&fbkgen) && config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE
-			 || NULL!=dynamic_cast<const JPEGGenerator*>(&fbkgen) && config->vision.rawcam_compression==Config::vision_config::COMPRESS_JPEG) {
+		if(e.getGeneratorID()==EventBase::visRawCameraEGID && config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE
+			 || e.getGeneratorID()==EventBase::visJPEGEGID && config->vision.rawcam_compression==Config::vision_config::COMPRESS_JPEG) {
 			if(const JPEGGenerator* jgen=dynamic_cast<const JPEGGenerator*>(&fbkgen))
 				if(jgen->getCurrentSourceFormat()==JPEGGenerator::SRC_COLOR)
 					return true;
@@ -170,38 +211,7 @@
 		big_layer=uv_layer;
 		small_layer=y_layer;
 	}
-	if(dynamic_cast<const RawCameraGenerator*>(&fbkgen)) {
-		unsigned int used=0;
-		bool opened=false;
-
-		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE || big_layer-small_layer>=2 && big_layer==uv_layer) {
-			opened=openPacket(fbkgen,e.getTimeStamp(),big_layer);
-			ASSERTRETVAL(cur!=NULL,"header failed",false);
-			
-			fbkgen.selectSaveImage(y_layer,RawCameraGenerator::CHAN_Y);
-			used=fbkgen.SaveBuffer(cur,avail);
-			ASSERTRETVAL(used!=0,"save image failed",false);
-			avail-=used; cur+=used;
-		}
-
-		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE || big_layer-small_layer>=2 && big_layer==y_layer) {
-			opened=openPacket(fbkgen,e.getTimeStamp(),big_layer);
-			ASSERTRETVAL(cur!=NULL,"header failed",false);
-			
-			fbkgen.selectSaveImage(uv_layer,RawCameraGenerator::CHAN_U);
-			used=fbkgen.SaveBuffer(cur,avail);
-			ASSERTRETVAL(used!=0,"save image failed",false);
-			avail-=used; cur+=used;
-			
-			fbkgen.selectSaveImage(uv_layer,RawCameraGenerator::CHAN_V);
-			used=fbkgen.SaveBuffer(cur,avail);
-			ASSERTRETVAL(used!=0,"save image failed",false);
-			avail-=used; cur+=used;
-		}
-
-		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE || !opened)
-			closePacket();
-	} else if(const JPEGGenerator* jgen=dynamic_cast<const JPEGGenerator*>(&fbkgen)) {
+	if(const JPEGGenerator* jgen=dynamic_cast<const JPEGGenerator*>(&fbkgen)) {
 		if(config->vision.rawcam_compression!=Config::vision_config::COMPRESS_JPEG)
 			return true;
 		if(jgen->getCurrentSourceFormat()==JPEGGenerator::SRC_COLOR && big_layer-small_layer<2) {
@@ -240,16 +250,47 @@
 			if(!opened)
 				closePacket();
 		}
+	} else {
+		unsigned int used=0;
+		bool opened=false;
+		
+		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE || big_layer-small_layer>=2 && big_layer==uv_layer) {
+			opened=openPacket(fbkgen,e.getTimeStamp(),big_layer);
+			ASSERTRETVAL(cur!=NULL,"header failed",false);
+			
+			fbkgen.selectSaveImage(y_layer,RawCameraGenerator::CHAN_Y);
+			used=fbkgen.SaveBuffer(cur,avail);
+			ASSERTRETVAL(used!=0,"save image failed",false);
+			avail-=used; cur+=used;
+		}
+		
+		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE || big_layer-small_layer>=2 && big_layer==y_layer) {
+			opened=openPacket(fbkgen,e.getTimeStamp(),big_layer);
+			ASSERTRETVAL(cur!=NULL,"header failed",false);
+			
+			fbkgen.selectSaveImage(uv_layer,RawCameraGenerator::CHAN_U);
+			used=fbkgen.SaveBuffer(cur,avail);
+			ASSERTRETVAL(used!=0,"save image failed",false);
+			avail-=used; cur+=used;
+			
+			fbkgen.selectSaveImage(uv_layer,RawCameraGenerator::CHAN_V);
+			used=fbkgen.SaveBuffer(cur,avail);
+			ASSERTRETVAL(used!=0,"save image failed",false);
+			avail-=used; cur+=used;
+		}
+		
+		if(config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE || !opened)
+			closePacket();
 	}
-
+	
 	return true;
 }
 
 bool
 RawCamBehavior::writeSingleChannel(const FilterBankEvent& e) {
 	FilterBankGenerator& fbkgen=*e.getSource();
-	if( config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE && dynamic_cast<const RawCameraGenerator*>(&fbkgen)
-			|| config->vision.rawcam_compression==Config::vision_config::COMPRESS_JPEG && dynamic_cast<const JPEGGenerator*>(&fbkgen) )
+	if( config->vision.rawcam_compression==Config::vision_config::COMPRESS_NONE && e.getGeneratorID()==EventBase::visRawCameraEGID
+			|| config->vision.rawcam_compression==Config::vision_config::COMPRESS_JPEG && e.getGeneratorID()==EventBase::visJPEGEGID )
 		{
 			if(const JPEGGenerator * jgen=dynamic_cast<const JPEGGenerator*>(&fbkgen))
 				if(jgen->getCurrentSourceFormat()!=JPEGGenerator::SRC_GRAYSCALE)
@@ -285,6 +326,19 @@
 	*/
 	packet=cur=NULL;
 	avail=0;
+	lastProcessedTime = get_time();
+}
+
+bool
+RawCamBehavior::sendCloseConnectionPacket() {
+	char msg[]="CloseConnection";
+	unsigned int len=strlen(msg)+LoadSave::stringpad;
+	char * buf = (char*)visRaw->getWriteBuffer(len);
+	ASSERTRETVAL(buf!=NULL,"Could not get buffer for closing packet",false);
+	unsigned int used=LoadSave::encode(msg,buf,len);
+	ASSERTRETVAL(used!=0,"Could not write close packet",false);
+	visRaw->write(used);
+	return true;
 }
 
 
@@ -293,9 +347,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.15 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.21 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/07/29 18:35:05 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/RawCamBehavior.h ./Behaviors/Mon/RawCamBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/RawCamBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/RawCamBehavior.h	Sun Aug  7 00:11:03 2005
@@ -12,7 +12,8 @@
 //! Forwards images from camera over wireless
 /*! The format used for serialization is basically defined by the
  *  subclass of FilterBankGenerator being used.  I suggest looking at
- *  that classes's documentation to determine the format used.
+ *  that classes's documentation to determine the format used. (Generally
+ *  either RawCameraGenerator or JPEGGenerator)
  *
  *  However, RawCamBehavior will add a few fields at the beginning of
  *  each packet to assist in processing the image stream.
@@ -26,7 +27,16 @@
  *  - <@c unsigned @c int: timestamp> <i>(time image was taken, milliseconds since boot)</i>
  *  - <@c unsigned @c int: framenumber> <i>(incremented for each frame, so we can tell if/when we drop one)</i>
  *
+ *  Alternatively, RawCameraGenerator may send a "Close Connection" packet
+ *  when the server is shutting down.  This is to help UDP connections, which
+ *  otherwise wouldn't realize that they need to start trying to reconnect.
+ *  - <@c string:"CloseConnection">
+ *  
  *  This is exactly the same protocol that is followed by the SegCamBehavior as well - the same code can parse either stream.
+ *
+ *  This is a binary protocol -- the fields listed indicate binary values
+ *  in the AIBO's byte order (little endian).  Strings are encoded using
+ *  the LoadSave::encode(char*,unsigned int, unsigned int) method.
  */ 
 class RawCamBehavior : public BehaviorBase {
 public:
@@ -44,10 +54,15 @@
 
 	static std::string getClassDescription() {
 		char tmp[20];
-		sprintf(tmp,"%d",config->vision.rle_port);
+		snprintf(tmp,20,"%d",config->vision.rawcam_port); tmp[19]='\0';
 		return std::string("Forwards images from camera over port ")+tmp;
 	}
 	virtual std::string getDescription() const { return getClassDescription(); }
+
+	static unsigned int getSourceLayer(unsigned int chan, unsigned int numLayers); //!< returns the layer which will be used out of the source, based on current ::config settings (i.e. compression, skip, etc)
+	static unsigned int getSourceYLayer(unsigned int numLayers); //!< returns the layer which will be used out of the source, based on current ::config settings (i.e. compression, skip, etc)
+	static unsigned int getSourceULayer(unsigned int numLayers); //!< returns the layer which will be used out of the source, based on current ::config settings (i.e. compression, skip, etc)
+	static unsigned int getSourceVLayer(unsigned int numLayers); //!< returns the layer which will be used out of the source, based on current ::config settings (i.e. compression, skip, etc)
 	
 protected:
 	//! opens a new packet, writes header info; returns true if open, false if otherwise open (check cur==NULL for error)
@@ -57,12 +72,15 @@
 	bool writeSingleChannel(const FilterBankEvent& fbke); //!< writes a single channel
 	void closePacket(); //!< closes and sends a packet, does nothing if no packet open
 
+	//! sends a packet signaling the server is closing the connection (good for UDP connections)
+	bool sendCloseConnectionPacket();
+		
 	Socket * visRaw; //!< socket for sending the image stream
 	char * packet; //!< point to the current buffer being prepared to be sent
 	char * cur; //!< current location within that buffer
 	unsigned int avail; //!< the number of bytes remaining in the buffer
 	unsigned int max_buf; //!< the buffer size requested from Wireless when the socket was allocated
-
+	unsigned int lastProcessedTime; //!< the time that the last event was processed
 private:
 	RawCamBehavior(const RawCamBehavior&); //!< don't call
 	RawCamBehavior& operator=(const RawCamBehavior&); //!< don't call
@@ -73,10 +91,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.10 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/RegionCamBehavior.cc ./Behaviors/Mon/RegionCamBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/RegionCamBehavior.cc	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/RegionCamBehavior.cc	Fri Aug  5 15:44:22 2005
@@ -0,0 +1,152 @@
+#include "RegionCamBehavior.h"
+#include "Wireless/Wireless.h"
+#include "Events/EventRouter.h"
+#include "Events/FilterBankEvent.h"
+#include "Behaviors/Controller.h"
+#include "Shared/ProjectInterface.h"
+#include "Vision/SegmentedColorGenerator.h"
+#include "Vision/RegionGenerator.h"
+
+RegionCamBehavior::RegionCamBehavior()
+	: BehaviorBase("RegionCamBehavior"), visRegion(NULL), packet(NULL), cur(NULL), avail(0), max_buf(0)
+{
+}
+
+void
+RegionCamBehavior::DoStart() {
+	BehaviorBase::DoStart();
+	
+	std::vector<std::string> args;
+	args.push_back("reg"); 
+	char port[50];
+	snprintf(port,50,"%d",config->vision.region_port);
+	args.push_back(port);
+	if(config->vision.region_transport==0) {
+		max_buf=UDP_WIRELESS_BUFFER_SIZE;
+		visRegion=wireless->socket(SocketNS::SOCK_DGRAM, 1024, max_buf);
+		args.push_back("udp");
+	} else if(config->vision.region_transport==1) {
+		max_buf=TCP_WIRELESS_BUFFER_SIZE;
+		visRegion=wireless->socket(SocketNS::SOCK_STREAM, 1024, max_buf);
+		wireless->setDaemon(visRegion,true);
+		args.push_back("tcp");
+	} else {
+		serr->printf("ERROR: Invalid Config::vision.region_transport: %d\n",config->vision.region_transport);
+		return;
+	}
+	wireless->listen(visRegion,config->vision.region_port);
+	Controller::loadGUI("org.tekkotsu.mon.VisionGUI","RegionVisionGUI",config->vision.region_port,args);
+
+	erouter->addListener(this,EventBase::visRegionEGID,ProjectInterface::visRegionSID);
+}
+
+void
+RegionCamBehavior::DoStop() {
+	erouter->removeListener(this);
+	Controller::closeGUI("RegionVisionGUI");
+
+	// this could be considered a bug in our wireless - if we don't setDaemon(...,false)
+	// it will try to listen again even though we explicitly closed the server socket...
+	wireless->setDaemon(visRegion,false);
+	wireless->close(visRegion->sock);
+	BehaviorBase::DoStop();
+}
+
+void
+RegionCamBehavior::processEvent(const EventBase& e) {
+	if(!wireless->isConnected(visRegion->sock))
+		return;
+	const FilterBankEvent* fbke=dynamic_cast<const FilterBankEvent*>(&e);
+	ASSERTRET(fbke!=NULL,"unexpected event");
+		bool succ=writeRegions(*fbke);
+		ASSERTRET(succ,"serialization failed");
+}
+
+bool
+RegionCamBehavior::openPacket(FilterBankGenerator& fbkgen, unsigned int time, unsigned int layer) {
+	if(packet!=NULL)
+		return false;
+
+	avail=max_buf-1; //not sure why -1, but Alok had it, so i will too
+	ASSERT(cur==NULL,"cur non-NULL");
+	cur=NULL;
+	char * buf=packet=(char*)visRegion->getWriteBuffer(avail);
+	ASSERTRETVAL(packet!=NULL,"could not get buffer",false);
+	
+	unsigned int used;
+	used=LoadSave::encode("TekkotsuImage",buf,avail);
+	ASSERTRETVAL(used!=0,"ran out of space",false);
+	avail-=used; buf+=used;
+	used=LoadSave::encode(Config::vision_config::ENCODE_SINGLE_CHANNEL,buf,avail);
+	ASSERTRETVAL(used!=0,"ran out of space",false);
+	avail-=used; buf+=used;
+	used=LoadSave::encode(Config::vision_config::COMPRESS_RLE,buf,avail);
+	ASSERTRETVAL(used!=0,"ran out of space",false);
+	avail-=used; buf+=used;
+
+	used=LoadSave::encode(fbkgen.getWidth(layer),buf,avail);
+	ASSERTRETVAL(used!=0,"ran out of space",false);
+	avail-=used; buf+=used;
+	used=LoadSave::encode(fbkgen.getHeight(layer),buf,avail);
+	ASSERTRETVAL(used!=0,"ran out of space",false);
+	avail-=used; buf+=used;
+	used=LoadSave::encode(time,buf,avail);
+	ASSERTRETVAL(used!=0,"ran out of space",false);
+	avail-=used; buf+=used;
+	used=LoadSave::encode(fbkgen.getFrameNumber(),buf,avail);
+	ASSERTRETVAL(used!=0,"ran out of space",false);
+	avail-=used; buf+=used;
+
+	cur=buf;
+	return true;
+}
+
+bool
+RegionCamBehavior::writeRegions(const FilterBankEvent& e) {
+	FilterBankGenerator& fbkgen=*e.getSource();
+
+	unsigned int layer=fbkgen.getNumLayers()-1-config->vision.regioncam_skip;
+	unsigned int used=0;
+	openPacket(fbkgen,e.getTimeStamp(),layer);
+	ASSERTRETVAL(cur!=NULL,"header failed",false);
+	
+	RegionGenerator * regGen = dynamic_cast<RegionGenerator*>(&fbkgen);
+	ASSERTRETVAL(regGen!=NULL,"fbkgen isn't an RegionGenerator",false);
+
+	regGen->selectSaveImage(layer,config->vision.rlecam_channel);
+	used=regGen->SaveBuffer(cur,avail);
+	ASSERTRETVAL(used!=0,"save region image failed",false);
+	avail-=used; cur+=used;
+	
+	const SegmentedColorGenerator * seg = dynamic_cast<const SegmentedColorGenerator*>((regGen->getSourceGenerator())->getSourceGenerator()); //Get the source of his source (the SegmentedColorGenerator)
+	ASSERTRETVAL(seg!=NULL,"The source of RegionGenerator's source is not a SegmentedColorGenerator - how do i know what the colors are?",false);
+	if(0==(used=seg->encodeColors(cur,avail))) return false;
+	avail-=used; cur+=used;
+
+	closePacket();
+
+	return true;
+}
+
+
+void
+RegionCamBehavior::closePacket() {
+	if(packet==NULL)
+		return;
+	visRegion->write(cur-packet);
+	packet=cur=NULL;
+	avail=0;
+}
+
+
+/*! @file
+ * @brief Implements RegionCamBehavior, which forwards the regions from RegionGenerator over wireless
+ * @author harm & niels (Creators)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.1 $
+ * $State: Exp $
+ * $Date: 2005/08/05 19:44:22 $
+ */
+
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/RegionCamBehavior.h ./Behaviors/Mon/RegionCamBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/RegionCamBehavior.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/RegionCamBehavior.h	Fri Aug  5 15:44:22 2005
@@ -0,0 +1,64 @@
+//-*-c++-*-
+#ifndef INCLUDED_RegionCamBehavior_h_
+#define INCLUDED_RegionCamBehavior_h_
+
+#include "Behaviors/BehaviorBase.h"
+#include "Shared/Config.h"
+
+class Socket;
+class FilterBankGenerator;
+class FilterBankEvent;
+
+//! Forwards segmented images from camera over wireless
+
+class RegionCamBehavior : public BehaviorBase {
+public:
+	//! constructor
+	RegionCamBehavior();
+
+	static const unsigned int TCP_WIRELESS_BUFFER_SIZE=85000; //!< 85000 bytes for use up to 416x320 pixels / 8 min expected runs * 5 bytes per run + some padding
+	static const unsigned int UDP_WIRELESS_BUFFER_SIZE=64*1024; //!< 64KB is the max udp packet size
+
+	virtual void DoStart();
+
+	virtual void DoStop();
+
+	virtual void processEvent(const EventBase& e);
+
+	static std::string getClassDescription() {
+		char tmp[20];
+		sprintf(tmp,"%d",config->vision.rle_port);
+		return std::string("Forwards regions calculated out of images from camera over port ")+tmp;
+	}
+	virtual std::string getDescription() const { return getClassDescription(); }
+	
+protected:
+	//! opens a new packet, writes header info; returns true if open, false if otherwise open (check cur==NULL for error)
+	/*! see the class documentation for RegionCamBehavior for the protocol documentation */
+	bool openPacket(FilterBankGenerator& fbkgen, unsigned int time, unsigned int layer); 
+	bool writeRegions(const FilterBankEvent& fbke); //!< writes the region information
+	void closePacket(); //!< closes and sends a packet, does nothing if no packet open
+
+	Socket * visRegion; //!< socket to send image stream over
+	char * packet; //!< buffer being filled out to be sent
+	char * cur; //!< current location in #packet
+	unsigned int avail; //!< number of bytes remaining in #packet
+	unsigned int max_buf; //!< the buffer size requested from Wireless when the socket was allocated
+
+private:
+	RegionCamBehavior(const RegionCamBehavior&); //!< don't call
+	RegionCamBehavior& operator=(const RegionCamBehavior&); //!< don't call
+};
+
+/*! @file
+ * @brief Implements RegionCamBehavior, which forwards the regions from RegionGenerator over wireless
+ * @author harm & niels (Creators)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.1 $
+ * $State: Exp $
+ * $Date: 2005/08/05 19:44:22 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/SegCamBehavior.cc ./Behaviors/Mon/SegCamBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/SegCamBehavior.cc	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/SegCamBehavior.cc	Fri Jul 29 14:35:04 2005
@@ -8,7 +8,7 @@
 #include "Vision/RLEGenerator.h"
 
 SegCamBehavior::SegCamBehavior()
-	: BehaviorBase("SegCamBehavior"), visRLE(NULL), packet(NULL), cur(NULL), avail(0), max_buf(0)
+	: BehaviorBase("SegCamBehavior"), visRLE(NULL), packet(NULL), cur(NULL), avail(0), max_buf(0), lastProcessedTime(0)
 {
 }
 
@@ -38,13 +38,15 @@
 
 	Controller::loadGUI("org.tekkotsu.mon.VisionGUI","SegVisionGUI",config->vision.rle_port,args);
 
-	erouter->addListener(this,EventBase::visSegmentEGID,ProjectInterface::visSegmentSID);
-	erouter->addListener(this,EventBase::visRLEEGID,ProjectInterface::visRLESID);
+	erouter->addListener(this,EventBase::visSegmentEGID,ProjectInterface::visSegmentSID,EventBase::deactivateETID);
+	erouter->addListener(this,EventBase::visRLEEGID,ProjectInterface::visRLESID,EventBase::deactivateETID);
 }
 
 void
 SegCamBehavior::DoStop() {
 	erouter->removeListener(this);
+	if(wireless->isConnected(visRLE->sock))
+		sendCloseConnectionPacket();
 	Controller::closeGUI("SegVisionGUI");
 
 	// this could be considered a bug in our wireless - if we don't setDaemon(...,false)
@@ -60,6 +62,8 @@
 		return;
 	const FilterBankEvent* fbke=dynamic_cast<const FilterBankEvent*>(&e);
 	ASSERTRET(fbke!=NULL,"unexpected event");
+	if ((get_time() - lastProcessedTime) < config->vision.rle_interval) // not enough time has gone by
+	  return;
 	if(config->vision.rlecam_compression==Config::vision_config::COMPRESS_NONE && e.getGeneratorID()==EventBase::visSegmentEGID) {
 		bool succ=writeSeg(*fbke);
 		ASSERTRET(succ,"serialization failed");
@@ -163,17 +167,29 @@
 	visRLE->write(cur-packet);
 	packet=cur=NULL;
 	avail=0;
+	lastProcessedTime = get_time();
 }
 
+bool
+SegCamBehavior::sendCloseConnectionPacket() {
+	char msg[]="CloseConnection";
+	unsigned int len=strlen(msg)+LoadSave::stringpad;
+	char * buf = (char*)visRLE->getWriteBuffer(len);
+	ASSERTRETVAL(buf!=NULL,"Could not get buffer for closing packet",false);
+	unsigned int used=LoadSave::encode(msg,buf,len);
+	ASSERTRETVAL(used!=0,"Could not write close packet",false);
+	visRLE->write(used);
+	return true;
+}
 
 /*! @file
  * @brief Implements SegCamBehavior, which forwards segmented images from camera over wireless
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.14 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/07/29 18:35:04 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/SegCamBehavior.h ./Behaviors/Mon/SegCamBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/SegCamBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/SegCamBehavior.h	Fri Jul 29 14:35:05 2005
@@ -12,7 +12,8 @@
 //! Forwards segmented images from camera over wireless
 /*! The format used for serialization is basically defined by the
  *  subclass of FilterBankGenerator being used.  I suggest looking at
- *  that classes's documentation to determine the format used.
+ *  that classes's documentation to determine the format used. (Generally
+ *  either SegmentedColorGenerator or RLEGenerator)
  *
  *  However, SegCamBehavior will add a few fields at the beginning of
  *  each packet to assist in processing the image stream.
@@ -26,10 +27,15 @@
  *  - <@c unsigned @c int: timestamp> <i>(time image was taken, milliseconds since boot)</i>
  *  - <@c unsigned @c int: framenumber> <i>(incremented for each frame, so we can tell if/when we drop one)</i>
  *
+ *  Alternatively, SegCamBehavior may send a "Close Connection" packet
+ *  when the server is shutting down.  This is to help UDP connections, which
+ *  otherwise wouldn't realize that they need to start trying to reconnect.
+ *  - <@c string:"CloseConnection">
+ *  
  *  This is exactly the same protocol that is followed by the
  *  RawCamBehavior as well - the same code can parse either stream.
  *
- *  However, odd bit - since the RLEGenerator doesn't save the color
+ *  However, one odd bit - since the RLEGenerator doesn't save the color
  *  information itself, SegCamBehavior will do it instead.  So, if
  *  SegCamBehavior is using RLE compression, it will tack a footer at
  *  the end of the packet: (from SegmentedColorGenerator::encodeColors())
@@ -38,6 +44,16 @@
  *    - <@c char: red> <i>red color to use for display of this index</i>
  *    - <@c char: green> <i>green color to use for display of this index</i>
  *    - <@c char: blue> <i>blue color to use for display of this index</i>
+ *
+ *  You can tell whether to expect the color footer by the creator string
+ *  that follows the SegCamBehavior header.  (The compression field listed
+ *  is considering segmented color itself a type of compression, whether
+ *  or not it's RLE encoded, so you can't use that to tell whether the
+ *  data is RLE encoded until you get to the data section.)
+ *
+ *  This is a binary protocol -- the fields listed indicate binary values
+ *  in the AIBO's byte order (little endian).  Strings are encoded using
+ *  the LoadSave::encode(char*,unsigned int, unsigned int) method.
  */ 
 class SegCamBehavior : public BehaviorBase {
 public:
@@ -55,7 +71,7 @@
 
 	static std::string getClassDescription() {
 		char tmp[20];
-		sprintf(tmp,"%d",config->vision.rle_port);
+		snprintf(tmp,20,"%d",config->vision.rle_port); tmp[19]='\0';
 		return std::string("Forwards segmented images from camera over port ")+tmp;
 	}
 	virtual std::string getDescription() const { return getClassDescription(); }
@@ -68,11 +84,15 @@
 	bool writeSeg(const FilterBankEvent& fbke); //!< writes a color image
 	void closePacket(); //!< closes and sends a packet, does nothing if no packet open
 
+	//! sends a packet signaling the server is closing the connection (good for UDP connections)
+	bool sendCloseConnectionPacket();
+		
 	Socket * visRLE; //!< socket to send image stream over
 	char * packet; //!< buffer being filled out to be sent
 	char * cur; //!< current location in #packet
 	unsigned int avail; //!< number of bytes remaining in #packet
 	unsigned int max_buf; //!< the buffer size requested from Wireless when the socket was allocated
+	unsigned int lastProcessedTime; //!< the time that the last event was processed
 
 private:
 	SegCamBehavior(const SegCamBehavior&); //!< don't call
@@ -84,10 +104,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/07/29 18:35:05 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/SpeakerServer.h ./Behaviors/Mon/SpeakerServer.h
--- ../Tekkotsu_2.3/Behaviors/Mon/SpeakerServer.h	Fri Nov 12 17:07:39 2004
+++ ./Behaviors/Mon/SpeakerServer.h	Sun Aug  7 00:11:03 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_SpeakerServer_h_
 
 #include "Behaviors/BehaviorBase.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 //! Plays streamed audio via the speaker
 class SpeakerServer : public BehaviorBase {
@@ -18,8 +18,8 @@
 	
 	private:
 		SpeakerServer();
-		SpeakerServer(const SpeakerServer& rhs);
-		SpeakerServer& operator=(const SpeakerServer& rhs);
+		SpeakerServer(const SpeakerServer& rhs); //!< don't call
+		SpeakerServer& operator=(const SpeakerServer& rhs); //!< don't call
 		static SpeakerServer* instance;
 		
 		int GotSocketData(char* data, int dataSize);
@@ -32,7 +32,7 @@
 		class Packet {
 			public:
 				Packet();
-				virtual ~Packet();
+				virtual ~Packet(); 
 				
 				class Buffer* header;
 				int size;
@@ -46,8 +46,8 @@
 				class Buffer* samples;
 			
 			private:
-				Packet(const Packet& rhs);
-				Packet& operator=(const Packet& rhs);
+				Packet(const Packet& rhs); //!< don't call
+				Packet& operator=(const Packet& rhs); //!< don't call
 		};
 		
 		Packet packet; 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/SpiderMachineBehavior.cc ./Behaviors/Mon/SpiderMachineBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/SpiderMachineBehavior.cc	Fri Dec 17 15:18:54 2004
+++ ./Behaviors/Mon/SpiderMachineBehavior.cc	Wed Jun  1 01:47:45 2005
@@ -4,7 +4,7 @@
 #include "Wireless/Wireless.h"
 
 SpiderMachineBehavior * SpiderMachineBehavior::theOne=NULL;
-unsigned int SpiderMachineBehavior::port=10080;
+unsigned int SpiderMachineBehavior::port=10081;
 
 void SpiderMachineBehavior::DoStart() {
 	BehaviorBase::DoStart(); // do this first
@@ -232,8 +232,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2004/12/17 20:18:54 $
+ * $Date: 2005/06/01 05:47:45 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/SpiderMachineBehavior.h ./Behaviors/Mon/SpiderMachineBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/SpiderMachineBehavior.h	Wed Dec 22 20:47:07 2004
+++ ./Behaviors/Mon/SpiderMachineBehavior.h	Sun Aug  7 00:11:03 2005
@@ -69,7 +69,7 @@
 	//! Points to the one SpiderMachineBehavior object that the input command stream is talking to.
 	/*! A kludge. Dunno how you're gonna make sure you're not using this uninitialized. */
 	static SpiderMachineBehavior * theOne;
-	static unsigned int port; //!< the port to listen on (10080 by default)
+	static unsigned int port; //!< the port to listen on (10081 by default)
 	static int callback(char *buf, int bytes); //!< called by wireless when there's new data
 
 public:
@@ -107,7 +107,7 @@
 	class Socket *cmdsock; //!< the socket for communication
 
 	typedef std::set<BehaviorBase*> registry_t; //!< the type of the behavior registry (BehaviorBase::registry)
-	typedef std::multiset<const StateNode*> expected_t; //!< the type of #ignore
+	typedef std::multiset<const StateNode*> expected_t; //!< the type of #expected
 	typedef std::set<std::string> listen_t; //!< the type of #listen
 	typedef std::queue<EventBase> queuedEvents_t; //!< the type of #queuedEvents
 
@@ -127,10 +127,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/StewartPlatformBehavior.cc ./Behaviors/Mon/StewartPlatformBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/StewartPlatformBehavior.cc	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/StewartPlatformBehavior.cc	Wed Jun  1 01:47:45 2005
@@ -0,0 +1,212 @@
+#include "StewartPlatformBehavior.h"
+#include "Motion/EmergencyStopMC.h"
+#include "Motion/MMAccessor.h"
+#include "Wireless/Wireless.h"
+#include "Events/EventRouter.h"
+#include "Events/EventBase.h"
+
+#include <libxml/parser.h>
+
+StewartPlatformBehavior* StewartPlatformBehavior::theOne = NULL;
+
+void StewartPlatformBehavior::DoStart() {
+	// Behavior startup
+	BehaviorBase::DoStart();
+	// Turn on wireless
+	cmdsock=wireless->socket(SocketNS::SOCK_STREAM, 300, 300);
+	sock=cmdsock->sock;
+	wireless->setDaemon(cmdsock,true);
+	wireless->setReceiver(cmdsock->sock, callback);
+	wireless->listen(cmdsock->sock, config->main.stewart_port);
+}
+
+void StewartPlatformBehavior::DoStop() {
+	// Turn off timers
+	erouter->removeListener(this);
+	// Close socket; turn wireless off
+  wireless->setDaemon(cmdsock,false);
+	closeComm();
+	cmdsock=NULL;
+	// Total behavior stop
+	BehaviorBase::DoStop();
+}
+
+void StewartPlatformBehavior::setParam(const std::string& cmd, float value) {
+	//cout << "got " << cmd << ' ' << value << endl;
+	if(cmd=="x") {
+	} else if(cmd=="y") {
+	} else if(cmd=="z") {
+	} else if(cmd=="tilt") {
+	} else if(cmd=="pan") {
+	} else if(cmd=="roll") {
+	} else {
+		serr->printf("StewartPlatformBehavior::runCommand() - bad message: '%s' == %g\n",cmd.c_str(),value);
+	}
+}
+
+void StewartPlatformBehavior::processEvent(const EventBase & /*e*/) {
+}
+
+void* StewartPlatformBehavior::getSAXHandler() {
+  static xmlSAXHandler handler;
+	static bool isinit=false;
+	if(!isinit) {
+		memset(&handler,0,sizeof(handler));
+    handler.endDocument  = (endDocumentSAXFunc)  StewartPlatformBehavior::sax_end_doc;
+    handler.startElement = (startElementSAXFunc) StewartPlatformBehavior::sax_start_element;
+    handler.endElement   = (endElementSAXFunc)   StewartPlatformBehavior::sax_end_element;
+    handler.warning      = (warningSAXFunc)      StewartPlatformBehavior::sax_warning;
+		handler.error        = (errorSAXFunc)        StewartPlatformBehavior::sax_error;
+		handler.fatalError   = (fatalErrorSAXFunc)   StewartPlatformBehavior::sax_fatal_error;
+		isinit=true;
+  }
+	return &handler;
+}
+
+// The command packet reassembly mechanism
+int StewartPlatformBehavior::callback(char *buf, int bytes) {
+	if(StewartPlatformBehavior::theOne==NULL)
+		return 0;
+	
+	static xmlSAXHandler * communicationParser = (xmlSAXHandler*)getSAXHandler();
+
+	buf[bytes]='\0';
+	theOne->docClosed=false;
+  if(theOne->ctxt==NULL) {
+		theOne->ctxt = xmlCreatePushParserCtxt(communicationParser, theOne, buf, bytes, NULL);
+		if (theOne->ctxt == NULL) {
+			serr->printf("StewartPlatform could not create parsing context\n");
+			theOne->closeComm();
+			return 1;
+		}
+		//this will trigger libxml to actually do processing on buf, *right now*
+		if(xmlParseChunk((xmlParserCtxtPtr)theOne->ctxt,NULL,0,0)!=0) {
+			serr->printf("StewartPlatform communication encountered an initial parsing error\n");
+			serr->printf("closing StewartPlatformBehavior communication.\n");
+			theOne->closeComm();
+			return 1;
+		}
+	} else {
+		if(xmlParseChunk((xmlParserCtxtPtr)theOne->ctxt,buf,bytes,0)!=0) {
+			serr->printf("StewartPlatform communication encountered a parsing error\n");
+			serr->printf("closing StewartPlatformBehavior communication.\n");
+			theOne->closeComm();
+			return 1;
+		}
+	}
+	if(theOne->docClosed) {
+		theOne->closeComm();
+	}
+  return 0;
+}
+
+void StewartPlatformBehavior::sax_start_element(StewartPlatformBehavior * inst, const char * name, const char ** attrs) {
+	/*cout << "Receiving " << name << " with attributes: ";
+	if(attrs!=NULL) {
+		while(*attrs!=NULL)
+			cout << *attrs++ << ' ';
+	}
+	cout << endl; */
+	if(strcmp(name,"param")==0) {
+		ASSERTRET(attrs!=NULL,"StewartPlatformBehavior: parser error, param missing attributes");
+		const char * pname=NULL;
+		const char * val=NULL;
+		for(; *attrs!=NULL; attrs++) {
+			if(strcmp(*attrs,"name")==0)
+				pname=*++attrs;
+			else if(strcmp(*attrs,"value")==0)
+				val=*++attrs;
+			else
+				serr->printf("StewartPlatformBehavior: warning unknown attribute %s\n",*attrs++);
+		}
+		ASSERTRET(pname!=NULL,"StewartPlatformBehavior: parser error, param missing name attribute");
+		ASSERTRET(val!=NULL,"StewartPlatformBehavior: parser error, param missing value attribute");
+		inst->setParam(pname,atof(val));
+	} else if(strcmp(name,"connection")==0) {
+		if(inst!=NULL && inst->cmdsock!=NULL)
+			inst->cmdsock->printf("<connection>\n");
+	} 
+}
+void StewartPlatformBehavior::sax_end_element(StewartPlatformBehavior * inst, const char * name) {
+	//cout << "end element " << name << endl;
+	if(strcmp(name,"connection")==0) {
+		inst->docClosed=true;
+	}
+}
+
+void StewartPlatformBehavior::sax_end_doc(StewartPlatformBehavior * inst) {
+	inst->docClosed=true;
+}
+
+void StewartPlatformBehavior::sax_warning(StewartPlatformBehavior * /*inst*/, const char *msg, ...) {
+	va_list args;
+	va_start(args, msg);
+	serr->printf("StewartPlatformBehavior communication encountered a warning:\n");
+	serr->vprintf(msg, args);
+	va_end(args);
+}
+
+void StewartPlatformBehavior::sax_error(StewartPlatformBehavior * /*inst*/, const char *msg, ...) {
+	va_list args;
+	va_start(args, msg);
+	serr->printf("StewartPlatformBehavior communication encountered an error:\n");
+	serr->vprintf(msg, args);
+	va_end(args);
+}
+
+void StewartPlatformBehavior::sax_fatal_error(StewartPlatformBehavior * /*inst*/, const char *msg, ...) {
+	va_list args;
+	va_start(args, msg);
+	serr->printf("StewartPlatformBehavior communication encountered a fatal error:\n");
+	serr->vprintf(msg, args);
+	va_end(args);
+}
+
+bool StewartPlatformBehavior::isConnected() {
+	bool con=theOne!=NULL && theOne->cmdsock!=NULL && wireless->isConnected(theOne->sock);
+	//since we're using a daemon socket, we don't need to reset the cmdsock
+	//if(!con)
+	//theOne->cmdsock=NULL;
+	if(!con && theOne->ctxt!=NULL) {
+		serr->printf("StewartPlatform connection was dropped\n");
+		xmlParserCtxtPtr tmp=(xmlParserCtxtPtr)theOne->ctxt;
+		theOne->ctxt=NULL; //do this first to prevent recursive errors
+		if(xmlParseChunk(tmp,"",0,1)!=0)
+			serr->printf("StewartPlatform communication encountered a parsing error in isConnected\n");
+		tmp->sax = NULL;
+		xmlFreeParserCtxt(tmp);	
+	}
+	return con;
+}
+
+void StewartPlatformBehavior::closeComm() {
+	if(cmdsock!=NULL) {
+		cmdsock->printf("</connection>\n");
+		wireless->close(cmdsock); //cmdsock is daemon, so it will still be valid
+		if(ctxt!=NULL) {
+			xmlParserCtxtPtr tmp=(xmlParserCtxtPtr)ctxt;
+			ctxt=NULL; //do this first to prevent any recursive errors
+			tmp->sax = NULL;
+			xmlFreeParserCtxt(tmp);	
+		}
+	} else {
+		ASSERT(ctxt==NULL,"non null parsing context with closed connection?");
+		if(cmdsock!=NULL)
+			wireless->close(cmdsock); //cmdsock is daemon, so it will still be valid
+	}
+}
+
+
+
+
+/*! @file
+ * @brief Implements StewartPlatformBehavior, moves the legs in synchrony to emulate the capabilities of a stewart platform
+ * @author tss (Creator)
+ * 
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:45 $
+ */
+
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/StewartPlatformBehavior.h ./Behaviors/Mon/StewartPlatformBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/StewartPlatformBehavior.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/StewartPlatformBehavior.h	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,97 @@
+//-*-c++-*-
+#ifndef INCLUDED_StewartPlatformBehavior_h_
+#define INCLUDED_StewartPlatformBehavior_h_
+
+#include <iostream>
+#include "Behaviors/BehaviorBase.h"
+#include "Motion/MotionManager.h"
+#include "Shared/Config.h"
+
+class Socket;
+
+//*********** NOT DONE **********//
+
+//! moves the legs in synchrony to emulate the capabilities of a stewart platform
+class StewartPlatformBehavior : public BehaviorBase {
+
+public:	
+	//! Points to the one StewartPlatformBehavior object that the input command stream is talking to.
+	static StewartPlatformBehavior * theOne;
+	static int callback(char *buf, int bytes); //!< called by wireless when there's new data
+
+public:
+	//! constructor
+	StewartPlatformBehavior()
+		: BehaviorBase("StewartPlatformBehavior"),
+			cmdsock(NULL), sock(-1), ctxt(NULL), docClosed(false),
+			pose_id(MotionManager::invalid_MC_ID)
+	{
+		theOne=this;
+	}
+	//! destructor
+	virtual ~StewartPlatformBehavior() {
+		theOne=NULL;
+	}
+
+	virtual void DoStart();
+
+	virtual void DoStop();
+
+	virtual void processEvent(const EventBase &);
+
+	static std::string getClassDescription() {
+		char tmp[20];
+		sprintf(tmp,"%d",config->main.stewart_port);
+		return std::string("moves the legs in synchrony to emulate the capabilities of a stewart platform, base on commands from port ")+tmp;
+	}
+	virtual std::string getDescription() const { return getClassDescription(); }
+
+	virtual void setParam(const std::string& cmd, float value); //!< processes a string received from wireless
+
+protected:
+	//! The input command stream socket
+	Socket *cmdsock;
+	int sock; //!< the socket number so we can test if #cmdsock is still valid
+
+	//! contains parsing context regarding communication socket
+	void* ctxt;
+	//! set to true by sax routines if the socket should be closed
+	bool docClosed;
+
+	//! The estop to control
+	MotionManager::MC_ID pose_id;
+
+	//! fills out (and returns) a xmlSAXHandler structure to control parsing of the communication stream
+	static void* getSAXHandler();
+
+	//!@name SAX functions
+	//! handles parsing of communications stream
+	static void sax_start_element(StewartPlatformBehavior * inst, const char * name, const char ** attrs);
+	static void sax_end_element(StewartPlatformBehavior * inst, const char * name);
+	static void sax_end_doc(StewartPlatformBehavior * inst);
+	static void sax_warning(StewartPlatformBehavior *inst, const char *msg, ...);
+	static void sax_error(StewartPlatformBehavior *inst, const char *msg, ...);
+	static void sax_fatal_error(StewartPlatformBehavior *inst, const char *msg, ...);
+	//@}
+
+	static bool isConnected(); //!< returns true if #theOne is connected
+	void closeComm(); //!< closes communications socket
+
+private:
+	StewartPlatformBehavior(const StewartPlatformBehavior&); //!< don't call
+	StewartPlatformBehavior operator=(const StewartPlatformBehavior&); //!< don't call
+
+};
+
+/*! @file
+ * @brief Describes StewartPlatformBehavior, moves the legs in synchrony to emulate the capabilities of a stewart platform
+ * @author tss (Creator)
+ * 
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+#endif 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/UPennWalkControllerBehavior.cc ./Behaviors/Mon/UPennWalkControllerBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/UPennWalkControllerBehavior.cc	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/UPennWalkControllerBehavior.cc	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,168 @@
+#include "UPennWalkControllerBehavior.h"
+#include "Behaviors/Controller.h"
+#include "Sound/SoundManager.h"
+
+using namespace std;
+
+UPennWalkControllerBehavior* UPennWalkControllerBehavior::theOne = NULL;
+
+void UPennWalkControllerBehavior::runCommand(unsigned char *command) {
+	// First, turn off the stop-if-no-heartbeat timer
+	erouter->removeTimer(this);
+
+	// Extract the command parameter
+	float param;
+	unsigned char *paramp = (unsigned char *) &param;
+
+	paramp[0] = command[1];
+	paramp[1] = command[2];
+	paramp[2] = command[3];
+	paramp[3] = command[4];
+
+	// Find out what type of command this is
+	switch(command[0]) {
+	case CMD_fwd:
+		dx = param;
+		break;
+	case CMD_roto:
+		da = param;
+		break;
+	case CMD_side:
+		dy = param;
+		break;
+	case CMD_opt0:
+		{
+			/*			HeadPointerMC *head =
+				(HeadPointerMC*)motman->checkoutMotion(head_id);
+			head->setJoints(0,0,0);
+			motman->checkinMotion(head_id);*/
+			break;
+		}
+	case CMD_opt1:
+	case CMD_opt2:
+	case CMD_opt3:
+	case CMD_opt4:
+		cout << "MECHA: hey, reprogram this button!" << endl;
+		break;
+	case CMD_opt5:
+		sndman->PlayFile("howl.wav");
+		break;
+	case CMD_opt6:
+		sndman->PlayFile("yap.wav");
+		break;
+	case CMD_opt7:
+		sndman->PlayFile("whimper.wav");
+		break;
+	case CMD_opt8:
+		sndman->PlayFile("growl.wav");
+		break;
+	case CMD_opt9:
+		sndman->PlayFile("barkmed.wav");
+		break;
+		// The options button commands.
+	default:
+		cout << "MECHA: unknown command " << command[0] << endl;
+	}
+
+	// If the command was a new motion command, apply the
+	// new motion parameters:
+	switch(command[0]) {
+	case CMD_fwd:
+	case CMD_roto:
+	case CMD_side:
+		{
+			MMAccessor<UPennWalkMC> walker(getWalkID());
+			float tdx=dx*13;
+			float tdy=dy*6.5;
+			float tda=da*.25;
+			walker->setTargetVelocity(tdx,tdy,tda);
+		}
+	}
+
+	// Reset the stop-if-no-heartbeat timer -- if we don't
+	// hear from the mothership in three seconds, stop immediately.
+	erouter->addTimer(this, 0, 3000, false);
+}
+
+void UPennWalkControllerBehavior::DoStart() {
+	// Behavior startup
+	BehaviorBase::DoStart();
+	// We listen to timers (but don't need to explicitly tell erouter -- addTimer implies this)
+	//erouter->addListener(this, EventBase::timerEGID);
+	// Enable walker (the MC_ID can be accessed through the shared_walker later)
+	motman->addPersistentMotion(shared_walker);
+	// Turn on wireless
+	theLastOne=theOne;
+	theOne=this;
+	cmdsock=wireless->socket(SocketNS::SOCK_STREAM, 2048, 2048);
+	wireless->setReceiver(cmdsock->sock, mechacmd_callback);
+	wireless->setDaemon(cmdsock,true); 
+	wireless->listen(cmdsock->sock, config->main.walkControl_port);
+	// Open the WalkGUI on the desktop
+	Controller::loadGUI("org.tekkotsu.mon.WalkGUI","WalkGUI",config->main.walkControl_port);
+}
+
+void UPennWalkControllerBehavior::DoStop() {
+	// Close the GUI
+	Controller::closeGUI("WalkGUI");
+	// Turn off timers
+	erouter->removeListener(this);
+	// Close socket; turn wireless off
+	wireless->setDaemon(cmdsock,false); 
+	wireless->close(cmdsock);
+	theOne=theLastOne;
+	// Disable walker
+	motman->removeMotion(getWalkID());
+	// Total behavior stop
+	BehaviorBase::DoStop();
+}
+
+// The command packet reassembly mechanism
+int UPennWalkControllerBehavior::mechacmd_callback(char *buf, int bytes) {
+  static char cb_buf[5];
+  static int cb_buf_filled;
+
+  // If there's an incomplete command in the command buffer, fill
+  // up as much of the command buffer as we can and then execute it
+  // if possible
+  if(cb_buf_filled) {
+    while((cb_buf_filled < 5) && bytes) {
+      cb_buf[cb_buf_filled++] = *buf++;	// copy incoming buffer byte
+      --bytes;				// decrement remaining byte ct.
+    }
+    // did we fill it? if so, execute! and mark buffer empty.
+    if(cb_buf_filled == 5) {
+      if(UPennWalkControllerBehavior::theOne) UPennWalkControllerBehavior::theOne->runCommand((unsigned char*) cb_buf);
+      cb_buf_filled = 0;
+    }
+  }
+
+  // now execute all complete bytes in the incoming buffer
+  while(bytes >= 5) {
+    if(UPennWalkControllerBehavior::theOne) UPennWalkControllerBehavior::theOne->runCommand((unsigned char *) buf);
+    bytes -= 5;
+    buf += 5;
+  }
+
+  // finally, store all remaining bytes in the command buffer
+  while(bytes) {
+    cb_buf[cb_buf_filled++] = *buf++;
+    --bytes;
+  }
+
+  return 0;
+}
+
+/*! @file
+ * @brief Implements UPennWalkControllerBehavior, listens to mecha control commands coming in from the command port for remotely controlling the walk
+ * @author tss (Creator)
+ * @author ejt (modifications)
+ * @author PA Gov. School for the Sciences 2003 Team Project - Haoqian Chen, Yantian Martin, Jon Stahlman (modifications)
+ * 
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:46 $
+ */
+
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/UPennWalkControllerBehavior.h ./Behaviors/Mon/UPennWalkControllerBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/UPennWalkControllerBehavior.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Mon/UPennWalkControllerBehavior.h	Sat Apr 23 14:33:26 2005
@@ -0,0 +1,112 @@
+//-*-c++-*-
+#ifndef INCLUDED_UPennWalkControllerBehavior_h_
+#define INCLUDED_UPennWalkControllerBehavior_h_
+
+#include <iostream>
+#include "Wireless/Wireless.h"
+#include "Behaviors/BehaviorBase.h"
+#include "Motion/MotionManager.h"
+#include "Motion/UPennWalkMC.h"
+#include "Motion/MMAccessor.h"
+#include "Events/EventRouter.h"
+#include "Events/EventBase.h"
+#include "Shared/Config.h"
+
+//! Listens to control commands coming in from the command port for remotely controlling the walk
+class UPennWalkControllerBehavior : public BehaviorBase {
+
+ public:	
+	//! Points to the one UPennWalkControllerBehavior object that the input
+	//! command stream is talking to. A kludge. Dunno how you're gonna
+	//! make sure you're not using this uninitialized.
+	static UPennWalkControllerBehavior * theOne;
+	static int mechacmd_callback(char *buf, int bytes); //!< called by wireless when there's new data
+
+ protected:
+	SharedObject<UPennWalkMC> shared_walker; //!< the WalkMC to use
+ 
+ private:
+	//!@name Command Bytes
+	static const char CMD_fwd  = 'f'; //!< handy symbol for matching incoming communication
+	static const char CMD_roto = 'r';
+	static const char CMD_side = 's';
+	static const char CMD_opt0 = '0';
+	static const char CMD_opt1 = '1';
+	static const char CMD_opt2 = '2';
+	static const char CMD_opt3 = '3';
+	static const char CMD_opt4 = '4';
+	static const char CMD_opt5 = '5';
+	static const char CMD_opt6 = '6';
+	static const char CMD_opt7 = '7';
+	static const char CMD_opt8 = '8';
+	static const char CMD_opt9 = '9';
+	//@}
+
+	float dx; //!< Motion parameter
+	float dy; //!< Motion parameter
+	float da; //!< Motion parameter
+
+	//! The last WCB object that was theOne, so we can restore it
+	//! to prominence when we die. This is a nice gesture, but it doesn't
+	//! really make sense since we're all using the same port. But just
+	//! in case something changes and we don't do that, this mechanism
+	//! is in place.
+	UPennWalkControllerBehavior *theLastOne;
+
+	//! The input command stream socket
+	Socket *cmdsock;
+
+	//! Executes a command. Called by mechacmd_callback.
+	void runCommand(unsigned char *command);
+
+	UPennWalkControllerBehavior(const UPennWalkControllerBehavior&); //!< don't call
+	UPennWalkControllerBehavior operator=(const UPennWalkControllerBehavior&); //!< don't call
+
+ public:
+	//! constructor
+	UPennWalkControllerBehavior() :
+	  BehaviorBase("UPennWalkControllerBehavior"),
+		shared_walker(),
+	  dx(0), dy(0), da(0),
+	  theLastOne(theOne),
+	  cmdsock(NULL)
+	{}
+	//! destructor
+	virtual ~UPennWalkControllerBehavior() { theOne = theLastOne; }
+
+	virtual void DoStart();
+
+	virtual void DoStop();
+
+	virtual UPennWalkMC * getWalkMC() { return &(*shared_walker); }  //!< returns the WalkMC which [will be|is being] used
+
+	virtual MotionManager::MC_ID getWalkID() { return shared_walker->getID(); } //!< returns the current Walk's MotionCommand ID
+
+	//! The only event we could possibly receive is the stop-if-no-heartbeat timer.
+	virtual void processEvent(const EventBase &) {
+		MMAccessor<UPennWalkMC> walker(getWalkID());
+		walker->setTargetVelocity(0,0,0);
+	}
+
+	static std::string getClassDescription() {
+		char tmp[20];
+		sprintf(tmp,"%d",config->main.walkControl_port);
+		return std::string("Listens to walk control commands coming in from port ")+tmp;
+	}
+	virtual std::string getDescription() const { return getClassDescription(); }
+};
+
+/*! @file
+ * @brief Describes UPennWalkControllerBehavior, listens to control commands coming in from the command port for remotely controlling the walk
+ * @author tss (Creator)
+ * @author ejt (modifications)
+ * @author PA Gov. School for the Sciences 2003 Team Project - Haoqian Chen, Yantian Martin, Jon Stahlman (modifications)
+ * 
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.1 $
+ * $State: Exp $
+ * $Date: 2005/04/23 18:33:26 $
+ */
+
+#endif 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/ViewWMVarsBehavior.h ./Behaviors/Mon/ViewWMVarsBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/ViewWMVarsBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/ViewWMVarsBehavior.h	Wed Nov 10 20:45:36 2004
@@ -38,7 +38,7 @@
  * @author ejt (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/WMMonitorBehavior.cc ./Behaviors/Mon/WMMonitorBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/WMMonitorBehavior.cc	Fri Apr 16 16:17:22 2004
+++ ./Behaviors/Mon/WMMonitorBehavior.cc	Fri Apr 16 16:17:22 2004
@@ -146,7 +146,7 @@
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Exp $
  * $Date: 2004/04/16 20:17:22 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/WMMonitorBehavior.h ./Behaviors/Mon/WMMonitorBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/WMMonitorBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/WMMonitorBehavior.h	Wed Nov 10 20:45:36 2004
@@ -136,7 +136,7 @@
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.9 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/WalkControllerBehavior.cc ./Behaviors/Mon/WalkControllerBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/WalkControllerBehavior.cc	Wed Nov  3 22:01:32 2004
+++ ./Behaviors/Mon/WalkControllerBehavior.cc	Wed Jun  1 01:47:46 2005
@@ -1,6 +1,8 @@
 #include "WalkControllerBehavior.h"
 #include "Behaviors/Controller.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
+
+using namespace std;
 
 WalkControllerBehavior* WalkControllerBehavior::theOne = NULL;
 
@@ -85,8 +87,8 @@
 void WalkControllerBehavior::DoStart() {
 	// Behavior startup
 	BehaviorBase::DoStart();
-	// We listen to timers
-	erouter->addListener(this, EventBase::timerEGID);
+	// We listen to timers (but don't need to explicitly tell erouter -- addTimer implies this)
+	//erouter->addListener(this, EventBase::timerEGID);
 	// Enable walker (the MC_ID can be accessed through the shared_walker later)
 	motman->addPersistentMotion(shared_walker);
 	// Turn on wireless
@@ -158,9 +160,9 @@
  * @author PA Gov. School for the Sciences 2003 Team Project - Haoqian Chen, Yantian Martin, Jon Stahlman (modifications)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/11/04 03:01:32 $
+ * $Date: 2005/06/01 05:47:46 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/WalkControllerBehavior.h ./Behaviors/Mon/WalkControllerBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/WalkControllerBehavior.h	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/WalkControllerBehavior.h	Wed Nov 10 20:45:36 2004
@@ -103,7 +103,7 @@
  * @author PA Gov. School for the Sciences 2003 Team Project - Haoqian Chen, Yantian Martin, Jon Stahlman (modifications)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Exp $
  * $Date: 2004/11/11 01:45:36 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/WorldStateSerializerBehavior.cc ./Behaviors/Mon/WorldStateSerializerBehavior.cc
--- ../Tekkotsu_2.3/Behaviors/Mon/WorldStateSerializerBehavior.cc	Wed Nov 10 20:45:36 2004
+++ ./Behaviors/Mon/WorldStateSerializerBehavior.cc	Mon Feb 21 03:05:57 2005
@@ -5,7 +5,7 @@
 #include "Events/EventRouter.h"
 
 WorldStateSerializerBehavior::WorldStateSerializerBehavior()
-	: BehaviorBase("WorldStateSerializerBehavior"), wsJoints(NULL), wsPIDs(NULL)
+	: BehaviorBase("WorldStateSerializerBehavior"), wsJoints(NULL), wsPIDs(NULL), lastProcessedTime(0)
 {
 	wsJoints=wireless->socket(SocketNS::SOCK_STREAM, 1024, 2048);
   wireless->setDaemon(wsJoints);
@@ -25,7 +25,10 @@
 	BehaviorBase::DoStop(); // do this last
 }
 
-void WorldStateSerializerBehavior::processEvent(const EventBase& /*e*/) {
+void WorldStateSerializerBehavior::processEvent(const EventBase& e) {
+  if ((e.getTimeStamp() - lastProcessedTime) < config->main.worldState_interval) // not enough time has gone by
+    return;
+  lastProcessedTime = e.getTimeStamp();
   char *buf=(char*)wsPIDs->getWriteBuffer((NumPIDJoints*3)*sizeof(float)+2*sizeof(unsigned int));
   if (buf) {
     encode(&buf,state->lastSensorUpdateTime);
@@ -48,13 +51,14 @@
   }
 }
 
+
 /*! @file
  * @brief Implements WorldStateSerializer, which copies WorldState into a buffer for transmission over the network
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/11/11 01:45:36 $
+ * $Date: 2005/02/21 08:05:57 $
  */
diff -urdN ../Tekkotsu_2.3/Behaviors/Mon/WorldStateSerializerBehavior.h ./Behaviors/Mon/WorldStateSerializerBehavior.h
--- ../Tekkotsu_2.3/Behaviors/Mon/WorldStateSerializerBehavior.h	Wed Jan 26 14:35:26 2005
+++ ./Behaviors/Mon/WorldStateSerializerBehavior.h	Mon Feb 21 03:05:57 2005
@@ -59,6 +59,7 @@
 
   Socket *wsJoints; //!< socket for sending current joint data
   Socket *wsPIDs; //!< socket for sending current PID info
+  unsigned int lastProcessedTime; //!< the time that the last event was processed
 
 private:
   WorldStateSerializerBehavior(const WorldStateSerializerBehavior&); //!< don't call
@@ -70,10 +71,10 @@
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
  * $State: Exp $
- * $Date: 2005/01/26 19:35:26 $
+ * $Date: 2005/02/21 08:05:57 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Entries ./Behaviors/Nodes/CVS/Entries
--- ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Nodes/CVS/Entries	Wed Aug 10 11:03:18 2005
@@ -0,0 +1,12 @@
+/GroupNode.h/1.6/Mon Jan 24 22:23:50 2005//Ttekkotsu-2_4
+/HeadPointerNode.h/1.7/Mon Jan 24 22:23:50 2005//Ttekkotsu-2_4
+/LedNode.h/1.6/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/MotionSequenceNode.h/1.3/Thu Jan 27 20:08:15 2005//Ttekkotsu-2_4
+/OutputNode.h/1.8/Wed Feb  2 18:20:27 2005//Ttekkotsu-2_4
+/PlayMotionSequenceNode.h/1.13/Fri Jan 21 22:50:37 2005//Ttekkotsu-2_4
+/SoundNode.h/1.11/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/TailWagNode.h/1.2/Mon Jan 24 22:23:50 2005//Ttekkotsu-2_4
+/WalkNode.h/1.15/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/WalkToTargetNode.cc/1.1/Sun Dec  5 04:47:53 2004//Ttekkotsu-2_4
+/WalkToTargetNode.h/1.4/Wed Dec  8 19:05:50 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Repository ./Behaviors/Nodes/CVS/Repository
--- ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Nodes/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Behaviors/Nodes
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Root ./Behaviors/Nodes/CVS/Root
--- ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Nodes/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Tag ./Behaviors/Nodes/CVS/Tag
--- ../Tekkotsu_2.3/Behaviors/Nodes/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Nodes/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/GroupNode.h ./Behaviors/Nodes/GroupNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/GroupNode.h	Mon Jan 24 17:23:50 2005
+++ ./Behaviors/Nodes/GroupNode.h	Mon Jan 24 17:23:50 2005
@@ -48,7 +48,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.6 $
  * $State: Exp $
  * $Date: 2005/01/24 22:23:50 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/HeadPointerNode.h ./Behaviors/Nodes/HeadPointerNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/HeadPointerNode.h	Mon Jan 24 17:23:50 2005
+++ ./Behaviors/Nodes/HeadPointerNode.h	Mon Jan 24 17:23:50 2005
@@ -56,7 +56,7 @@
  * @author dst (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.7 $
  * $State: Exp $
  * $Date: 2005/01/24 22:23:50 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/LedNode.h ./Behaviors/Nodes/LedNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/LedNode.h	Mon Jan 24 17:23:50 2005
+++ ./Behaviors/Nodes/LedNode.h	Wed Jun  1 01:47:46 2005
@@ -45,7 +45,7 @@
 
 protected:
   //! constructor
-  LedNode(std::string &classname, std::string &nodename) : 
+  LedNode(const std::string &classname, const std::string &nodename) : 
     StateNode(classname,nodename), leds_mc(), leds_id(MotionManager::invalid_MC_ID) {}
 
 
@@ -56,10 +56,10 @@
  * @author dst (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
  * $State: Exp $
- * $Date: 2005/01/24 22:23:50 $
+ * $Date: 2005/06/01 05:47:46 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/MotionSequenceNode.h ./Behaviors/Nodes/MotionSequenceNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/MotionSequenceNode.h	Thu Jan 27 15:08:15 2005
+++ ./Behaviors/Nodes/MotionSequenceNode.h	Thu Jan 27 15:08:15 2005
@@ -132,7 +132,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Exp $
  * $Date: 2005/01/27 20:08:15 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/OutputNode.h ./Behaviors/Nodes/OutputNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/OutputNode.h	Fri Dec  3 19:10:42 2004
+++ ./Behaviors/Nodes/OutputNode.h	Wed Feb  2 13:20:27 2005
@@ -11,17 +11,17 @@
 class OutputNode : public StateNode {
 public:
 	//!constructor, sets name and ostream to use for output
-	OutputNode(const char* nm, ostream& output) : StateNode("OutputNode",nm), next(NULL), out(output), msg(nm) {}
+	OutputNode(const char* nm, std::ostream& output) : StateNode("OutputNode",nm), next(NULL), out(output), msg(nm) {}
 	//!constructor, sets name and another state which will immediately be transitioned to upon activation
-	OutputNode(const char* nm, ostream& output, StateNode * nextstate) : StateNode("OutputNode",nm), next(nextstate), out(output), msg(nm) {}
+	OutputNode(const char* nm, std::ostream& output, StateNode * nextstate) : StateNode("OutputNode",nm), next(nextstate), out(output), msg(nm) {}
 	//!constructor, sets name, message, and another state which will immediately be transitioned to upon activation
-	OutputNode(const char* nm, const std::string& mg, ostream& output, StateNode * nextstate) : StateNode("OutputNode",nm), next(nextstate), out(output), msg(mg) {}
+	OutputNode(const char* nm, const std::string& mg, std::ostream& output, StateNode * nextstate) : StateNode("OutputNode",nm), next(nextstate), out(output), msg(mg) {}
 
 	//!outputs this state's name, will transition to #next if non-NULL
 	/*!if #next is NULL, the state will simply stay active until some other transition causes it to leave*/
 	virtual void DoStart() {
 		StateNode::DoStart();
-		out << msg << endl;
+		out << msg << std::endl;
 		if(next!=NULL) {
 			DoStop();
 			next->DoStart();
@@ -30,7 +30,7 @@
 	
 protected:
 	StateNode* next; //!< the state to transition to upon entering, can be NULL
-	ostream& out;    //!< the stream to use for output - if not specified (default constructor) cout will be used
+	std::ostream& out;    //!< the stream to use for output - if not specified (default constructor) cout will be used
 	std::string msg;      //!< message to show on activation
 
 private:
@@ -43,10 +43,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/12/04 00:10:42 $
+ * $Date: 2005/02/02 18:20:27 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/PlayMotionSequenceNode.h ./Behaviors/Nodes/PlayMotionSequenceNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/PlayMotionSequenceNode.h	Fri Jan 21 17:50:37 2005
+++ ./Behaviors/Nodes/PlayMotionSequenceNode.h	Fri Jan 21 17:50:37 2005
@@ -18,7 +18,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.13 $
  * $State: Exp $
  * $Date: 2005/01/21 22:50:37 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/SoundNode.h ./Behaviors/Nodes/SoundNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/SoundNode.h	Mon Jan 24 17:23:50 2005
+++ ./Behaviors/Nodes/SoundNode.h	Wed Jun  1 01:47:46 2005
@@ -4,7 +4,7 @@
 
 #include "Behaviors/StateNode.h"
 #include "Events/EventRouter.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 //! A simple StateNode that plays a sound upon startup and throws a status event on completion
 /*! Doesn't automatically preload the sound buffer - if you want the sound file
@@ -81,10 +81,10 @@
  * @author dst (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.10 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2005/01/24 22:23:50 $
+ * $Date: 2005/06/01 05:47:46 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/TailWagNode.h ./Behaviors/Nodes/TailWagNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/TailWagNode.h	Mon Jan 24 17:23:50 2005
+++ ./Behaviors/Nodes/TailWagNode.h	Mon Jan 24 17:23:50 2005
@@ -51,7 +51,7 @@
  * @author dst, ejt (Creators)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Exp $
  * $Date: 2005/01/24 22:23:50 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/WalkNode.h ./Behaviors/Nodes/WalkNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/WalkNode.h	Mon Jan 24 17:23:50 2005
+++ ./Behaviors/Nodes/WalkNode.h	Sun Aug  7 00:11:03 2005
@@ -6,67 +6,119 @@
 #include "Motion/MotionManager.h"
 #include "Motion/WalkMC.h"
 #include "Motion/MMAccessor.h"
+#include "Events/LocomotionEvent.h"
+#include "Events/EventRouter.h"
 
 //! A StateNode for walking in a direction
 class WalkNode : public StateNode {
 public:
+	//! lets us interpret values as either distances or velocities
+  enum WalkMode_t {
+		VelocityWalkMode, //!< #x, #y, #a will be interpreted as mm/s
+		DistanceWalkMode //!< #x, #y, #a will be interpreted as millimeters
+	};
+
+public:
 	//!constructor
 	WalkNode()
-		: StateNode("WalkNode"), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(0), y(0), a(0)
+	  : StateNode("WalkNode"), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(0), y(0), a(0), n(-1), walkMode()
 	{}
 
-	//!constructor, positive @a yvel is counter-clockwise from above (to match coordinate system)
+	//!constructor, positive @a yvel is counter-clockwise from above (to match coordinate system), assumes velocity
 	WalkNode(float xvel, float yvel, float avel)
-		: StateNode("WalkNode"), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(xvel), y(yvel), a(avel)
+	  : StateNode("WalkNode"), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(xvel), y(yvel), a(avel), n(-1), walkMode(VelocityWalkMode)
 	{}
 
-	//!constructor, positive @a yvel is counter-clockwise from above (to match coordinate system)
+	//!constructor, positive @a yvel is counter-clockwise from above (to match coordinate system), assumes distance
+	WalkNode(float xvel, float yvel, float avel, int steps)
+	  : StateNode("WalkNode"), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(xvel), y(yvel), a(avel), n(steps), walkMode(DistanceWalkMode)
+	{}
+
+	//!constructor, positive @a yvel is counter-clockwise from above (to match coordinate system), assumes velocity
 	WalkNode(const std::string& name, float xvel, float yvel, float avel)
-		: StateNode("WalkNode",name), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(xvel), y(yvel), a(avel)
+	  : StateNode("WalkNode",name), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(xvel), y(yvel), a(avel), n(-1), walkMode(VelocityWalkMode)
+	{}
+
+	//!constructor, positive @a yvel is counter-clockwise from above (to match coordinate system), assumes distance
+	WalkNode(const std::string& name, float xvel, float yvel, float avel, int steps)
+	  : StateNode("WalkNode",name), walkid(MotionManager::invalid_MC_ID), walkidIsMine(true), x(xvel), y(yvel), a(avel), n(steps), walkMode(DistanceWalkMode)
 	{}
 
 	//!destructor, check if we need to call our teardown
 	~WalkNode() {
-		if(issetup)
-			teardown();
+	  if(issetup)
+	    teardown();
 	}
 
 	//! sets the velocity of the walk
-	void setVelocity(float xvel, float yvel, float avel) {
-		x=xvel;
-		y=yvel;
-		a=avel;
-		updateWalk(x,y,a);
+	void setDisplacement(float xd, float yd, float ad, int np = -1) {
+	  //cout << "SET_DISPLACEMENT" << endl;
+	  //updateWalk(xd,yd,ad,np,false);
+	  storeValues(xd, yd, ad, np, DistanceWalkMode);
+	}
+
+	//! sets the velocity of the walk
+	void setVelocity(float xvel, float yvel, float avel, int np = -1) {
+	  //updateWalk(xvel,yvel,avel,np);
+	  storeValues(xvel, yvel, avel, np, VelocityWalkMode);
 	}
 	
 	//! sets the velocity in x direction (positive is forward)
-	void setXVelocity(float xvel) { x=xvel; updateWalk(x,y,a); }
+	void setXVelocity(float xvel) { x=xvel; storeValues(xvel, y, a, n, VelocityWalkMode); }
 
 	//! returns the velocity in x direction (positive is forward)
 	float getXVelocity() { return x; }
 
 	//! sets the velocity in y direction (positive is forward)
-	void setYVelocity(float yvel) { y=yvel; updateWalk(x,y,a); }
+	void setYVelocity(float yvel) { y=yvel; storeValues(x, yvel, a, n, VelocityWalkMode); }
 
 	//! returns the velocity in y direction (positive is forward)
 	float getYVelocity() { return y; }
 
 	//! sets the velocity of the turn, positive is counter-clockwise from above (to match coordinate system)
-	void setAVelocity(float avel) { a=avel; updateWalk(x,y,a); }
+	void setAVelocity(float avel) { a=avel; storeValues(x, y, avel, n, VelocityWalkMode); }
 
 	//! returns the velocity of the turn, positive is counter-clockwise from above (to match coordinate system)
 	float getAVelocity() { return a; }
 
 	virtual void DoStart() {
 		StateNode::DoStart();
-		updateWalk(x,y,a);
+		if (walkid != MotionManager::invalid_MC_ID) {
+		  erouter->addListener(this, EventBase::locomotionEGID, walkid, EventBase::statusETID);
+		}
+
+	  updateWMC();
 	}
 
 	virtual void DoStop() {
-		updateWalk(0,0,0);
-		StateNode::DoStop();
+	  //added the 0
+	  //cout << "-----------WALK NODE: DoStop()" << endl;
+	  erouter->removeListener(this);
+	  if(walkid!=MotionManager::invalid_MC_ID) {
+	    MMAccessor<WalkMC> walk(walkid);
+	    walk->setTargetVelocity(0,0,0,0);
+	  }
+	  //updateWalk(0,0,0,0);
+	  StateNode::DoStop();
 	}
 
+        //! receive locomotionEGID status event and throw stateMachineEGID status event, ie a completion event
+        virtual void processEvent(const EventBase& e) {
+	  //cout << "PROCESSING WALK EVENTS" << endl;
+	  if (e.getGeneratorID() == EventBase::locomotionEGID) {
+	    const LocomotionEvent le = *reinterpret_cast<const LocomotionEvent*>(&e);
+	    //cout << "LE description: " << le.getDescription() << endl;
+	    //cout << "LE X: " << le.x << " = 0? " << (le.x == 0) << endl;
+	    //cout << "LE Y: " << le.y << " = 0? " << (le.y == 0) << endl;
+	    //cout << "LE A: " << le.a << " = 0? " << (le.a == 0) << endl;
+	    if (le.x == 0 && le.y == 0 && le.a == 0) {
+	      //cout << "Posting Completion Event for Walk." << endl;
+	      postCompletionEvent();
+	    }
+	  }
+        }
+
+
 	//! removes #walkid if #walkidIsMine
 	virtual void teardown() {
 		if(walkidIsMine) {
@@ -82,8 +134,10 @@
 			motman->removeMotion(walkid);
 			walkid=MotionManager::invalid_MC_ID;
 		}
+		erouter->removeListener(this, EventBase::locomotionEGID);
 		walkid=id;
 		walkidIsMine=(id==MotionManager::invalid_MC_ID);
+		erouter->addListener(this, EventBase::locomotionEGID, walkid, EventBase::statusETID);
 	}
 
 	//! use this to access the WalkMC that the WalkNode is using
@@ -93,24 +147,116 @@
 	virtual bool ownsWalkID() { return walkidIsMine; }
 
 protected:
+	//! stores the values and if active, calls updateWMC()
+  void storeValues(float xp, float yp, float ap, int np, WalkMode_t wmode) {
+    x = xp;
+    y = yp;
+    a = ap;
+    n = np;
+    walkMode = wmode;
+
+    if (isActive()) {
+      updateWMC();
+    }
+  }
+
+	//! makes the appropriate calls on the WalkMC
+  void updateWMC() {
+    if(walkid==MotionManager::invalid_MC_ID) {
+      SharedObject<WalkMC> walk;
+      MotionManager::MC_ID id = motman->addPersistentMotion(walk);
+      setWalkID(id);
+      walkidIsMine=true;
+    }
+    MMAccessor<WalkMC> walk(walkid);
+    switch(walkMode) {
+    case VelocityWalkMode:
+      walk->setTargetVelocity(x,y,a,n);
+      break;
+    case DistanceWalkMode:
+      walk->setTargetDisplacement(x,y,a,n); // WalkMC will calculate velocities.
+      break;
+    default:
+      std::cout << "Unknown Walk Mode" << std::endl;
+      break;
+    }
+  }
+
+  /*
+  void updateWMC() {
+    if(walkid==MotionManager::invalid_MC_ID) {
+      SharedObject<WalkMC> walk;
+      switch(walkMode) {
+      case VelocityWalkMode:
+	walk->setTargetVelocity(x,y,a,n);
+	break;
+      case DistanceWalkMode:
+	walk->setTargetDisplacement(x,y,a,n); // WalkMC will calculate velocities.
+	break;
+      default:
+	cout << "Unknown Walk Mode" << endl;
+	break;
+      }
+      MotionManager::MC_ID id = motman->addPersistentMotion(walk);
+      setWalkID(id);
+      walkidIsMine=true;
+    } else {
+      MMAccessor<WalkMC> walk(walkid);
+      switch(walkMode) {
+      case VelocityWalkMode:
+	walk->setTargetVelocity(x,y,a,n);
+	break;
+      case DistanceWalkMode:
+	walk->setTargetDisplacement(x,y,a,n); // WalkMC will calculate velocities.
+	break;
+      default:
+	cout << "Unknown Walk Mode" << endl;
+	break;
+      }
+    }
+  }
+  */
+
+  /*
 	//!if the walk is invalid, create; then set xya
-	void updateWalk(float xvel, float yvel, float avel) {
-		if(walkid==MotionManager::invalid_MC_ID) {
-			SharedObject<WalkMC> walk;
-			walk->setTargetVelocity(xvel,yvel,avel);
-			walkid=motman->addPersistentMotion(walk);
-			walkidIsMine=true;
-		} else {
-			MMAccessor<WalkMC> walk(walkid);
-			walk->setTargetVelocity(xvel,yvel,avel);
-		}
+	void updateWalk(float xp, float yp, float ap, int np=-1, bool isVelocity=true) {
+	  cout << "NNNNNNNNNPPPPPPPPP: " << np << endl;
+	  vector3d velocities;
+	  if(walkid==MotionManager::invalid_MC_ID) {
+	    SharedObject<WalkMC> walk;
+	    if (isVelocity)
+	      walk->setTargetVelocity(xp,yp,ap,np);
+	    else
+	      walk->setTargetDisplacement(xp,yp,ap,np); // WalkMC will calculate velocities.
+	    velocities = walk->getCurVelocity();
+	    MotionManager::MC_ID id = motman->addPersistentMotion(walk);
+	    setWalkID(id);
+	    walkidIsMine=true;
+	  } else {
+	    MMAccessor<WalkMC> walk(walkid);
+	    if (isVelocity)
+	      walk->setTargetVelocity(xp,yp,ap,np);
+	    else
+	      walk->setTargetDisplacement(xp,yp,ap,np); // WalkMC will calculate velocities.
+
+	    velocities = walk->getCurVelocity();  // extract the velocities WalkMC calculated
+	  }
+	  
+	  x = velocities.x;
+	  y = velocities.y;
+	  a = velocities.z;
+	  n = np;
 	}
+  */
 
 	MotionManager::MC_ID walkid; //!< the current WalkMC
 	bool walkidIsMine; //!< true if the walk was created in updateWalk (instead of assigned externally)
-	float x; //!< velocity in x direction (positive is forward)
-	float y; //!< velocity in y direction (positive is dog's left)
-	float a; //!< velocity of the turn, positive is counter-clockwise from above (to match coordinate system)
+	float x; //!< velocity in x direction (positive is forward), or distance if #walkMode is DistanceWalkMode
+	float y; //!< velocity in y direction (positive is dog's left), or distance if #walkMode is DistanceWalkMode
+	float a; //!< velocity of the turn, positive is counter-clockwise from above (to match coordinate system), or distance if #walkMode is DistanceWalkMode
+	int n; //!< number of steps (-1 means walk forever)
+
+  WalkMode_t walkMode; //!< the current interpretation of #x, #y, and #a
 };
 
 /*! @file
@@ -118,10 +264,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.8 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2005/01/24 22:23:50 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/WalkToTargetNode.cc ./Behaviors/Nodes/WalkToTargetNode.cc
--- ../Tekkotsu_2.3/Behaviors/Nodes/WalkToTargetNode.cc	Sat Dec  4 23:47:53 2004
+++ ./Behaviors/Nodes/WalkToTargetNode.cc	Sat Dec  4 23:47:53 2004
@@ -74,7 +74,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.1 $
  * $State: Exp $
  * $Date: 2004/12/05 04:47:53 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Nodes/WalkToTargetNode.h ./Behaviors/Nodes/WalkToTargetNode.h
--- ../Tekkotsu_2.3/Behaviors/Nodes/WalkToTargetNode.h	Wed Dec  8 14:05:50 2004
+++ ./Behaviors/Nodes/WalkToTargetNode.h	Wed Dec  8 14:05:50 2004
@@ -54,7 +54,7 @@
  * @author ejt (Creator)
  *
  * $Author: lkirtane $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Exp $
  * $Date: 2004/12/08 19:05:50 $
diff -urdN ../Tekkotsu_2.3/Behaviors/StateNode.cc ./Behaviors/StateNode.cc
--- ../Tekkotsu_2.3/Behaviors/StateNode.cc	Mon Jan 24 17:12:13 2005
+++ ./Behaviors/StateNode.cc	Fri Apr 15 17:30:55 2005
@@ -2,9 +2,6 @@
 #include "Events/EventRouter.h"
 #include "Wireless/Wireless.h"
 
-/*! @deprecated, behavior constructors should take a name argument (which by default should be the name of the type of the class) */
-StateNode::StateNode() : BehaviorBase("StateNode"), parent(NULL), transitions(), issetup(false), retain(true), startedTime(0), nodes() {}
-
 StateNode::~StateNode() {
 	ASSERT(!isActive(), "Destructing while active?")
 	for(std::vector<Transition*>::iterator it=transitions.begin(); it!=transitions.end(); it++)
@@ -13,8 +10,8 @@
 		teardown();
 		if(issetup) {
 			serr->printf("WARNING %s doesn't seem to call StateNode::teardown() in its\n"
-									 "        implementation of the function: issetup=%d, nodes.size()=%d\n"
-									 "        Attempting to recover...\n",getClassName().c_str(),issetup,nodes.size());
+			             "        implementation of the function: issetup=%d, nodes.size()=%lu\n"
+			             "        Attempting to recover...\n",getClassName().c_str(),issetup,(unsigned long)nodes.size());
 			StateNode::teardown();
 		}
 	}
@@ -43,9 +40,13 @@
     setup();
     issetup=true;
   }
-  for(std::vector<Transition*>::iterator it=transitions.begin(); it!=transitions.end(); it++)
-    if ( !(*it)->isActive()  ) (*it)->DoStart();
   postStartEvent();
+  for(std::vector<Transition*>::iterator it=transitions.begin(); it!=transitions.end(); it++) {
+    if ( !(*it)->isActive()  )
+			(*it)->DoStart();
+		if(!isActive()) //a transition fired upon its start
+			break;
+	}
 }
 
 void StateNode::DoStop() {
@@ -60,8 +61,8 @@
 		teardown();
 		if(issetup) {
 			serr->printf("WARNING %s doesn't seem to call StateNode::teardown() in its\n"
-									 "        implementation of the function: issetup=%d, nodes.size()=%d\n"
-									 "        Attempting to recover...\n",getClassName().c_str(),issetup,nodes.size());
+			             "        implementation of the function: issetup=%d, nodes.size()=%lu\n"
+			             "        Attempting to recover...\n",getClassName().c_str(),issetup,(unsigned long)nodes.size());
 			StateNode::teardown();
 		}
 	}
@@ -94,9 +95,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.22 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.25 $
  * $State: Exp $
- * $Date: 2005/01/24 22:12:13 $
+ * $Date: 2005/04/15 21:30:55 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/StateNode.h ./Behaviors/StateNode.h
--- ../Tekkotsu_2.3/Behaviors/StateNode.h	Mon Jan 24 17:12:13 2005
+++ ./Behaviors/StateNode.h	Sun Aug  7 00:11:02 2005
@@ -8,12 +8,13 @@
 #include <string>
 
 //! Recursive data structure - both a state machine controller as well as a node within a state machine itself
-/*! Override setup() to setup your own Transition and StateNode network.*/
+/*! Override setup() to setup your own Transition and StateNode network.
+ *  There are two StateNode templates in <a href="http://cvs.tekkotsu.org/cgi-bin/viewcvs.cgi/Tekkotsu/project/templates/"><i>project</i><tt>/templates/</tt></a>: <a href="http://cvs.tekkotsu.org/cgi-bin/viewcvs.cgi/Tekkotsu/project/templates/statenode.h?rev=HEAD&content-type=text/vnd.viewcvs-markup">statenode.h</a> and <a href="http://cvs.tekkotsu.org/cgi-bin/viewcvs.cgi/Tekkotsu/project/templates/statemachine.h?rev=HEAD&content-type=text/vnd.viewcvs-markup">statemachine.h</a>.
+ *  statenode.h is meant for leaf nodes, which directly implement the execution of a task.
+ *  statemachine.h is meant for nodes which contain a network of transitions and subnodes, which together solve the task.
+*/
 class StateNode  : public BehaviorBase {
 public:
-	//! deprecated, behavior constructors should take a name argument (which by default should be the name of the type of the class)
-	StateNode() __attribute__((deprecated));
-
 	//!constructor, pass a name to use
 	StateNode(const std::string& name) : BehaviorBase("StateNode",name), parent(NULL), transitions(), issetup(false), retain(true), startedTime(0), nodes() {}
 
@@ -29,7 +30,7 @@
 	//!Returns the const std::vector of transitions so you can read through them if need be
 	const std::vector<Transition*>& getTransitions() const { return transitions; }
 
-	//!Adds a StateNode to #nodes so it can be automatically dereferenced later, returns what it's passed (for convenience), calls AddReference() on @a node.  Also sets the node's parent to #this if it is null.
+	//!Adds a StateNode to #nodes so it can be automatically dereferenced later, returns what it's passed (for convenience), calls AddReference() on @a node.  Also sets the node's parent to @c this if it is null.
 	virtual StateNode* addNode(StateNode* node);
 
 	//!Returns the std::vector of sub-nodes so you can modify them yourself if need be
@@ -104,10 +105,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.17 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.20 $
  * $State: Exp $
- * $Date: 2005/01/24 22:12:13 $
+ * $Date: 2005/08/07 04:11:02 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Transition.cc ./Behaviors/Transition.cc
--- ../Tekkotsu_2.3/Behaviors/Transition.cc	Fri Dec 17 00:51:32 2004
+++ ./Behaviors/Transition.cc	Wed Aug  3 14:47:58 2005
@@ -1,26 +1,9 @@
 #include "Transition.h"
 #include "StateNode.h"
 #include "Wireless/Wireless.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Events/EventRouter.h"
 
-/*! @deprecated, use the version of the constructor where you can pass a name */
-Transition::Transition() : BehaviorBase("Transition"), srcs(), dsts(), sound() {}
-
-/*! @deprecated, use the version of the constructor where you can pass a name */
-Transition::Transition(StateNode* destination)
-	: BehaviorBase("Transition"), srcs(), dsts(), sound()
-{
-	addDestination(destination);
-}
-
-
-/*! @deprecated: use #fire() instead (just a better name) */
-void Transition::activate() {
-	serr->printf("Transition::activate() is deprecated.  Use Transition::fire() instead.\n");
-	fire();
-}
-
 void Transition::fire() {
 	//serr->printf("%s fire() - enter %d\n",getName().c_str(),get_time());
 
@@ -53,7 +36,7 @@
 		ans+="--"+instanceName+"-->";
 		ans+='{';
 		for(unsigned int i=0; i<dsts.size(); i++)
-			ans+=dsts[i]->getName()+(i<srcs.size()-1?',':'}');
+			ans+=dsts[i]->getName()+(i<dsts.size()-1?',':'}');
 		return ans;
 	}
 } 
@@ -63,9 +46,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.13 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.16 $
  * $State: Exp $
- * $Date: 2004/12/17 05:51:32 $
+ * $Date: 2005/08/03 18:47:58 $
  */
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Transition.h ./Behaviors/Transition.h
--- ../Tekkotsu_2.3/Behaviors/Transition.h	Mon Nov 15 17:46:19 2004
+++ ./Behaviors/Transition.h	Sun Aug  7 00:11:02 2005
@@ -31,6 +31,9 @@
  *  simpler because it doesn't have to worry about recursive looping
  *  depending whether the source was added to the transition or the
  *  transition was added to the source.  Confusing?  Exactly.
+ *
+ *  A template file is available at <a href="http://cvs.tekkotsu.org/cgi-bin/viewcvs.cgi/Tekkotsu/project/templates/transition.h?rev=HEAD&content-type=text/vnd.viewcvs-markup"><i>project</i><tt>/templates/transition.h</tt></a>,
+ *  which will help you get moving faster.
  */
 class Transition : public BehaviorBase {
 	friend class StateNode;
@@ -41,9 +44,6 @@
 	//!call this when the transition should be made, base class version simply calls StateNode::DoStop() on each active of #srcs and StateNode::DoStart() on each inactive of #dsts, but you can override.
 	virtual void fire();
 
-  //!deprecated: use #fire() instead (just a better name
-  virtual void activate() __attribute__((deprecated));
-
 	virtual std::vector<StateNode*>& getSources() { return srcs; }  //!< returns a user-modifiable reference to the current source list
 	virtual const std::vector<StateNode*>& getSources() const { return srcs; } //!< returns a const reference to the current source list
 
@@ -58,12 +58,8 @@
 	virtual std::string getName() const;
 
 protected:
-	//! deprecated, use the version of the constructor where you can pass a name
-	Transition() __attribute__((deprecated));
 	//!constructor, pass your subclass type name as a string for the default name
 	explicit Transition(const std::string& classname) : BehaviorBase(classname), srcs(), dsts(), sound() {}
-	//! deprecated, use the version of the constructor where you can pass a name
-	explicit Transition(StateNode* destination) __attribute__((deprecated));
 	//!constructor, specify destination StateNode (ignores NULL)
 	Transition(const std::string& classname, StateNode* destination) : BehaviorBase(classname), srcs(), dsts(), sound() {
 		addDestination(destination);
@@ -95,10 +91,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.12 $
  * $State: Exp $
- * $Date: 2004/11/15 22:46:19 $
+ * $Date: 2005/08/07 04:11:02 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Entries ./Behaviors/Transitions/CVS/Entries
--- ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Transitions/CVS/Entries	Wed Aug 10 11:03:18 2005
@@ -0,0 +1,14 @@
+/CompareTrans.h/1.10/Fri Apr 15 21:31:15 2005//Ttekkotsu-2_4
+/CompletionTrans.h/1.9/Thu Dec 23 01:47:07 2004//Ttekkotsu-2_4
+/ConnectionMadeTrans.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/EventTrans.h/1.6/Thu Dec 23 01:47:07 2004//Ttekkotsu-2_4
+/LostTargetTrans.h/1.4/Tue Jan  4 19:51:41 2005//Ttekkotsu-2_4
+/NullTrans.h/1.8/Thu Dec 23 01:47:07 2004//Ttekkotsu-2_4
+/RandomTrans.cc/1.3/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/RandomTrans.h/1.3/Tue Jan  4 19:51:41 2005//Ttekkotsu-2_4
+/SmoothCompareTrans.h/1.11/Tue Dec 14 03:24:57 2004//Ttekkotsu-2_4
+/TextMsgTrans.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/TimeOutTrans.h/1.15/Sat Dec  4 00:11:19 2004//Ttekkotsu-2_4
+/VisualTargetCloseTrans.h/1.15/Mon Jun 13 21:22:41 2005//Ttekkotsu-2_4
+/VisualTargetTrans.h/1.14/Mon Jun 13 21:23:01 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Repository ./Behaviors/Transitions/CVS/Repository
--- ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Transitions/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Behaviors/Transitions
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Root ./Behaviors/Transitions/CVS/Root
--- ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Transitions/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Tag ./Behaviors/Transitions/CVS/Tag
--- ../Tekkotsu_2.3/Behaviors/Transitions/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Transitions/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/CompareTrans.h ./Behaviors/Transitions/CompareTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/CompareTrans.h	Mon Nov 15 17:46:19 2004
+++ ./Behaviors/Transitions/CompareTrans.h	Fri Apr 15 17:31:15 2005
@@ -34,18 +34,29 @@
 		NE //!< not equal
 	};
 	
+	//! constructor, only checks @a monitor when it is first activated (no polling)
+  CompareTrans(StateNode* destination, const T* monitor, Test_t test, const T& value)
+		: Transition("CompareTrans",destination), mon(monitor), tst(test), val(value), isPolling(false), poller()
+	{ }
+	
 	//! constructor, see CompareTrans class notes for information
   CompareTrans(StateNode* destination, const T* monitor, Test_t test, const T& value, const EventBase& poll)
-		: Transition("CompareTrans",destination), mon(monitor), tst(test), val(value), poller(poll)
+		: Transition("CompareTrans",destination), mon(monitor), tst(test), val(value), isPolling(true), poller(poll)
 	{ }
 	
 	//! constructor, see CompareTrans class notes for information
   CompareTrans(const std::string& name, StateNode* destination, const T* monitor, Test_t test, const T& value, const EventBase& poll)
-		: Transition("CompareTrans",name,destination), mon(monitor), tst(test), val(value), poller(poll)
+		: Transition("CompareTrans",name,destination), mon(monitor), tst(test), val(value), isPolling(true), poller(poll)
 	{ }
 	
 	//!starts listening
-	virtual void DoStart() { Transition::DoStart(); erouter->addListener(this,poller); }
+	virtual void DoStart() {
+		Transition::DoStart();
+		if(isPolling)
+			erouter->addListener(this,poller);
+		else
+			processEvent(EventBase());
+	}
 
 	//!stops listening
 	virtual void DoStop() { erouter->removeListener(this); Transition::DoStop(); }
@@ -75,14 +86,19 @@
 	}
 
 protected:
+	//! constructor (no polling), see CompareTrans class notes for information (this version is only need by subclasses so they can pass their type name)
+  CompareTrans(const std::string& classname, const std::string& instancename, StateNode* destination, const T* monitor, Test_t test, const T& value)
+		: Transition(classname,instancename,destination), mon(monitor), tst(test), val(value), isPolling(false), poller()
+	{ }
 	//! constructor, see CompareTrans class notes for information (this version is only need by subclasses so they can pass their type name)
   CompareTrans(const std::string& classname, const std::string& instancename, StateNode* destination, const T* monitor, Test_t test, const T& value, const EventBase& poll)
-		: Transition(classname,instancename,destination), mon(monitor), tst(test), val(value), poller(poll)
+		: Transition(classname,instancename,destination), mon(monitor), tst(test), val(value), isPolling(true), poller(poll)
 	{ }
 
 	const T* mon; //!< address of value to monitor
 	Test_t tst; //!< test to make
 	T val; //!< value to compare against
+	bool isPolling; //!< set to true if #poller should be used (otherwise only checked on activation)
 	EventBase poller; //!< event to listen to, when it comes, compare the values
 
 private:
@@ -95,10 +111,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/11/15 22:46:19 $
+ * $Date: 2005/04/15 21:31:15 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/CompletionTrans.h ./Behaviors/Transitions/CompletionTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/CompletionTrans.h	Wed Dec 22 20:47:07 2004
+++ ./Behaviors/Transitions/CompletionTrans.h	Wed Dec 22 20:47:07 2004
@@ -72,7 +72,7 @@
  * @author dst (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.9 $
  * $State: Exp $
  * $Date: 2004/12/23 01:47:07 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/ConnectionMadeTrans.h ./Behaviors/Transitions/ConnectionMadeTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/ConnectionMadeTrans.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Transitions/ConnectionMadeTrans.h	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,59 @@
+//-*-c++-*-
+#ifndef INCLUDED_ConnectionMadeTrans_h_
+#define INCLUDED_ConnectionMadeTrans_h_
+
+#include "Behaviors/Transition.h"
+#include "Events/EventRouter.h"
+#include "Wireless/Wireless.h"
+
+//! a transition that occurs as soon as a connection is made
+class ConnectionMadeTrans : public Transition {
+public:
+
+  //! constructor
+  ConnectionMadeTrans(StateNode* destination, Socket* sock) : Transition("ConnectionMadeTrans",destination), socket(sock) {}
+	
+  //! constructor
+  ConnectionMadeTrans(const std::string& name, StateNode* destination, Socket* sock) : 
+    Transition("ConnectionMadeTrans",name,destination), socket(sock) {}
+	
+  //!starts 32 msec timer with sid=0
+  virtual void DoStart() {
+    Transition::DoStart();
+    erouter->addTimer(this,0,32,true);
+  }
+
+  //!stops timer
+  virtual void DoStop() { erouter->removeListener(this); Transition::DoStop(); }
+
+  //!when timer event is received, fire() the transition
+  virtual void processEvent(const EventBase&) { 
+    if(socket!=NULL && wireless->isConnected(socket->sock)) {
+      fire();
+    }
+  }
+
+protected:
+  //! constructor, only to be called by subclasses (which need to specify their own @a classname)
+  ConnectionMadeTrans(const std::string &classname, const std::string &instancename, StateNode* destination, Socket* sock) :
+    Transition(classname,instancename,destination), socket(sock) {}
+  ConnectionMadeTrans(const ConnectionMadeTrans&);     //!< DON'T CALL THIS
+  ConnectionMadeTrans& operator=(const ConnectionMadeTrans&);  //!< DON'T CALL THIS
+  
+
+
+  Socket* socket; //!< the socket to expect the connection on
+};
+
+/*! @file
+ * @brief Defines ConnectionMadeTrans, which causes a transition as soon as a connection is made
+ * @author klibby (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/EventTrans.h ./Behaviors/Transitions/EventTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/EventTrans.h	Wed Dec 22 20:47:07 2004
+++ ./Behaviors/Transitions/EventTrans.h	Wed Dec 22 20:47:07 2004
@@ -68,7 +68,7 @@
  * @author dst (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.6 $
  * $State: Exp $
  * $Date: 2004/12/23 01:47:07 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/LostTargetTrans.h ./Behaviors/Transitions/LostTargetTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/LostTargetTrans.h	Tue Jan  4 14:51:41 2005
+++ ./Behaviors/Transitions/LostTargetTrans.h	Tue Jan  4 14:51:41 2005
@@ -68,7 +68,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Exp $
  * $Date: 2005/01/04 19:51:41 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/NullTrans.h ./Behaviors/Transitions/NullTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/NullTrans.h	Wed Dec 22 20:47:07 2004
+++ ./Behaviors/Transitions/NullTrans.h	Wed Dec 22 20:47:07 2004
@@ -40,7 +40,7 @@
  * @author dst (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Exp $
  * $Date: 2004/12/23 01:47:07 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/RandomTrans.cc ./Behaviors/Transitions/RandomTrans.cc
--- ../Tekkotsu_2.3/Behaviors/Transitions/RandomTrans.cc	Sun Nov 28 00:58:38 2004
+++ ./Behaviors/Transitions/RandomTrans.cc	Wed Jun  1 01:47:46 2005
@@ -2,7 +2,7 @@
 #include <vector>
 
 #include "../BehaviorBase.h"
-#include "../../SoundPlay/SoundManager.h"
+#include "../../Sound/SoundManager.h"
 #include "../StateNode.h"
 #include "RandomTrans.h"
 
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/SmoothCompareTrans.h ./Behaviors/Transitions/SmoothCompareTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/SmoothCompareTrans.h	Mon Dec 13 22:24:57 2004
+++ ./Behaviors/Transitions/SmoothCompareTrans.h	Mon Dec 13 22:24:57 2004
@@ -73,7 +73,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.11 $
  * $State: Exp $
  * $Date: 2004/12/14 03:24:57 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/TextMsgTrans.h ./Behaviors/Transitions/TextMsgTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/TextMsgTrans.h	Wed Dec 31 19:00:00 1969
+++ ./Behaviors/Transitions/TextMsgTrans.h	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,86 @@
+//-*-c++-*-
+#ifndef INCLUDED_TextMsgTrans_h_
+#define INCLUDED_TextMsgTrans_h_
+
+#include "Behaviors/Transition.h"
+#include "Events/TextMsgEvent.h"
+
+//! Fires when a matching string is received
+class TextMsgTrans : public Transition {
+
+	// **************************** //
+	// ******* CONSTRUCTORS ******* //
+	// **************************** //
+public:
+	//! default constructor, use type name as instance name
+	TextMsgTrans(StateNode* destination, const std::string& trigger )
+		: Transition("TextMsgTrans",destination), msg(trigger)
+	{}
+
+protected:
+  //! constructor for subclasses (which would need to provide a different class name)
+  TextMsgTrans(const std::string &class_name, const std::string &instance_name, StateNode* destination, const std::string& trigger )
+    : Transition(class_name,instance_name,destination), msg(trigger)
+	{}
+	
+	
+	// **************************** //
+	// ********* METHODS ********** //
+	// **************************** //
+public:
+	//! Just like a behavior, called when it's time to start doing your thing
+	virtual void DoStart() {
+		Transition::DoStart(); // do this first (required)
+		erouter->addListener(this, EventBase::textmsgEGID );
+	}
+
+	virtual void processEvent(const EventBase& event) {
+		const TextMsgEvent *e = dynamic_cast<const TextMsgEvent*>(&event);
+		if(e==NULL)
+			return;
+		if(e->getText()==msg)
+			fire();
+	}
+
+	//! Just like a behavior, called when it's time to stop doing your thing
+	virtual void DoStop() {
+		erouter->removeListener(this); //generally a good idea, unsubscribe all
+		Transition::DoStop(); // do this last (required)
+	}
+
+	static std::string getClassDescription() { return "Fires when a matching string is received"; }
+	virtual std::string getDescription() const { return getClassDescription(); }
+
+
+	// **************************** //
+	// ********* MEMBERS ********** //
+	// **************************** //
+protected:
+	std::string msg; //!< the trigger to match messages against
+
+
+	// **************************** //
+	// ********** OTHER *********** //
+	// **************************** //
+private:
+	// Providing declarations for these functions will avoid a compiler warning if
+	// you have any class members which are pointers.  However, as it is, an error
+	// will result if you inadvertantly cause a call to either (which is probably
+	// a good thing, unless you really intended to copy/assign a behavior, in
+	// which case simply provide implementations for the functions)
+	TextMsgTrans(const TextMsgTrans&); //!< don't call (copy constructor)
+	TextMsgTrans& operator=(const TextMsgTrans&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines TextMsgTrans, which fires when a matching string is received
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/TimeOutTrans.h ./Behaviors/Transitions/TimeOutTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/TimeOutTrans.h	Fri Dec  3 19:11:19 2004
+++ ./Behaviors/Transitions/TimeOutTrans.h	Fri Dec  3 19:11:19 2004
@@ -86,7 +86,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.15 $
  * $State: Exp $
  * $Date: 2004/12/04 00:11:19 $
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/VisualTargetCloseTrans.h ./Behaviors/Transitions/VisualTargetCloseTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/VisualTargetCloseTrans.h	Mon Nov 15 17:46:19 2004
+++ ./Behaviors/Transitions/VisualTargetCloseTrans.h	Mon Jun 13 17:22:41 2005
@@ -14,10 +14,12 @@
 class VisualTargetCloseTrans : public Transition {
 public:
 	//!constructor
-	VisualTargetCloseTrans(StateNode* destination, unsigned int source_id) : Transition("VisualTargetCloseTrans",destination), sid(source_id) {}
+	VisualTargetCloseTrans(StateNode* destination, unsigned int source_id, float threshold=225)
+		: Transition("VisualTargetCloseTrans",destination), sid(source_id), distanceThreshold(threshold) {}
 
 	//!constructor
-	VisualTargetCloseTrans(const std::string& name, StateNode* destination, unsigned int source_id) : Transition("VisualTargetCloseTrans",name,destination), sid(source_id) {}
+	VisualTargetCloseTrans(const std::string& name, StateNode* destination, unsigned int source_id, float threshold=225)
+		: Transition("VisualTargetCloseTrans",name,destination), sid(source_id), distanceThreshold(threshold) {}
 
 	//!starts listening for the object specified by the source id in the constructor
 	virtual void DoStart() { Transition::DoStart(); erouter->addListener(this,EventBase::visObjEGID,sid); }
@@ -40,13 +42,16 @@
 			IRDistOffset=ERS220Info::IRDistOffset;
 		else if(state->robotDesign & WorldState::ERS7Mask)
 			IRDistOffset=ERS7Info::NearIRDistOffset;
-		if(x*x+y*y<0.02f && IRDistOffset!=-1U && state->sensors[IRDistOffset]<225)
+		if(x*x+y*y<0.02f && IRDistOffset!=-1U && state->sensors[IRDistOffset]<distanceThreshold)
 			fire();
 	}
 
 protected:
 	//!Source ID of object to track
 	unsigned int sid;
+	
+	//!Distance at which to trigger transition, in millimeters
+	float distanceThreshold;
 };
 
 /*! @file
@@ -54,10 +59,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2004/11/15 22:46:19 $
+ * $Date: 2005/06/13 21:22:41 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Behaviors/Transitions/VisualTargetTrans.h ./Behaviors/Transitions/VisualTargetTrans.h
--- ../Tekkotsu_2.3/Behaviors/Transitions/VisualTargetTrans.h	Mon Nov 15 17:46:19 2004
+++ ./Behaviors/Transitions/VisualTargetTrans.h	Mon Jun 13 17:23:01 2005
@@ -7,7 +7,7 @@
 #include "Shared/debuget.h"
 #include "Shared/WorldState.h"
 
-//! causes a transition when a visual object is "close"
+//! causes a transition when a visual object has been seen for at least 6 camera frames
 class VisualTargetTrans : public Transition {
 public:
 	//!constructor
@@ -58,14 +58,14 @@
 };
 
 /*! @file
- * @brief Defines VisualTargetTrans, which causes a transition when a visual object is seen for a few frames
+ * @brief Defines VisualTargetTrans, which causes a transition when a visual object has been seen for at least 6 camera frames
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.13 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.14 $
  * $State: Exp $
- * $Date: 2004/11/15 22:46:19 $
+ * $Date: 2005/06/13 21:23:01 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/CVS/Entries ./CVS/Entries
--- ../Tekkotsu_2.3/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,19 @@
+/INSTALL/1.1/Sat Aug 23 23:25:37 2003//Ttekkotsu-2_4
+/Makefile/1.33/Sun Aug  7 04:11:02 2005//Ttekkotsu-2_4
+/README/1.8/Tue Aug  9 23:10:47 2005//Ttekkotsu-2_4
+/common.h/1.3/Fri Jul  1 19:45:42 2005//Ttekkotsu-2_4
+/entry.h/1.2/Sat Jul 17 03:38:01 2004//Ttekkotsu-2_4
+/license.txt/1.1/Thu Apr  1 00:16:51 2004//Ttekkotsu-2_4
+D/Behaviors////
+D/Events////
+D/IPC////
+D/Motion////
+D/Shared////
+D/Sound////
+D/Vision////
+D/Wireless////
+D/aperios////
+D/docs////
+D/local////
+D/project////
+D/tools////
diff -urdN ../Tekkotsu_2.3/CVS/Repository ./CVS/Repository
--- ../Tekkotsu_2.3/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu
diff -urdN ../Tekkotsu_2.3/CVS/Root ./CVS/Root
--- ../Tekkotsu_2.3/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/CVS/Tag ./CVS/Tag
--- ../Tekkotsu_2.3/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Events/CVS/Entries ./Events/CVS/Entries
--- ../Tekkotsu_2.3/Events/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Events/CVS/Entries	Wed Aug 10 11:03:18 2005
@@ -0,0 +1,20 @@
+/DataEvent.h/1.3/Wed Jun 29 22:03:34 2005//Ttekkotsu-2_4
+/EventBase.cc/1.25/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/EventBase.h/1.34/Wed Jun 29 22:03:34 2005//Ttekkotsu-2_4
+/EventGeneratorBase.cc/1.4/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/EventGeneratorBase.h/1.10/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/EventListener.h/1.2/Thu Sep 25 15:27:10 2003//Ttekkotsu-2_4
+/EventRouter.cc/1.18/Thu Jul  7 22:34:15 2005//Ttekkotsu-2_4
+/EventRouter.h/1.21/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/EventTranslator.cc/1.15/Tue Jul 26 03:11:23 2005//Ttekkotsu-2_4
+/EventTranslator.h/1.9/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/EventTrapper.h/1.2/Thu Sep 25 15:27:10 2003//Ttekkotsu-2_4
+/FilterBankEvent.h/1.11/Wed Jun 29 22:03:35 2005//Ttekkotsu-2_4
+/LocomotionEvent.cc/1.4/Wed Jun 29 22:03:35 2005//Ttekkotsu-2_4
+/LocomotionEvent.h/1.8/Wed Jun 29 22:03:35 2005//Ttekkotsu-2_4
+/SegmentedColorFilterBankEvent.h/1.4/Wed Jun 29 22:03:35 2005//Ttekkotsu-2_4
+/TextMsgEvent.cc/1.3/Fri Jun 10 17:26:30 2005//Ttekkotsu-2_4
+/TextMsgEvent.h/1.12/Wed Jun 29 22:03:35 2005//Ttekkotsu-2_4
+/VisionObjectEvent.cc/1.9/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/VisionObjectEvent.h/1.15/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Events/CVS/Repository ./Events/CVS/Repository
--- ../Tekkotsu_2.3/Events/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Events/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Events
diff -urdN ../Tekkotsu_2.3/Events/CVS/Root ./Events/CVS/Root
--- ../Tekkotsu_2.3/Events/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Events/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Events/CVS/Tag ./Events/CVS/Tag
--- ../Tekkotsu_2.3/Events/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Events/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Events/DataEvent.h ./Events/DataEvent.h
--- ../Tekkotsu_2.3/Events/DataEvent.h	Sun Jan 18 05:16:57 2004
+++ ./Events/DataEvent.h	Wed Jun 29 18:03:34 2005
@@ -13,6 +13,14 @@
 	DataEvent() : EventBase() {}
 	DataEvent(const T& d, EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur=0) : EventBase(gid,sid,tid,dur), data(d) {}
 	DataEvent(const T& d, EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur, const std::string& n, float mag) : EventBase(gid,sid,tid,dur,n,mag), data(d) {}
+
+	//! copy constructor
+	DataEvent(const DataEvent& evt) : EventBase(evt), data(evt.data) {}
+	
+	//! assignment
+	const DataEvent& operator=(const DataEvent& evt) { EventBase::operator=(evt); data=evt.data; return *this; }
+
+	virtual EventBase* clone() const { return new DataEvent<T>(*this); }
 	//@}
 
 	void setData(const T& d) { data=d; } //!< assigns @a d to the internal #data
@@ -21,10 +29,6 @@
 
 protected:
 	T data; //!< the data being communicated
-
-private:
-	DataEvent(const DataEvent& fbk); //!< don't call
-	const DataEvent& operator=(const DataEvent& fbk); //!< don't call
 };
 
 /*! @file
@@ -32,10 +36,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.2 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
  * $State: Exp $
- * $Date: 2004/01/18 10:16:57 $
+ * $Date: 2005/06/29 22:03:34 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/EventBase.cc ./Events/EventBase.cc
--- ../Tekkotsu_2.3/Events/EventBase.cc	Wed Dec 22 18:54:07 2004
+++ ./Events/EventBase.cc	Wed Jun  1 01:47:46 2005
@@ -1,6 +1,8 @@
 #include "EventBase.h"
 #include <stdio.h>
 #include <sstream>
+#include <libxml/tree.h>
+#include "Shared/debuget.h"
 
 const char* const EventBase::EventGeneratorNames[numEGIDs] = {
 	"unknownEGID",
@@ -18,7 +20,7 @@
 	"sensorEGID",
 	"stateMachineEGID",
 	"stateTransitionEGID",
-	"testmsgEGID",
+	"textmsgEGID",
 	"timerEGID",
 	"visOFbkEGID",
 	"visRawCameraEGID",
@@ -32,15 +34,22 @@
 	"worldModelEGID",
 };
 
+const char* const EventBase::EventTypeNames[numETIDs] = {
+	"activate",
+	"status",
+	"deactivate"
+};
+
+const char* const EventBase::EventTypeAbbr[numETIDs] = { "A", "S", "D" };
 
 EventBase::EventBase()
-	: LoadSave(), stim_id(), magnitude(0), timestamp(get_time()), nameisgen(true), genID(unknownEGID), typeID(statusETID), sourceID((unsigned int)-1), duration(0)
+	: XMLLoadSave(), stim_id(), magnitude(0), timestamp(get_time()), saveFormat(XML), nameisgen(true), genID(unknownEGID), typeID(statusETID), sourceID((unsigned int)-1), duration(0)
 {
 	genName();
 }
 
 EventBase::EventBase(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur)
-	: LoadSave(), stim_id(), magnitude(0), timestamp(get_time()), nameisgen(true), genID(gid), typeID(tid), sourceID(sid), duration(dur)
+	: XMLLoadSave(), stim_id(), magnitude(0), timestamp(get_time()), saveFormat(XML), nameisgen(true), genID(gid), typeID(tid), sourceID(sid), duration(dur)
 {
 	genName();
 	if(tid==deactivateETID)
@@ -49,8 +58,18 @@
 		setMagnitude(1.0);
 }
 
+EventBase::EventBase(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur, const std::string& n)
+	: XMLLoadSave(), stim_id(), magnitude(0), timestamp(get_time()), saveFormat(XML), nameisgen(true), genID(gid), typeID(tid), sourceID(sid), duration(dur)
+{
+	setName(n);
+	if(tid==deactivateETID)
+		setMagnitude(0.0);
+	else
+		setMagnitude(1.0);
+}
+
 EventBase::EventBase(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur, const std::string& n, float mag)
-	: LoadSave(), stim_id(), magnitude(mag), timestamp(get_time()), nameisgen(true), genID(gid), typeID(tid), sourceID(sid), duration(dur)
+	: XMLLoadSave(), stim_id(), magnitude(mag), timestamp(get_time()), saveFormat(XML), nameisgen(true), genID(gid), typeID(tid), sourceID(sid), duration(dur)
 {
 	setName(n);
 }
@@ -69,16 +88,7 @@
 	stim_id+=',';
 	stim_id+=sourcename;
 	stim_id+=',';
-	switch(getTypeID()) {
-	case EventBase::activateETID:
-		stim_id+='A'; break;
-	case EventBase::statusETID:
-		stim_id+='S'; break;
-	case EventBase::deactivateETID:
-		stim_id+='D'; break;
-	default:
-		stim_id+='U'; break; //unknown
-	}
+	stim_id+=EventTypeAbbr[getTypeID()];
 	stim_id+=')';
 	nameisgen=false;
 	return *this;
@@ -99,6 +109,8 @@
 
 unsigned int
 EventBase::getBinSize() const {
+	if(saveFormat==XML)
+		return XMLLoadSave::getBinSize();
 	unsigned int used=0;
 	used+=creatorSize("EventBase");
 	used+=stim_id.size()+stringpad;
@@ -113,7 +125,7 @@
 }
 
 unsigned int
-EventBase::LoadBuffer(const char buf[], unsigned int len) {
+EventBase::LoadBinaryBuffer(const char buf[], unsigned int len) {
 	unsigned int origlen=len;
 	unsigned int used=0;
 	if(0==(used=checkCreator("EventBase",buf,len,true))) return 0;
@@ -141,7 +153,7 @@
 }
 
 unsigned int
-EventBase::SaveBuffer(char buf[], unsigned int len) const {
+EventBase::SaveBinaryBuffer(char buf[], unsigned int len) const {
 	unsigned int origlen=len;
 	unsigned int used=0;
 	if(0==(used=saveCreator("EventBase",buf,len))) return 0;
@@ -165,6 +177,84 @@
 	return origlen-len;
 }
 
+void EventBase::LoadXML(xmlNode* node) {
+	if(xmlStrcmp(node->name, (const xmlChar *)"event"))
+		throw bad_format(node,"Load of the wrong type -- expecting 'event' node");
+	unsigned int i;
+	xmlChar* str = xmlGetProp(node,(const xmlChar*)"egid");
+	if(str==NULL)
+		throw bad_format(node,"missing generator id");
+	for(i=0; i<numEGIDs; i++) {
+		if(xmlStrcmp(str,(const xmlChar*)EventGeneratorNames[i])==0)
+			break;
+	}
+	xmlFree(str);
+	if(i==numEGIDs)
+		throw bad_format(node,"bad event generator name");
+	genID=static_cast<EventGeneratorID_t>(i);
+	str = xmlGetProp(node,(const xmlChar*)"sid");
+	if(str==NULL)
+		throw bad_format(node,"missing source id");
+	sourceID=atoi((const char*)str);
+	xmlFree(str);
+	str = xmlGetProp(node,(const xmlChar*)"etid");
+	if(str==NULL)
+		throw bad_format(node,"missing type id");
+	for(i=0; i<numETIDs; i++) {
+		if(xmlStrcmp(str,(const xmlChar*)EventTypeAbbr[i])==0)
+			break;
+		if(xmlStrcmp(str,(const xmlChar*)EventTypeNames[i])==0)
+			break;
+	}
+	xmlFree(str);
+	if(i==numETIDs)
+		throw bad_format(node,"bad event type name");
+	typeID=static_cast<EventTypeID_t>(i);
+	str = xmlGetProp(node,(const xmlChar*)"time");
+	if(str==NULL)
+		throw bad_format(node,"missing timestamp");
+	timestamp=atoi((const char*)str);
+	xmlFree(str);
+	str = xmlGetProp(node,(const xmlChar*)"duration");
+	if(str==NULL)
+		throw bad_format(node,"missing duration");
+	duration=atoi((const char*)str);
+	xmlFree(str);
+	str = xmlGetProp(node,(const xmlChar*)"magnitude");
+	if(str==NULL)
+		throw bad_format(node,"missing magnitude");
+	magnitude=atoi((const char*)str);
+	xmlFree(str);
+	str = xmlGetProp(node,(const xmlChar*)"custom_name");
+	if(str!=NULL) {
+		setName((const char*)str);
+		xmlFree(str);
+	} else
+		genName();
+}
+void EventBase::SaveXML(xmlNode * node) const {
+	xmlNodeSetName(node,(const xmlChar*)"event");
+	xmlSetProp(node,(const xmlChar*)"egid",(const xmlChar*)EventGeneratorNames[genID]);
+	char buf[20];
+	snprintf(buf,20,"%x",sourceID);
+	xmlSetProp(node,(const xmlChar*)"sid",(const xmlChar*)buf);
+	xmlSetProp(node,(const xmlChar*)"etid",(const xmlChar*)EventTypeAbbr[typeID]);
+	snprintf(buf,20,"%u",timestamp);
+	xmlSetProp(node,(const xmlChar*)"time",(const xmlChar*)buf);
+	snprintf(buf,20,"%u",duration);
+	xmlSetProp(node,(const xmlChar*)"duration",(const xmlChar*)buf);
+	snprintf(buf,20,"%g",magnitude);
+	xmlSetProp(node,(const xmlChar*)"magnitude",(const xmlChar*)buf);
+	if(!nameisgen) {
+		//extract custom name
+		size_t b=stim_id.find(',');
+		ASSERTRET(b!=std::string::npos,"malformed event name! (no comma)");
+		size_t e=stim_id.find(',',++b);
+		ASSERTRET(e!=std::string::npos,"malformed event name! (no 2nd comma)");
+		xmlSetProp(node,(const xmlChar*)"custom_name",(const xmlChar*)stim_id.substr(b,e-b).c_str());
+	}
+}
+
 void
 EventBase::genName() {
 	if(!nameisgen)
@@ -180,9 +270,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.24 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.25 $
  * $State: Exp $
- * $Date: 2004/12/22 23:54:07 $
+ * $Date: 2005/06/01 05:47:46 $
  */
 
diff -urdN ../Tekkotsu_2.3/Events/EventBase.h ./Events/EventBase.h
--- ../Tekkotsu_2.3/Events/EventBase.h	Wed Dec 22 18:12:59 2004
+++ ./Events/EventBase.h	Wed Jun 29 18:03:34 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_EventBase_h
 
 #include "Shared/get_time.h"
-#include "Shared/LoadSave.h"
+#include "Shared/XMLLoadSave.h"
 #include <string>
 
 //! The basis of events passed around the high level system
@@ -40,8 +40,11 @@
  *  where as others refer to time since last status (e.g. sensors
  *  updates)
  *
+ *  @note All subclasses must override getClassTypeID() and provide
+ *  a unique value to allow fast serialization for inter-process
+ *  communication.
  */
-class EventBase : public LoadSave {
+class EventBase : public XMLLoadSave {
  public:
 	//! Lists all possible event generator ids
 	/*! An event generator is a abstract source of events, used for listening to and parsing certain classes of events
@@ -63,7 +66,7 @@
 		sensorEGID,       //!< Sends a status event when new sensor readings are available. see SensorSourceID::SensorSourceID_t
 		stateMachineEGID, //!< Sends an event upon entering and leaving a StateNode; SID is pointer to the StateNode; duration is always 0; some state will throw a status event when they have completed their task and are now idling
 		stateTransitionEGID, //!< Sends an event each time a transition is triggered; SID is a pointer to the transition; type is always status, duration is always 0; guaranteed to occur immediately *before* the transition actually occurs
-    textmsgEGID,      //!< Sends status events when a text msg is received on console; generated by the Controller, SID is always -1; durations is always 0 (see Controller for more information)
+		textmsgEGID,      //!< Sends status events when a text msg is received on console; generated by the Controller, SID is always -1; durations is always 0 (see Controller for more information)
 		timerEGID,        //!< Sends timer events; you set timers explicitly, you don't have to listen as well. (See EventRouter::addTimer()) There's no cross-talk, only the listener which requested the timer will receive it; SID is whatever you requested it to be; duration is the time (since boot, in ms) that the timer was supposed to go off; these are always status
 		visOFbkEGID,      //!< Sends a DataEvent < OFbkImageVectorData > for every camera image received from the system; SID and duration are always 0 (This is generated by the MainObj instantiation of MMCombo)
 		visRawCameraEGID, //!< Sends a FilterBankEvent when new raw camera images are available; SID is whatever value you gave during setup (typically in StartupBehavior_SetupVision.cc), duration is always 0
@@ -88,14 +91,30 @@
 		deactivateETID, //!< Last of a series of events, e.g. button up
 		numETIDs        //!< the number of different event types
 	};
+	
+	//! holds string versions of EventTypeID_t
+	static const char* const EventTypeNames[numETIDs];
+	
+	//! holds abbreviated string versions of EventTypeID_t
+	static const char* const EventTypeAbbr[numETIDs];
 
 	/*! @name Constructors/Destructors */
 	//! constructor
 	/*! @see EventRouter::postEvent() */
 	EventBase(); 
 	EventBase(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur=0);
+	EventBase(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur, const std::string& n);
 	EventBase(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur, const std::string& n, float mag);
 	virtual ~EventBase() {} //!< destructor
+
+	//! allows a copy to be made of an event, supporting polymorphism
+	/*! Must be overridden by all subclasses to allow this to happen
+	 * 
+	 *  I would like to switch this over to the cloneable interface once
+	 *  the compiler gets updated out of the 3.3 branch... see
+	 *  Cloneable::clone() for a discussion of the issue and
+	 *  implementation notes. */
+	virtual EventBase* clone() const { return new EventBase(*this); }
 	//@}
 
 	/*! @name Methods */
@@ -145,18 +164,66 @@
 	bool shorterThan(const EventBase& eb) const { return duration<eb.duration && *this==eb; }//!< compares event duration and ensures same event generator, source, and type - useful for event masks
 	bool equalOrLongerThan(const EventBase& eb) const { return duration>=eb.duration && *this==eb; }//!< compares event duration and ensures same event generator, source, and type - useful for event masks
 	bool equalOrShorterThan(const EventBase& eb) const { return duration<=eb.duration && *this==eb; }//!< compares event duration and ensures same event generator, source, and type - useful for event masks
+	
+	static bool isValidGeneratorID(unsigned int egid) { return egid<numEGIDs; }
 	//@}
 
 	//! Useful for serializing events to send between processes
 	/*! @name LoadSave interface */
+
+	//! All subclasses should override this and return a unique ID for their class.
+	/*! All IDs corresponding to all-capital letters are reserved for future
+	 *  framework expansion.  (Thus, user subclasses should contain at least one
+	 *  lower-case letter.)  This code can be used when serializing to allow quick
+	 *  identification of the class type by the receiver. */
+	virtual unsigned int getClassTypeID() const { return makeClassTypeID("BASE"); }
+
 	virtual unsigned int getBinSize() const;
-	virtual unsigned int LoadBuffer(const char buf[], unsigned int len);
-	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
+	virtual unsigned int LoadBinaryBuffer(const char buf[], unsigned int len);
+	virtual unsigned int SaveBinaryBuffer(char buf[], unsigned int len) const;
+	virtual void LoadXML(xmlNode* node);
+	virtual void SaveXML(xmlNode * node) const;
+
+	virtual unsigned int LoadBuffer(const char buf[], unsigned int len)  {
+		unsigned int test = saveFormat!=BINARY ? XMLLoadSave::LoadBuffer(buf,len) : LoadBinaryBuffer(buf,len);
+		if(test!=0) //if the default didn't work, try the other format too...
+			return test;
+		return saveFormat!=BINARY ? LoadBinaryBuffer(buf,len) : XMLLoadSave::LoadBuffer(buf,len);
+	}
+	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const { return saveFormat!=BINARY ? XMLLoadSave::SaveBuffer(buf,len) : SaveBinaryBuffer(buf,len); }
+
+	virtual	unsigned int LoadFile(const char* filename) {
+		unsigned int test = saveFormat!=BINARY ? XMLLoadSave::LoadFile(filename) : LoadSave::LoadFile(filename);
+		if(test!=0) //if the default didn't work, try the other format too...
+			return test;
+		return saveFormat!=BINARY ? LoadSave::LoadFile(filename) : XMLLoadSave::LoadFile(filename);
+	}
+	virtual unsigned int SaveFile(const char* filename) const { return saveFormat!=BINARY ? XMLLoadSave::SaveFile(filename) : LoadSave::SaveFile(filename); }
+	
+	virtual unsigned int LoadFileStream(FILE* f) { return saveFormat!=BINARY ? XMLLoadSave::LoadFileStream(f) : LoadSave::LoadFileStream(f); }
+	virtual unsigned int SaveFileStream(FILE* f) const { return saveFormat!=BINARY ? XMLLoadSave::SaveFileStream(f) : LoadSave::SaveFileStream(f); }
+	
+	//! values to pass to setSaveFormat()
+	enum SaveFormat {
+		BINARY, //!< saves will be in packed binary, loads will try binary first
+		XML //!< saves will be in xml, loads will try xml first
+	};
+	virtual void setSaveFormat(SaveFormat sf) const { saveFormat=sf; } //!< set #saveFormat
+	virtual SaveFormat getSaveFormat() const { return saveFormat; } //!< return #saveFormat
 	//@}
+	
  protected:
-  std::string stim_id; //!< the name of the event, use the same name consistently or else will be seen as different stimuli
-  float magnitude; //!< the current "strength" of the event/stimuli... MAKE SURE this gets set to ZERO IF event is DEACTIVATE
-  unsigned int timestamp; //!< the time the event was created - set automatically by constructor
+	//! converts the first 4 characters of @a str to an unsigned int, should ensure consistent byte ordering across platforms
+	/*! The numeric value may differ between platforms, but it will be consistent
+	 *  with the IDs on that platform, which is the real key since we aren't doing
+	 *  math, just equality */
+	static unsigned int makeClassTypeID(const char* str) { return *reinterpret_cast<const unsigned int*>(str); }
+
+	std::string stim_id; //!< the name of the event, use the same name consistently or else will be seen as different stimuli
+	float magnitude; //!< the current "strength" of the event/stimuli... MAKE SURE this gets set to ZERO IF event is DEACTIVATE
+	unsigned int timestamp; //!< the time the event was created - set automatically by constructor
+
+	mutable SaveFormat saveFormat; //!< controls the format used during the next call to SaveBuffer() (packed binary or XML)
 
 	bool nameisgen; //!< tracks whether the current name (stim_id) was generated by genName() (true) or setName() (false)
 	virtual void genName(); //!< calls setName() with a string version of sourceID, decimal notation
@@ -178,10 +245,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.31 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.34 $
  * $State: Exp $
- * $Date: 2004/12/22 23:12:59 $
+ * $Date: 2005/06/29 22:03:34 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/EventGeneratorBase.cc ./Events/EventGeneratorBase.cc
--- ../Tekkotsu_2.3/Events/EventGeneratorBase.cc	Tue Nov  9 15:01:49 2004
+++ ./Events/EventGeneratorBase.cc	Wed Jun  1 01:47:46 2005
@@ -6,12 +6,10 @@
 void
 EventGeneratorBase::DoStart() {
 	BehaviorBase::DoStart();
-	if(autoListen) {
+	if(autoListen && getGeneratorID()!=EventBase::numEGIDs) {
 		erouter->addListener(this,EventBase::erouterEGID,getGeneratorID());
-		if(erouter->hasListeners(getGeneratorID(),getSourceID())) {
-			erouter->addListener(this,getListenGeneratorID(),getListenSourceID());
-			isListening=true;
-		}
+		if(hasListeners())
+			addSrcListener();
 	}
 }
 
@@ -24,58 +22,127 @@
 
 void
 EventGeneratorBase::processEvent(const EventBase& event) {
-	if(!autoListen)
+	if(!autoListen || getGeneratorID()==EventBase::numEGIDs)
 		return;
 	if(event.getGeneratorID()==EventBase::erouterEGID) {
-		if(erouter->hasListeners(getGeneratorID(),getSourceID())) {
-			if(!isListening) {
-				erouter->addListener(this,getListenGeneratorID(),getListenSourceID());
-				isListening=true;
-			}
+		if(hasListeners()) {
+			addSrcListener();
 		} else {
-			if(isListening) {
-				erouter->removeListener(this,getListenGeneratorID(),getListenSourceID());
-				isListening=false;
-			}
+			removeSrcListener();
 		}
 	}
 }
 
 void
+EventGeneratorBase::setAutoListen(EventBase::EventGeneratorID_t gid) {
+	removeSrcListener();
+	autoListen=true;
+	srcGenID=gid;
+	specificity=GENERATOR;
+	if(gid==EventBase::numEGIDs) {
+		autoListen=false;
+		return;
+	}
+	if(isActive())
+		erouter->addListener(this,EventBase::erouterEGID,getGeneratorID());
+	if(hasListeners())
+		addSrcListener();
+}
+
+void
 EventGeneratorBase::setAutoListen(EventBase::EventGeneratorID_t gid, unsigned int sid) {
-	if(isListening) {
-		erouter->removeListener(this,getListenGeneratorID(),getListenSourceID());
-		isListening=false;
+	removeSrcListener();
+	autoListen=true;
+	srcGenID=gid;
+	srcSourceID=sid;
+	specificity=SOURCE;
+	if(gid==EventBase::numEGIDs) {
+		autoListen=false;
+		return;
 	}
+	if(isActive())
+		erouter->addListener(this,EventBase::erouterEGID,getGeneratorID());
+	if(hasListeners())
+		addSrcListener();
+}
+
+void
+EventGeneratorBase::setAutoListen(EventBase::EventGeneratorID_t gid, unsigned int sid, EventBase::EventTypeID_t tid) {
+	removeSrcListener();
 	autoListen=true;
 	srcGenID=gid;
 	srcSourceID=sid;
-		if(erouter->hasListeners(getGeneratorID(),getSourceID())) {
-		if(!isListening) {
-			erouter->addListener(this,getListenGeneratorID(),getListenSourceID());
-			isListening=true;
-		}
+	srcTypeID=tid;
+	specificity=TYPE;
+	if(gid==EventBase::numEGIDs || tid==EventBase::numETIDs) {
+		autoListen=false;
+		return;
 	}
+	if(isActive())
+		erouter->addListener(this,EventBase::erouterEGID,getGeneratorID());
+	if(hasListeners())
+		addSrcListener();
 }
 
 void
 EventGeneratorBase::unsetAutoListen() {
-	if(isListening) {
+	removeSrcListener();
+	autoListen=false;
+}
+
+bool
+EventGeneratorBase::hasListeners() const {
+	return erouter->hasListeners(getGeneratorID(),getSourceID());
+}
+
+void
+EventGeneratorBase::addSrcListener() {
+	if(isListening || getListenGeneratorID()==EventBase::numEGIDs)
+		return;
+	switch(specificity) {
+	case GENERATOR:
+		erouter->addListener(this,getListenGeneratorID());
+		break;
+	case SOURCE:
+		erouter->addListener(this,getListenGeneratorID(),getListenSourceID());
+		break;
+	case TYPE:
+		if(getListenTypeID()==EventBase::numETIDs)
+			return;
+		erouter->addListener(this,getListenGeneratorID(),getListenSourceID(),getListenTypeID());
+		break;
+	}
+	isListening=true;
+}
+
+void
+EventGeneratorBase::removeSrcListener() {
+	if(!isListening)
+		return;
+	switch(specificity) {
+	case GENERATOR:
+		erouter->removeListener(this,getListenGeneratorID());
+		break;
+	case SOURCE:
 		erouter->removeListener(this,getListenGeneratorID(),getListenSourceID());
-		isListening=false;
+		break;
+	case TYPE:
+		erouter->removeListener(this,getListenGeneratorID(),getListenSourceID(),getListenTypeID());
+		break;
 	}
-	autoListen=false;
+	isListening=false;
 }
 
 
+
 /*! @file
  * @brief 
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/06/01 05:47:46 $
  */
 
diff -urdN ../Tekkotsu_2.3/Events/EventGeneratorBase.h ./Events/EventGeneratorBase.h
--- ../Tekkotsu_2.3/Events/EventGeneratorBase.h	Mon Dec 20 16:47:59 2004
+++ ./Events/EventGeneratorBase.h	Sun Aug  7 00:11:03 2005
@@ -37,49 +37,86 @@
 	 *  to call EventGeneratorBase::processEvent() in order to allow them to be used */
 	virtual void processEvent(const EventBase& event);
 	
+
+	//! These concern the events which will be thrown to listeners
+	//!@name Downstream Settings
+
 	//! return the generator ID that will be broadcast from
-	virtual EventBase::EventGeneratorID_t getGeneratorID() { return myGenID; }
+	virtual EventBase::EventGeneratorID_t getGeneratorID() const { return myGenID; }
 	//! set the generator ID that will be broadcast from (typically it's a bad idea to call this...)
 	virtual void setGeneratorID(EventBase::EventGeneratorID_t gid) { myGenID=gid; }
 
 	//! return the source ID that will be broadcast on
-	virtual unsigned int getSourceID() { return mySourceID; }
+	virtual unsigned int getSourceID() const { return mySourceID; }
 	//! set the source ID that will be broadcast on
 	virtual void setSourceID(unsigned int sid) { mySourceID=sid; }
 
-	//! returns the source ID that will be listened for (not the source of the FilterBankEvent to be created - that depends on the subclass)
-	virtual unsigned int getListenSourceID() const { return srcSourceID; }
-	//! returns the generator ID that will be listened for (not the generator of the FilterBankEvent to be created - that depends on the subclass)
-	virtual EventBase::EventGeneratorID_t getListenGeneratorID() const { return srcGenID; }
+	//! return true if this generator has listeners
+	virtual bool hasListeners() const;
+	//@}
+
+
+	//! These help select which events will be received from other generators
+	//!@name Upstream Settings
+
+	//! lets you specify what level of filtering should be done
+	enum specificity_t {
+		GENERATOR, //!< only the generator needs to match, select all sources and types
+		SOURCE,    //!< both generator and source need to match, select all types
+		TYPE       //!< explicit event tuple; generator, source, and type must all match
+	};
+	//! returns the current specificity level, to modify this, call the appropriate version of setAutoListen()
+	virtual specificity_t getSpecificity() const { return specificity; }
+
+	//! turns on auto listening to make it easier to set up dependancies between vision filters
+	virtual void setAutoListen(EventBase::EventGeneratorID_t gid);
 	//! turns on auto listening to make it easier to set up dependancies between vision filters
 	virtual void setAutoListen(EventBase::EventGeneratorID_t gid, unsigned int sid);
-
+	//! turns on auto listening to make it easier to set up dependancies between vision filters
+	virtual void setAutoListen(EventBase::EventGeneratorID_t gid, unsigned int sid, EventBase::EventTypeID_t tid);
 	//! turns off auto listening
 	virtual void unsetAutoListen();
 
+	//! returns the generator ID that will be listened for (not the generator of the FilterBankEvent to be created - that depends on the subclass)
+	virtual EventBase::EventGeneratorID_t getListenGeneratorID() const { return srcGenID; }
+	//! returns the source ID that will be listened for (not the source of the FilterBankEvent to be created - that depends on the subclass)
+	virtual unsigned int getListenSourceID() const { return srcSourceID; }
+	//! returns the type ID that will be listened for (not the type of the FilterBankEvent to be created - that depends on the subclass)
+	virtual EventBase::EventTypeID_t getListenTypeID() const { return srcTypeID; }
+
+	//@}
+
 protected:
 	//!@name Constructors
 	//!
-	EventGeneratorBase(const std::string& name, EventBase::EventGeneratorID_t mgid, unsigned int msid)
-		: BehaviorBase(name), myGenID(mgid), mySourceID(msid), autoListen(false), isListening(false), srcGenID(EventBase::unknownEGID), srcSourceID(0)
-	{}
-	EventGeneratorBase(const std::string& name, EventBase::EventGeneratorID_t mgid, unsigned int msid,EventBase::EventGeneratorID_t srcgid, unsigned int srcsid)
-		: BehaviorBase(name), myGenID(mgid), mySourceID(msid), autoListen(true), isListening(false), srcGenID(srcgid), srcSourceID(srcsid)
-	{}
 	EventGeneratorBase(const std::string& classname, const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid)
-		: BehaviorBase(classname,instancename), myGenID(mgid), mySourceID(msid), autoListen(false), isListening(false), srcGenID(EventBase::unknownEGID), srcSourceID(0)
+		: BehaviorBase(classname,instancename), myGenID(mgid), mySourceID(msid), autoListen(false), isListening(false), srcGenID(EventBase::numEGIDs), srcSourceID(), srcTypeID(), specificity()
+	{}
+	EventGeneratorBase(const std::string& classname, const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid,EventBase::EventGeneratorID_t srcgid)
+		: BehaviorBase(classname,instancename), myGenID(mgid), mySourceID(msid), autoListen(srcgid!=EventBase::numEGIDs), isListening(false), srcGenID(srcgid), srcSourceID(), srcTypeID(), specificity(GENERATOR)
 	{}
 	EventGeneratorBase(const std::string& classname, const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid,EventBase::EventGeneratorID_t srcgid, unsigned int srcsid)
-		: BehaviorBase(classname,instancename), myGenID(mgid), mySourceID(msid), autoListen(true), isListening(false), srcGenID(srcgid), srcSourceID(srcsid)
+		: BehaviorBase(classname,instancename), myGenID(mgid), mySourceID(msid), autoListen(srcgid!=EventBase::numEGIDs), isListening(false), srcGenID(srcgid), srcSourceID(srcsid), srcTypeID(), specificity(SOURCE)
+	{}
+	EventGeneratorBase(const std::string& classname, const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid,EventBase::EventGeneratorID_t srcgid, unsigned int srcsid, EventBase::EventTypeID_t srctype)
+		: BehaviorBase(classname,instancename), myGenID(mgid), mySourceID(msid), autoListen(srcgid!=EventBase::numEGIDs), isListening(false), srcGenID(srcgid), srcSourceID(srcsid), srcTypeID(srctype), specificity(TYPE)
 	{}
 	//@}
 
+	//! subscribe this generator to its source
+	virtual void addSrcListener();
+
+	//! unsubscribe this generator from its source
+	virtual void removeSrcListener();
+
 	EventBase::EventGeneratorID_t myGenID; //!< the generator ID to broadcast on
 	unsigned int mySourceID;     //!< the source ID to broadcast on
 	bool autoListen;          //!< if true, will automatically start listening for EventBase(genID,sourceID) events
 	bool isListening;         //!< true if listening triggered by autoListen
 	EventBase::EventGeneratorID_t srcGenID; //!< the generator ID to listen for (typically the source that this filter works on)
 	unsigned int srcSourceID;    //!< the source ID to listen for
+	EventBase::EventTypeID_t srcTypeID; //!< the type ID to listen for
+	specificity_t specificity; //!< the level of event specificity that is being listened for, so when #autoListen is triggered, we can subscribe to the right level of event stream
 };
 
 /*! @file
@@ -87,10 +124,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.8 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/12/20 21:47:59 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/EventListener.h ./Events/EventListener.h
--- ../Tekkotsu_2.3/Events/EventListener.h	Thu Sep 25 11:27:10 2003
+++ ./Events/EventListener.h	Thu Sep 25 11:27:10 2003
@@ -20,7 +20,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Rel $
  * $Date: 2003/09/25 15:27:10 $
diff -urdN ../Tekkotsu_2.3/Events/EventRouter.cc ./Events/EventRouter.cc
--- ../Tekkotsu_2.3/Events/EventRouter.cc	Fri Jan 28 19:01:57 2005
+++ ./Events/EventRouter.cc	Thu Jul  7 18:34:15 2005
@@ -145,13 +145,24 @@
 }
 
 void EventRouter::removeListener(EventListener* el) {
-	for(unsigned int eg=0; eg<EventBase::numEGIDs; eg++)
-		removeListener(el,(EventBase::EventGeneratorID_t)eg);
+	for(unsigned int eg=0; eg<EventBase::numEGIDs; eg++) {
+		EventBase::EventGeneratorID_t egid=(EventBase::EventGeneratorID_t)eg;
+		if(!listeners.removeMapping(el,egid))
+			continue; //nothing was removed, don't want to clean up or throw an event
+		listeners.clean(egid);
+		if(!hasListeners(egid))
+			postEvent(new EventBase(EventBase::erouterEGID,egid,EventBase::deactivateETID,0,EventBase::EventGeneratorNames[egid],0));
+		else
+			postEvent(new EventBase(EventBase::erouterEGID,egid,EventBase::statusETID,0,EventBase::EventGeneratorNames[egid],1));
+	}
+	removeTimer(el); //this should go away when we implement bug 89
 }
 void EventRouter::removeListener(EventListener* el, EventBase::EventGeneratorID_t egid) {
-	if(egid==EventBase::timerEGID)
+	if(egid==EventBase::timerEGID) {
+		printf("WARNING: The use of removeListener with timerEGID is deprecated,\n"
+		       "         please see http://bugs.tekkotsu.org/show_bug.cgi?id=89\n");
 		removeTimer(el);
-	else {
+	} else {
 		if(!listeners.removeMapping(el,egid))
 			return; //nothing was removed, don't want to clean up or throw an event
 		listeners.clean(egid);
@@ -162,9 +173,11 @@
 	}
 }
 void EventRouter::removeListener(EventListener* el, EventBase::EventGeneratorID_t egid, unsigned int sid) {
-	if(egid==EventBase::timerEGID)
+	if(egid==EventBase::timerEGID) {
+		printf("WARNING: The use of removeListener with timerEGID is deprecated,\n"
+		       "         please see http://bugs.tekkotsu.org/show_bug.cgi?id=89\n");
 		removeTimer(el,sid);
-	else {
+	} else {
 		unsigned int removed=0;
 		for(unsigned int et=0; et<EventBase::numETIDs; et++)
 			removed+=listeners.removeMapping(el,egid,sid,(EventBase::EventTypeID_t)et);
@@ -179,6 +192,8 @@
 }
 void EventRouter::removeListener(EventListener* el, EventBase::EventGeneratorID_t egid, unsigned int sid, EventBase::EventTypeID_t etid) {
 	if(egid==EventBase::timerEGID) {
+		printf("WARNING: The use of removeListener with timerEGID is deprecated,\n"
+		       "         please see http://bugs.tekkotsu.org/show_bug.cgi?id=89\n");
 		if(etid==EventBase::statusETID)
 			removeTimer(el,sid);
 	} else {
@@ -192,9 +207,11 @@
 	}
 }
 void EventRouter::removeListener(EventListener* el, const EventBase& e) {
-	if(e.getGeneratorID()==EventBase::timerEGID)
+	if(e.getGeneratorID()==EventBase::timerEGID) {
+		printf("WARNING: The use of removeListener with timerEGID is deprecated,\n"
+		       "         please see http://bugs.tekkotsu.org/show_bug.cgi?id=89\n");
 		removeTimer(el,e.getSourceID());
-	else {
+	} else {
 		if(!listeners.removeMapping(el,e.getGeneratorID(),e.getSourceID(),e.getTypeID()))
 			return; //nothing was removed, don't want to clean up or throw an event
 		listeners.clean(e.getGeneratorID());
@@ -205,10 +222,6 @@
 	}
 }
 
-void EventRouter::forgetListener(EventListener* el) {
-	removeListener(el);
-}
-
 void EventRouter::addTrapper(EventTrapper* el, const EventBase& e) {
 	bool hadListener=hasListeners(e.getGeneratorID());
 	trappers.addMapping(el,e.getGeneratorID(),e.getSourceID(),e.getTypeID());
@@ -632,10 +645,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.16 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.18 $
  * $State: Exp $
- * $Date: 2005/01/29 00:01:57 $
+ * $Date: 2005/07/07 22:34:15 $
  */
 
 
diff -urdN ../Tekkotsu_2.3/Events/EventRouter.h ./Events/EventRouter.h
--- ../Tekkotsu_2.3/Events/EventRouter.h	Thu Jan 27 15:15:32 2005
+++ ./Events/EventRouter.h	Sun Aug  7 00:11:03 2005
@@ -142,9 +142,6 @@
 	//! stops sending specified events from the generator to the listener.  If a timer is passed it will invoke removeTimer(@a el, @a e.getSourceID())
 	void removeListener(EventListener* el, const EventBase& e);
 
-	/*! @deprecated use removeListener(EventListener* el) instead
-	 *  @brief deprecated, you should call removeListener(EventListener* el) instead */
-	void forgetListener(EventListener* el) __attribute__((deprecated));
 	//@}
 
 	//!@name Trapper Management
@@ -185,7 +182,7 @@
 		//! just does the default, i'm just being explicit since there's a pointer (no deep copy!)
 		TimerEntry(const TimerEntry& t) : el(t.el), sid(t.sid), delay(t.delay), next(t.next), repeat(t.repeat) {}
 		//! just does the default, i'm just being explicit since there's a pointer (no deep copy!)
-		TimerEntry operator=(const TimerEntry& t) { el=t.el; sid=t.sid; delay=t.delay; next=t.next; repeat=t.repeat; return *this; }
+		TimerEntry& operator=(const TimerEntry& t) { el=t.el; sid=t.sid; delay=t.delay; next=t.next; repeat=t.repeat; return *this; }
 		//! will reset timer
 		/*! @param d the time from now when the timer should go off (in milliseconds)
 		 *  @param r true if the timer should automatically repeat */
@@ -235,9 +232,9 @@
 	bool doSendBufferLock;              //!< in case of recursive calls to processEventBuffer()/doSendBuffer()
 	unsigned int lastBufClear;          //!< time of last event buffer clear
 	unsigned int buffertime;            //!< The time between clearings of the buffer
-																			/*!< <li>0 will not use the buffer, events are routed upon posting
-																			 *   <li>1 will clear the buffer at next call to processTimers() or processEventBuffer()
-																			 *   <li>a larger value will cause a delay of that number of milliseconds since the last clearing */
+																			/*!< - 0 will not use the buffer, events are routed upon posting
+																			 *   - 1 will clear the buffer at next call to processTimers() or processEventBuffer()
+																			 *   - a larger value will cause a delay of that number of milliseconds since the last clearing */
 	
 	//! Does the actual storage of the mapping between EventBase's and the EventListeners/EventTrappers who should receive them
 	/*! Actually only stores void*'s, so it's more general than just Listeners or Trappers */
@@ -296,7 +293,7 @@
 		/*! Only checks #allevents */
 		bool verifyMappingAll(void * listener, EventBase::EventGeneratorID_t egid);
 		//! Needed to complete EventRouter::isListening suite
-		/*! Checks both #allevents and #filtered events */
+		/*! Checks both #allevents and #filteredevents */
 		bool verifyMappingAny(void * listener, EventBase::EventGeneratorID_t egid);
 
 		//! Needed to complete EventRouter::isListening suite
@@ -334,10 +331,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.18 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.21 $
  * $State: Exp $
- * $Date: 2005/01/27 20:15:32 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/EventTranslator.cc ./Events/EventTranslator.cc
--- ../Tekkotsu_2.3/Events/EventTranslator.cc	Fri Jan 28 19:02:55 2005
+++ ./Events/EventTranslator.cc	Mon Jul 25 23:11:23 2005
@@ -6,99 +6,105 @@
 #include "Shared/debuget.h"
 #include <iostream>
 
-bool
-EventTranslator::trapEvent(const EventBase& event) {
-	enqueue(event,queue);
-	return true;
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OSubject.h>
+#else
+#  include "IPC/MessageQueue.h"
+#endif
+#include "IPC/RCRegion.h"
+
+using namespace std;
+
+EventTranslator::eventLookup_t EventTranslator::eventLookup;
+
+EventTranslator::~EventTranslator() {
+	for(eventLookup_t::iterator it=eventLookup.begin(); it!=eventLookup.end(); ++it)
+		delete (*it).second;
+	eventLookup.clear();
 }
 
 void
-EventTranslator::enqueue(const EventBase& event, Queue_t * q) {
-	unsigned int len=event.getBinSize();
-	TypeID_t type;
-	if(dynamic_cast<const LocomotionEvent*>(&event)!=NULL) {
-		type=LocomotionEvent_ID;
-	} else if(dynamic_cast<const VisionObjectEvent*>(&event)!=NULL) {
-		type=VisionObjectEvent_ID;
-	} else if(dynamic_cast<const TextMsgEvent*>(&event)!=NULL) {
-		type=TextMsgEvent_ID;
-	} else {
-		ASSERT(dynamic_cast<const EventBase*>(&event)!=NULL,"stupid OS/compiler/linker/whatever");
-		type=EventBase_ID;
-	}
-	void* buf=q->reserve(sizeof(TypeID_t)+len);
+EventTranslator::encodeEvent(const EventBase& event) {
+	event.setSaveFormat(EventBase::BINARY);
+	const unsigned int headerlen=sizeof(event.getClassTypeID());
+	const unsigned int bufsize=headerlen+event.getBinSize();
+	char * buf=bufferRequest(bufsize);
 	if(buf==NULL) {
-		ASSERT(false,"Queue overflow "<<type<<' '<<len);
-	} else {
-		*reinterpret_cast<TypeID_t*>(buf)=type;
-		reinterpret_cast<char*>(buf)+=sizeof(TypeID_t);
-		unsigned int err=event.SaveBuffer(reinterpret_cast<char*>(buf),len);
-		ASSERT(err!=0,"bad save");
+		cerr << "ERROR: EventTranslator unable to transmit event because requested buffer was NULL" << endl;
+		return;
 	}
-	q->done();
+	unsigned int header=event.getClassTypeID();
+	memcpy(buf,&header,headerlen);
+	unsigned int used=event.SaveBuffer(buf+headerlen,bufsize-headerlen);
+	if(used==0) {
+		cerr << "ERROR: EventTranslator unable to transmit event because EventBase::SaveBuffer failed (buffer==" << (void*)(buf+headerlen) << ", size==" << bufsize-headerlen << ")" << endl;
+		post(buf,0);
+		return;
+	}
+	post(buf,used);
+	return;
 }
-	
+
+EventBase*
+EventTranslator::decodeEvent(const char * entry, unsigned int size) {
+	const unsigned int headerlen=sizeof(unsigned int);
+	unsigned int header=0;
+	memcpy(&header,entry,headerlen);
+	eventLookup_t::iterator it=eventLookup.find(header);
+	if(it==eventLookup.end()) {
+		cerr << "ERROR: EventTranslator unable to translate buffer because header does not match a previously registered class type id" << endl;
+		return NULL;
+	}
+	EventBase* evt=static_cast<EventBase*>((*it).second->constructTemplate());
+	evt->setSaveFormat(EventBase::BINARY);
+	if(evt->LoadBuffer(entry+headerlen,size-headerlen)==0) {
+		cerr << "ERROR: EventTranlator unable to translate buffer because data is malformed (EventBase::LoadBuffer failed)" << endl;
+		return NULL;
+	}
+	return evt;
+}
+
 void
-EventTranslator::translateEvents() {
-	unsigned int i;
-	for(i=0; i<queue->size(); i++)
-		sendEvent(queue->data(i),queue->size(i));
-	while(!queue->clear(i)) //needed so if another was added while we were processing last one we will get it
-		sendEvent(queue->data(i++),queue->size(i));
+NoOpEventTranslator::encodeEvent(const EventBase& event) {
+	evtRouter.postEvent(event.clone());
+}
+
+char*
+IPCEventTranslator::bufferRequest(unsigned int size) {
+	ASSERT(curRegion==NULL,"WARNING: IPCEventTranslator::bufferRequest() curRegion was not NULL");
+	curRegion = new RCRegion(size);
+	return curRegion->Base();
 }
 
+//#include "Shared/TimeET.h"
+
 void
-EventTranslator::sendEvent(const void * entry, unsigned int size) {
-	TypeID_t type=*reinterpret_cast<const TypeID_t*>(entry);
-	const char* buf=reinterpret_cast<const char*>(entry)+sizeof(TypeID_t);
-	size-=sizeof(TypeID_t);
-	EventBase * evt=NULL;
-	switch(type) {
-	case LocomotionEvent_ID: {
-		evt=new LocomotionEvent;
-	} break;
-	case VisionObjectEvent_ID: {
-		evt=new VisionObjectEvent;
-	} break;
-	case TextMsgEvent_ID: {
-		evt=new TextMsgEvent;
-	} break;
-	case EventBase_ID: {
-		evt=new EventBase;
-	} break;
-	//no default case because we want
-	//a compiler warning if we miss one
-	}
-	ASSERTRET(evt!=NULL,"Unrecognized entry type");
-	unsigned int err=evt->LoadBuffer(buf,size);
-	if(err==0) {
-		std::cout<<"ERROR: type="<<type<< " len="<<size<<std::endl;
-		for(unsigned int i=0; i<size; i++) {
-			printf("%hx",buf[i]);
-			if(i%10==0)
-				printf("\n");
-			else if(i%4==0)
-				printf(" ");
-		}
-		std::cout << "This is a rare bug we are trying to track down.\n"
-			"Please email a brief message containing the above\n"
-			"hex dump to info@tekkotsu.org.  Thank you!" << std::endl;
+IPCEventTranslator::post(const char* buf, unsigned int /*size*/) {
+	ASSERTRET(curRegion!=NULL,"ERROR: IPCEventTranslator::post(buf,size) was NULL");
+	if(buf!=curRegion->Base()) {
+		cerr << "ERROR: IPCEventTranslator::post(buf,size) buf does not match value given from previous bufferRequest()" << endl;
+		return;
 	}
-	ASSERTRET(err!=0,"bad load");
-	ASSERTRET(evt->getGeneratorID()<EventBase::numEGIDs && evt->getTypeID()<EventBase::numETIDs,
-						"invalid EGID "<<evt->getGeneratorID()<<" or ETID "<<evt->getTypeID());
-	erouter->postEvent(evt);
+	//cout << TimeET() << endl;
+#ifdef PLATFORM_APERIOS
+	subject.SetData(curRegion);
+	subject.NotifyObservers();
+#else
+	subject.sendMessage(curRegion);
+	curRegion->RemoveReference();
+#endif
+	curRegion=NULL;
 }
-
+	
 
 /*! @file
  * @brief Implements EventTranslator, which receives events from EventRouters in non-Main processes and adds them into a SharedQueue for Main to pick up
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.8 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2005/01/29 00:02:55 $
+ * $Date: 2005/07/26 03:11:23 $
  */
 
diff -urdN ../Tekkotsu_2.3/Events/EventTranslator.h ./Events/EventTranslator.h
--- ../Tekkotsu_2.3/Events/EventTranslator.h	Thu Sep 16 14:35:12 2004
+++ ./Events/EventTranslator.h	Sun Aug  7 00:11:03 2005
@@ -2,70 +2,159 @@
 #ifndef INCLUDED_EventTranslator_h_
 #define INCLUDED_EventTranslator_h_
 
-#include "Shared/SharedQueue.h"
 #include "Events/EventTrapper.h"
+#include "Events/EventListener.h"
+#include "Shared/Factory.h"
+#include <map>
 
 //! EventTranslator receives events from EventRouters in non-Main processes and adds them into a SharedQueue for Main to pick up
-/*! The SharedQueue which the processes should set up and then pass to this object
- *  is defined by TranslatorSharedQueue_t - it allows 100 entries totalling 3KB of space.
- *  You can modify the type to change the capacity, but if you're making that many events that
- *  between Main's calls to translateEvents() you might want to rethink a few things...
- * 
- *  EventTranslator only handles LocomotionEvent, VisionObjectEvent, and TextMsgEvent subtypes for
- *  the moment.  Anything else is only handled as an EventBase class. (so extra fields aren't
- *  going to be stored) It's easy to add more types if you need to send them from other
- *  processes (that's the whole point of this class!)
- *
- *  Reason for doing it this way: Avoids OPENR message lag time (4-8ms in our testing), also
- *  avoids problems with RTTI stored in classes from different processes. */
-class EventTranslator : public EventTrapper {
+class EventTranslator : public EventTrapper, public EventListener {
 public:
 	//!constructor
-	EventTranslator() : queue(NULL) {}
+	EventTranslator() : trapRet(false) {}
 
-	//!Use this type to set up the shared queue between processes
-	typedef SharedQueue<3*1024,100> Queue_t;
+	//!destructor
+	virtual ~EventTranslator();
+
+	//! Call this with events which should be forwarded to other processes
+	virtual void encodeEvent(const EventBase& event);
+
+	//! Call this with events which should be forwarded to other processes (redirects to encodeEvent())
+	/*! By providing an EventTrapper interface, you can directly
+	 *  register this class with an EventRouter instead of having to
+	 *  manually forward events (although you could do that as well)
+	 *  @return #trapRet, which you can set via setTrapEventValue() */
+	virtual bool trapEvent(const EventBase& event) { encodeEvent(event); return trapRet; }
+
+	//! Call this with events which should be forwarded to other processes (redirects to encodeEvent())
+	/*! By providing an EventListener interface, you can directly
+	 *  register this class with an EventRouter instead of having to
+	 *  manually forward events (although you could do that as well) */
+	virtual void processEvent(const EventBase& event) { encodeEvent(event); }
+
+	//! Called with buffers containing incoming events which should be reconstituted
+	/*! @return the reconstituted event, or NULL if an error occured (malformed data) */
+	static EventBase* decodeEvent(const char* buf, unsigned int size);
+
+	//!This should be called during initialization to register all EventBase subclasses
+	/*! @return true upon success, false if an event matching that prototype's EventBase::getClassTypeID() was already registered */
+	template<class EB>
+	static bool registerPrototype() {
+		EB prototype;
+		eventLookup_t::const_iterator it=eventLookup.find(prototype.getClassTypeID());
+		if(it!=eventLookup.end())
+			return false;
+		eventLookup[prototype.getClassTypeID()]=new Factory<EB>;
+		return true;
+	}
+
+	//! set #trapRet, which can let you decide whether trapped events should be filtered or not
+	virtual void setTrapEventValue(bool v) { trapRet=v; }
 	
-	//!an ID is inserted before the event data in the queue so we can tell which subclass it is
-	/*!(quickly, could look at the creator code which is stored, but that's a text string)*/
-	enum TypeID_t { EventBase_ID, LocomotionEvent_ID, VisionObjectEvent_ID, TextMsgEvent_ID };
 
-	//!sets the SharedQueue which should be used
-	void setQueue(Queue_t * q) { queue=q; }
+protected:
+	//! Shorthand for they type of #eventLookup
+	typedef std::map<unsigned int,FactoryBase*> eventLookup_t;
+	
+	//! Allows quick lookup of event subclasses based on their EventBase::getClassTypeID()
+	static eventLookup_t eventLookup;
 
-	//!called by the event router when something in this process sends an event
-	virtual bool trapEvent(const EventBase& event);
+	//! Called by encodeEvent() to request a buffer for serializing into, must be at least @a size
+	/*! This buffer will then be sent to post(), which should free
+	 *  it (or recycle it for usage by a later bufferRequest()) */
+	virtual char* bufferRequest(unsigned int size)=0;
+
+	//! Called by encodeEvent() after serialization is complete for communication to other processes
+	/*! @param buf the data to be sent, will be a buffer previously requested from #bufferRequest
+	 *  @param size the number of bytes to send
+	 *
+	 *  You will always get this callback after each call to bufferRequest(), even
+	 *  in the event of an error during saving.  If an error occured, the callback
+	 *  will receive 0 for size.*/
+	virtual void post(const char* buf, unsigned int size)=0;
+
+	//! The value which trapEvent() should return
+	bool trapRet;
+
+private:
+	EventTranslator(const EventTranslator&); //!< don't call
+	EventTranslator& operator=(const EventTranslator&); //!< don't call
+};
+
+class EventRouter;
+
+//! For completeness, if you want to have events be piped directly to the local erouter instead having to be encoded and decoded
+/*! Unfortunately, this still entails a memory copy of the event since
+ *  we have to make a new event for posting to the event router.  We
+ *  could avoid this if events were reference counted or if there was
+ *  a way to direct the EventRouter not to free the event after
+ *  processing.
+ *
+ *  Beware of subscribing this class as a listener to the same
+ *  EventRouter that it is sending to -- could cause infinite
+ *  recursion */
+class NoOpEventTranslator : public EventTranslator {
+public:
+	//! constructor
+	explicit NoOpEventTranslator(EventRouter& er) : EventTranslator(), evtRouter(er) {}
+
+	virtual void encodeEvent(const EventBase& event);
+
+protected:
+	//! should never be called, only included to satisfy interface
+	virtual char* bufferRequest(unsigned int /*size*/) { return NULL; }
+	//! should never be called, only included to satisfy interface
+	virtual void post(const char* /*buf*/, unsigned int /*size*/) { }
 	
-	//!called by trapEvent to do all the work, needed so MotionCommands can enqueue directly
-	static void enqueue(const EventBase& event, Queue_t * q);
+	EventRouter& evtRouter; //!< the EventRouter to send events to
+};
 
-	//!called by non-MotionCommands to enqueue an event
-	void enqueue(const EventBase& event) { enqueue(event,queue); }
 
-	//!called whenever Main gets some processor time to check for events from other processes
-	void translateEvents();
+#ifdef PLATFORM_APERIOS
+class OSubject;
+#else
+class MessageQueueBase;
+#endif
+class RCRegion;
+
+//! An implementation of EventTranslator which will forward events using the inter-process mechanisms of the current platform
+/*! The current implementation creates an RCRegion for each event and
+ *  then releases its reference to the region after it is sent.  A
+ *  more efficient implementation might retain a queue of recycled
+ *  RCRegions to reduce allocation costs */
+class IPCEventTranslator : public EventTranslator {
+public:
+
+#ifdef PLATFORM_APERIOS
+	typedef OSubject IPCSender_t; //!< the class for sending IPC messages on aperios
+#else
+	typedef MessageQueueBase IPCSender_t; //!< the class for sending IPC messages on unix-based systems
+#endif
+
+	//! constructor
+	explicit IPCEventTranslator(IPCSender_t& subj) : EventTranslator(), subject(subj), curRegion(NULL) {}
 
 protected:
-	//!called by translateEvents for each event to be sent
-	static void sendEvent(const void* buf, unsigned int size);
+	virtual char* bufferRequest(unsigned int size);
+	virtual void post(const char* buf, unsigned int size);
 	
-	//!pointer to queue of events to be sent
-	Queue_t * queue;
+	IPCSender_t& subject; //!< where to post messages upon serialization, set by constructor
+	RCRegion* curRegion; //!< the region currently being serialized into, only valid between call to bufferRequest() and following post()
 
 private:
-	EventTranslator(const EventTranslator&); //!< don't call
-	EventTranslator operator=(const EventTranslator&); //!< don't call
+	IPCEventTranslator(const IPCEventTranslator&); //!< don't call
+	IPCEventTranslator operator=(const IPCEventTranslator&); //!< don't call
 };
 
 /*! @file
- * @brief Describes EventTranslator, which receives events from EventRouters in non-Main processes and adds them into a SharedQueue for Main to pick up
+ * @brief Describes EventTranslator and IPCEventTranslator, which receives events from EventRouters in non-Main processes and adds them into a SharedQueue for Main to pick up
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2004/09/16 18:35:12 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/EventTrapper.h ./Events/EventTrapper.h
--- ../Tekkotsu_2.3/Events/EventTrapper.h	Thu Sep 25 11:27:10 2003
+++ ./Events/EventTrapper.h	Thu Sep 25 11:27:10 2003
@@ -26,7 +26,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Rel $
  * $Date: 2003/09/25 15:27:10 $
diff -urdN ../Tekkotsu_2.3/Events/FilterBankEvent.h ./Events/FilterBankEvent.h
--- ../Tekkotsu_2.3/Events/FilterBankEvent.h	Wed Dec 22 18:12:59 2004
+++ ./Events/FilterBankEvent.h	Wed Jun 29 18:03:35 2005
@@ -9,10 +9,21 @@
 class FilterBankEvent : public EventBase {
 public:
 	//! constructor
-	FilterBankEvent(FilterBankGenerator* creator,EventBase::EventGeneratorID_t gid,unsigned int sid)
-		: EventBase(gid,sid,EventBase::statusETID,0,creator->getName(),1), src(creator)
+	FilterBankEvent(FilterBankGenerator* creator,EventBase::EventGeneratorID_t gid,unsigned int sid,EventBase::EventTypeID_t tid)
+		: EventBase(gid,sid,tid,0,creator->getName()), src(creator)
 	{}
 
+	//! copy constructor (shallow copy -- the generator shouldn't be going anywhere)
+	FilterBankEvent(const FilterBankEvent& fbk) : EventBase(fbk), src(fbk.src) {}
+	
+	//! assignment operator  (shallow copy -- the generator shouldn't be going anywhere)
+	const FilterBankEvent& operator=(const FilterBankEvent& fbk) { EventBase::operator=(fbk); src=fbk.src; return *this; }
+
+	virtual EventBase* clone() const { return new FilterBankEvent(*this); }
+
+	//don't do this until we actually override the LoadSave interface
+	//virtual unsigned int getClassTypeID() const { return makeClassTypeID("FBKE"); }
+
 	//! Gives access to underlying generator
 	inline FilterBankGenerator* getSource() const { return src; }
 
@@ -49,8 +60,6 @@
 	FilterBankGenerator* src;
 
 private:
-	FilterBankEvent(const FilterBankEvent& fbk); //!< don't call
-	const FilterBankEvent& operator=(const FilterBankEvent& fbk); //!< don't call
 };
 
 /*! @file 
@@ -58,10 +67,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/12/22 23:12:59 $
+ * $Date: 2005/06/29 22:03:35 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/LocomotionEvent.cc ./Events/LocomotionEvent.cc
--- ../Tekkotsu_2.3/Events/LocomotionEvent.cc	Wed Sep  1 17:30:57 2004
+++ ./Events/LocomotionEvent.cc	Wed Jun 29 18:03:35 2005
@@ -1,5 +1,9 @@
 #include "LocomotionEvent.h"
 #include <sstream>
+#include <libxml/tree.h>
+
+#include <iostream>
+using namespace std;
 
 std::string
 LocomotionEvent::getDescription(bool showTypeSpecific/*=true*/, unsigned int verbosity/*=0*/) const {
@@ -13,6 +17,9 @@
 unsigned int
 LocomotionEvent::getBinSize() const {
 	unsigned int used=EventBase::getBinSize();
+	if(saveFormat==XML)
+		return used; //if using XML, the XMLLoadSave::getBinSize (called by EventBase::getBinSize) is all we need
+	//otherwise need to add our own fields
 	used+=creatorSize("EventBase::LocomotionEvent");
 	used+=sizeof(x);
 	used+=sizeof(y);
@@ -21,10 +28,10 @@
 }
 
 unsigned int
-LocomotionEvent::LoadBuffer(const char buf[], unsigned int len) {
+LocomotionEvent::LoadBinaryBuffer(const char buf[], unsigned int len) {
 	unsigned int origlen=len;
 	unsigned int used;
-	if(0==(used=EventBase::LoadBuffer(buf,len))) return 0;
+	if(0==(used=EventBase::LoadBinaryBuffer(buf,len))) return 0;
 	len-=used; buf+=used;
 	if(0==(used=checkCreator("EventBase::LocomotionEvent",buf,len,true))) return 0;
 	len-=used; buf+=used;
@@ -38,10 +45,10 @@
 }
 
 unsigned int
-LocomotionEvent::SaveBuffer(char buf[], unsigned int len) const {
+LocomotionEvent::SaveBinaryBuffer(char buf[], unsigned int len) const {
 	unsigned int origlen=len;
 	unsigned int used;
-	if(0==(used=EventBase::SaveBuffer(buf,len))) return 0;
+	if(0==(used=EventBase::SaveBinaryBuffer(buf,len))) return 0;
 	len-=used; buf+=used;
 	if(0==(used=saveCreator("EventBase::LocomotionEvent",buf,len))) return 0;
 	len-=used; buf+=used;
@@ -54,14 +61,77 @@
 	return origlen-len;
 }
 
+void LocomotionEvent::LoadXML(xmlNode* node) {
+	if(node==NULL)
+		return;
+	
+	EventBase::LoadXML(node);
+	
+	for(xmlNode* cur = skipToElement(node->children); cur!=NULL; cur = skipToElement(cur->next)) {
+		if(xmlStrcmp(cur->name, (const xmlChar *)"param"))
+			continue;
+		
+		xmlChar * name = xmlGetProp(cur,(const xmlChar*)"name");
+		if(name==NULL)
+			throw bad_format(cur,"property missing name");
+		
+		xmlChar * val = xmlGetProp(cur,(const xmlChar*)"value");
+		if(val==NULL)
+			throw bad_format(cur,"property missing value");
+		
+		cout << "LoadXML: " << name << "=" << val << endl;
+		
+		if(xmlStrcmp(name, (const xmlChar *)"x")==0)
+			x=atof((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"y")==0)
+			y=atof((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"a")==0)
+			a=atof((const char*)val);
+		
+		xmlFree(val);
+		xmlFree(name);
+	}
+}
+
+//! a little local macro to make saving fields easier
+#define SAVE_PARAM(name) { \
+xmlNode* cur=xmlNewChild(node,NULL,(const xmlChar*)"param",NULL); \
+if(cur==NULL) \
+throw bad_format(node,"Error: LocomotionEvent xml error on saving param"); \
+xmlSetProp(cur,(const xmlChar*)"name",(const xmlChar*)#name); \
+char valbuf[20]; \
+snprintf(valbuf,20,"%g",name); \
+xmlSetProp(cur,(const xmlChar*)"value",(const xmlChar*)valbuf); }
+
+void LocomotionEvent::SaveXML(xmlNode * node) const {
+	if(node==NULL)
+		return;
+	EventBase::SaveXML(node);
+	
+	//clear old params first
+	for(xmlNode* cur = skipToElement(node->children); cur!=NULL; ) {
+		if(xmlStrcmp(cur->name, (const xmlChar *)"param")==0) {
+			xmlUnlinkNode(cur);
+			xmlFreeNode(cur);
+			cur = skipToElement(node->children); //restart the search (boo)
+		} else
+			cur = skipToElement(cur->next);
+	}
+	
+	cout << "SaveXML: " << x << ' ' << y << ' ' << a << endl;
+
+	SAVE_PARAM(x);
+	SAVE_PARAM(y);
+	SAVE_PARAM(a);
+}
 
 /*! @file
  * @brief Implements LocomotionEvent, which gives updates regarding the current movement of the robot through the world
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.1 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2004/09/01 21:30:57 $
+ * $Date: 2005/06/29 22:03:35 $
  */
diff -urdN ../Tekkotsu_2.3/Events/LocomotionEvent.h ./Events/LocomotionEvent.h
--- ../Tekkotsu_2.3/Events/LocomotionEvent.h	Wed Sep  1 17:30:57 2004
+++ ./Events/LocomotionEvent.h	Wed Jun 29 18:03:35 2005
@@ -1,7 +1,9 @@
+//-*-c++-*-
 #ifndef INCLUDED_LocomotionEvent_h_
 #define INCLUDED_LocomotionEvent_h_
 
 #include "EventBase.h"
+#include <iostream>
 
 //! Gives updates regarding the current movement of the robot through the world
 /*! An activate event will be sent when a potential source of motion is created,
@@ -19,8 +21,11 @@
 	LocomotionEvent() : EventBase(),x(0),y(0),a(0) {}
 	LocomotionEvent(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur=0) : EventBase(gid,sid,tid,dur),x(0),y(0),a(0) {}
 	LocomotionEvent(EventGeneratorID_t gid, unsigned int sid, EventTypeID_t tid, unsigned int dur, const std::string& n, float mag) : EventBase(gid,sid,tid,dur,n,mag),x(0),y(0),a(0) {}
+	virtual EventBase* clone() const { return new LocomotionEvent(*this); }
 	//@}
 
+	virtual unsigned int getClassTypeID() const { return makeClassTypeID("LOCO"); }
+
 	//! Allows you to set the new X, Y, and A components
 	LocomotionEvent& setXYA(float X, float Y, float A) {
 		x=X;
@@ -32,8 +37,10 @@
 	virtual std::string getDescription(bool showTypeSpecific=true, unsigned int verbosity=0) const;
 
 	virtual unsigned int getBinSize() const;
-	virtual unsigned int LoadBuffer(const char buf[], unsigned int len);
-	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
+	virtual unsigned int LoadBinaryBuffer(const char buf[], unsigned int len);
+	virtual unsigned int SaveBinaryBuffer(char buf[], unsigned int len) const;
+	virtual void LoadXML(xmlNode* node);
+	virtual void SaveXML(xmlNode * node) const;
 
 	float x; //!< the new x component (body relative)
 	float y; //!< the new y component (body relative)
@@ -45,10 +52,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/09/01 21:30:57 $
+ * $Date: 2005/06/29 22:03:35 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/SegmentedColorFilterBankEvent.h ./Events/SegmentedColorFilterBankEvent.h
--- ../Tekkotsu_2.3/Events/SegmentedColorFilterBankEvent.h	Sun Jan 18 05:16:57 2004
+++ ./Events/SegmentedColorFilterBankEvent.h	Wed Jun 29 18:03:35 2005
@@ -21,15 +21,34 @@
 	typedef __gnu_cxx::hash_map<const char*, unsigned int, __gnu_cxx::hash<const char*>, hashcmp_eqstr> hashmap; //!< a shorthand for the hash structure that CMVision expects for the color lookups
 
 	//! constructor, to be used when first segmented, later stages should use the other constructor
-	SegmentedColorFilterBankEvent(FilterBankGenerator* creator,EventBase::EventGeneratorID_t gid,unsigned int sid, FilterBankGenerator* segColorSrc, unsigned int nColors, color_class_state * colorInfos, const hashmap * clrNames)
-		: FilterBankEvent(creator,gid,sid), segsrc(segColorSrc), numColors(nColors), colors(colorInfos), colorNames(clrNames)
+	SegmentedColorFilterBankEvent(FilterBankGenerator* creator,EventBase::EventGeneratorID_t gid,unsigned int sid,EventBase::EventTypeID_t tid, FilterBankGenerator* segColorSrc, unsigned int nColors, color_class_state * colorInfos, const hashmap * clrNames)
+		: FilterBankEvent(creator,gid,sid,tid), segsrc(segColorSrc), numColors(nColors), colors(colorInfos), colorNames(clrNames)
 	{}
 
 	//! constructor, allows you to pass along color information to later stages
-	SegmentedColorFilterBankEvent(FilterBankGenerator* creator,EventBase::EventGeneratorID_t gid,unsigned int sid, const SegmentedColorFilterBankEvent& segevt )
-		: FilterBankEvent(creator,gid,sid), segsrc(segevt.segsrc), numColors(segevt.numColors), colors(segevt.colors), colorNames(segevt.colorNames)
+	SegmentedColorFilterBankEvent(FilterBankGenerator* creator,EventBase::EventGeneratorID_t gid,unsigned int sid,EventBase::EventTypeID_t tid, const SegmentedColorFilterBankEvent& segevt )
+		: FilterBankEvent(creator,gid,sid,tid), segsrc(segevt.segsrc), numColors(segevt.numColors), colors(segevt.colors), colorNames(segevt.colorNames)
 	{}
 
+	//! copy constructor (shallow copy -- the generator shouldn't be going anywhere)
+	SegmentedColorFilterBankEvent(const SegmentedColorFilterBankEvent& fbk)
+		: FilterBankEvent(fbk), segsrc(fbk.segsrc), numColors(fbk.numColors),
+			colors(fbk.colors), colorNames(fbk.colorNames)
+	{}
+	
+	//! assignment operator  (shallow copy -- the generator shouldn't be going anywhere)
+	const SegmentedColorFilterBankEvent& operator=(const SegmentedColorFilterBankEvent& fbk) {
+		EventBase::operator=(fbk);
+		segsrc=fbk.segsrc; numColors=fbk.numColors;
+		colors=fbk.colors; colorNames=fbk.colorNames;
+		return *this;
+	}
+
+	virtual EventBase* clone() const { return new SegmentedColorFilterBankEvent(*this); }
+
+	//don't do this until we actually override the LoadSave interface
+	//virtual unsigned int getClassTypeID() const { return makeClassTypeID("SFBK"); }
+
 	//! Gives access to underlying generator
 	inline FilterBankGenerator* getSegmentedColorSource() const { return segsrc; }
 
@@ -37,10 +56,10 @@
 	inline unsigned int getNumColors() const { return numColors; }
 
 	//! gives direct access to the color information
-	inline color_class_state * getColors() const { return colors; }
+	inline const color_class_state * getColors() const { return colors; }
 
 	//! gives direct access to the color information
-	inline color_class_state& getColor(unsigned int i) const { return colors[i]; }
+	inline const color_class_state& getColor(unsigned int i) const { return colors[i]; }
 
 	//! returns index of color corresponding to a string (uses a fast hash lookup)
 	inline unsigned int getColorIndex(const char * name) const {
@@ -55,13 +74,10 @@
 protected:
 	//! pointer to generator which did the segmentation and therefore holds the color information
 	FilterBankGenerator* segsrc;
-	const unsigned int numColors; //!< number of available colors
-  color_class_state * const colors; //!< array of available colors
-  const hashmap * const colorNames; //!< hash map to look up index from name
+	unsigned int numColors; //!< number of available colors
+  const color_class_state * colors; //!< array of available colors
+  const hashmap * colorNames; //!< hash map to look up index from name
 
-private:
-	SegmentedColorFilterBankEvent(const SegmentedColorFilterBankEvent& fbk); //!< don't call
-	const SegmentedColorFilterBankEvent& operator=(const SegmentedColorFilterBankEvent& fbk); //!< don't call
 };
 
 /*! @file 
@@ -69,10 +85,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.2 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2004/01/18 10:16:57 $
+ * $Date: 2005/06/29 22:03:35 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/TextMsgEvent.cc ./Events/TextMsgEvent.cc
--- ../Tekkotsu_2.3/Events/TextMsgEvent.cc	Wed Sep  1 17:30:57 2004
+++ ./Events/TextMsgEvent.cc	Fri Jun 10 13:26:30 2005
@@ -1,5 +1,6 @@
 #include "TextMsgEvent.h"
 #include <sstream>
+#include <libxml/tree.h>
 
 std::string
 TextMsgEvent::getDescription(bool showTypeSpecific/*=true*/, unsigned int verbosity/*=0*/) const {
@@ -13,6 +14,9 @@
 unsigned int
 TextMsgEvent::getBinSize() const {
 	unsigned int used=EventBase::getBinSize();
+	if(saveFormat==XML)
+		return used; //if using XML, the XMLLoadSave::getBinSize (called by EventBase::getBinSize) is all we need
+	//otherwise need to add our own fields
 	used+=creatorSize("EventBase::TextMsgEvent");
 	used+=_text.size()+stringpad;
 	//used+=sizeof(_token);
@@ -20,10 +24,10 @@
 }
 
 unsigned int
-TextMsgEvent::LoadBuffer(const char buf[], unsigned int len) {
+TextMsgEvent::LoadBinaryBuffer(const char buf[], unsigned int len) {
 	unsigned int origlen=len;
 	unsigned int used;
-	if(0==(used=EventBase::LoadBuffer(buf,len))) return 0;
+	if(0==(used=EventBase::LoadBinaryBuffer(buf,len))) return 0;
 	len-=used; buf+=used;
 	if(0==(used=checkCreator("EventBase::TextMsgEvent",buf,len,true))) return 0;
 	len-=used; buf+=used;
@@ -35,10 +39,10 @@
 }
 
 unsigned int
-TextMsgEvent::SaveBuffer(char buf[], unsigned int len) const {
+TextMsgEvent::SaveBinaryBuffer(char buf[], unsigned int len) const {
 	unsigned int origlen=len;
 	unsigned int used;
-	if(0==(used=EventBase::SaveBuffer(buf,len))) return 0;
+	if(0==(used=EventBase::SaveBinaryBuffer(buf,len))) return 0;
 	len-=used; buf+=used;
 	if(0==(used=saveCreator("EventBase::TextMsgEvent",buf,len))) return 0;
 	len-=used; buf+=used;
@@ -49,13 +53,61 @@
 	return origlen-len;
 }
 
+void TextMsgEvent::LoadXML(xmlNode* node) {
+	if(node==NULL)
+		return;
+	
+	EventBase::LoadXML(node);
+	
+	for(xmlNode* cur = skipToElement(node->children); cur!=NULL; cur = skipToElement(cur->next)) {
+		if(xmlStrcmp(cur->name, (const xmlChar *)"param"))
+			continue;
+		
+		xmlChar * name = xmlGetProp(cur,(const xmlChar*)"name");
+		if(name==NULL)
+			throw bad_format(cur,"property missing name");
+		
+		xmlChar * val = xmlGetProp(cur,(const xmlChar*)"value");
+		if(val==NULL)
+			throw bad_format(cur,"property missing value");
+		
+		if(xmlStrcmp(name, (const xmlChar *)"text")==0)
+			_text=(const char*)val;
+		
+		xmlFree(val);
+		xmlFree(name);
+	}
+}
+
+void TextMsgEvent::SaveXML(xmlNode * node) const {
+	if(node==NULL)
+		return;
+	EventBase::SaveXML(node);
+	
+	//clear old params first
+	for(xmlNode* cur = skipToElement(node->children); cur!=NULL; ) {
+		if(xmlStrcmp(cur->name, (const xmlChar *)"param")==0) {
+			xmlUnlinkNode(cur);
+			xmlFreeNode(cur);
+			cur = skipToElement(node->children); //restart the search (boo)
+		} else
+			cur = skipToElement(cur->next);
+	}
+	
+	xmlNode* cur=xmlNewChild(node,NULL,(const xmlChar*)"param",NULL);
+	if(cur==NULL)
+		throw bad_format(node,"Error: VisionObjectEvent xml error on saving param");
+	xmlSetProp(cur,(const xmlChar*)"name",(const xmlChar*)"text");
+	xmlSetProp(cur,(const xmlChar*)"value",(const xmlChar*)_text.c_str());
+}
+
 /*! @file
  * @brief Implements TextMsgEvent, which extends EventBase to also include actual message text
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.1 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
  * $State: Exp $
- * $Date: 2004/09/01 21:30:57 $
+ * $Date: 2005/06/10 17:26:30 $
  */
diff -urdN ../Tekkotsu_2.3/Events/TextMsgEvent.h ./Events/TextMsgEvent.h
--- ../Tekkotsu_2.3/Events/TextMsgEvent.h	Wed Sep  1 17:30:57 2004
+++ ./Events/TextMsgEvent.h	Wed Jun 29 18:03:35 2005
@@ -13,6 +13,10 @@
   //! Constructor, pass a text msg
   TextMsgEvent(const std::string& text) : EventBase(EventBase::textmsgEGID,(unsigned int)-1, EventBase::statusETID,0),_text(text)/*,_token(0)*/ { }
   
+	virtual EventBase* clone() const { return new TextMsgEvent(*this); }
+
+	virtual unsigned int getClassTypeID() const { return makeClassTypeID("TXTM"); }
+
   std::string getText() const { return _text; } //!< returns the text
   TextMsgEvent& setText(const std::string& text) { _text=text; return *this; } //!< sets the text
   
@@ -22,9 +26,11 @@
 	std::string getDescription(bool showTypeSpecific=true, unsigned int verbosity=0) const;
 	
 	virtual unsigned int getBinSize() const;
-	virtual unsigned int LoadBuffer(const char buf[], unsigned int len);
-	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
-
+	virtual unsigned int LoadBinaryBuffer(const char buf[], unsigned int len);
+	virtual unsigned int SaveBinaryBuffer(char buf[], unsigned int len) const;
+	virtual void LoadXML(xmlNode* node);
+	virtual void SaveXML(xmlNode * node) const;
+	
  protected:
   std::string _text; //!< the unmodified arguments passed to the command
   //int _token;      //!< for future expansion, to support centralized parsing
@@ -35,10 +41,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.10 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.12 $
  * $State: Exp $
- * $Date: 2004/09/01 21:30:57 $
+ * $Date: 2005/06/29 22:03:35 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Events/VisionObjectEvent.cc ./Events/VisionObjectEvent.cc
--- ../Tekkotsu_2.3/Events/VisionObjectEvent.cc	Wed Jan 12 16:48:17 2005
+++ ./Events/VisionObjectEvent.cc	Sun Aug  7 00:11:03 2005
@@ -1,5 +1,6 @@
 #include "VisionObjectEvent.h"
 #include <sstream>
+#include <libxml/tree.h>
 
 // Changed 'getDescription' to show BB and area info in EventLogger. Change functions to add new parameters (BB and area) to buffer
 
@@ -8,13 +9,16 @@
 	if(!showTypeSpecific)
 		return EventBase::getDescription(showTypeSpecific,verbosity);
 	std::ostringstream logdata;
-	logdata << EventBase::getDescription(showTypeSpecific,verbosity) << '\t' << _x1 <<  '\t' <<_x2 <<'\t' <<_y1 <<'\t' <<_y2 ;
+	logdata << EventBase::getDescription(showTypeSpecific,verbosity) << '\t' << _x1 <<  '\t' <<_x2 <<'\t' <<_y1 <<'\t' <<_y2<<'\t'<<_frame ;
 	return logdata.str();
 }
 
 unsigned int
 VisionObjectEvent::getBinSize() const {
 	unsigned int used=EventBase::getBinSize();
+	if(saveFormat==XML)
+		return used; //if using XML, the XMLLoadSave::getBinSize (called by EventBase::getBinSize) is all we need
+	//otherwise need to add our own fields
 	used+=creatorSize("EventBase::VisionObjectEvent");
 	used+=sizeof(_x1);
 	used+=sizeof(_x2);
@@ -24,10 +28,10 @@
 }
 
 unsigned int
-VisionObjectEvent::LoadBuffer(const char buf[], unsigned int len) {
+VisionObjectEvent::LoadBinaryBuffer(const char buf[], unsigned int len) {
 	unsigned int origlen=len;
 	unsigned int used;
-	if(0==(used=EventBase::LoadBuffer(buf,len))) return 0;
+	if(0==(used=EventBase::LoadBinaryBuffer(buf,len))) return 0;
 	len-=used; buf+=used;
 	if(0==(used=checkCreator("EventBase::VisionObjectEvent",buf,len,true))) return 0;
 	len-=used; buf+=used;
@@ -43,10 +47,10 @@
 }
 
 unsigned int
-VisionObjectEvent::SaveBuffer(char buf[], unsigned int len) const {
+VisionObjectEvent::SaveBinaryBuffer(char buf[], unsigned int len) const {
 	unsigned int origlen=len;
 	unsigned int used;
-	if(0==(used=EventBase::SaveBuffer(buf,len))) return 0;
+	if(0==(used=EventBase::SaveBinaryBuffer(buf,len))) return 0;
 	len-=used; buf+=used;
 	if(0==(used=saveCreator("EventBase::VisionObjectEvent",buf,len))) return 0;
 	len-=used; buf+=used;
@@ -61,14 +65,89 @@
 	return origlen-len;
 }
 
+void VisionObjectEvent::LoadXML(xmlNode* node) {
+	if(node==NULL)
+		return;
+	
+	EventBase::LoadXML(node);
+
+	for(xmlNode* cur = skipToElement(node->children); cur!=NULL; cur = skipToElement(cur->next)) {
+		if(xmlStrcmp(cur->name, (const xmlChar *)"param"))
+			continue;
+
+		xmlChar * name = xmlGetProp(cur,(const xmlChar*)"name");
+		if(name==NULL)
+			throw bad_format(cur,"property missing name");
+
+		xmlChar * val = xmlGetProp(cur,(const xmlChar*)"value");
+		if(val==NULL)
+			throw bad_format(cur,"property missing value");
+
+		if(xmlStrcmp(name, (const xmlChar *)"x1")==0)
+			_x1=atof((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"x2")==0)
+			_x2=atof((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"y1")==0)
+			_y1=atof((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"y2")==0)
+			_y2=atof((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"clipLeft")==0)
+			_clipLeft=atoi((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"clipRight")==0)
+			_clipRight=atoi((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"clipTop")==0)
+			_clipTop=atoi((const char*)val);
+		else if(xmlStrcmp(name, (const xmlChar *)"clipBottom")==0)
+			_clipBottom=atoi((const char*)val);
+		
+		xmlFree(val);
+		xmlFree(name);
+	}
+}
+
+//! a little local macro to make saving fields easier
+#define SAVE_PARAM(strname,varname,format) {\
+xmlNode* cur=xmlNewChild(node,NULL,(const xmlChar*)"param",NULL); \
+if(cur==NULL) \
+throw bad_format(node,"Error: VisionObjectEvent xml error on saving param"); \
+xmlSetProp(cur,(const xmlChar*)"name",(const xmlChar*)strname); \
+char valbuf[20]; \
+snprintf(valbuf,20,format,varname); \
+xmlSetProp(cur,(const xmlChar*)"value",(const xmlChar*)valbuf); }
+
+void VisionObjectEvent::SaveXML(xmlNode * node) const {
+	if(node==NULL)
+		return;
+	EventBase::SaveXML(node);
+	
+	//clear old params first
+	for(xmlNode* cur = skipToElement(node->children); cur!=NULL; ) {
+		if(xmlStrcmp(cur->name, (const xmlChar *)"param")==0) {
+			xmlUnlinkNode(cur);
+			xmlFreeNode(cur);
+			cur = skipToElement(node->children); //restart the search (boo)
+		} else
+			cur = skipToElement(cur->next);
+	}
+	
+	SAVE_PARAM("x1",_x1,"%g");
+	SAVE_PARAM("y1",_y1,"%g");
+	SAVE_PARAM("x2",_x2,"%g");
+	SAVE_PARAM("y2",_y2,"%g");
+	SAVE_PARAM("clipLeft",_clipLeft,"%d");
+	SAVE_PARAM("clipRight",_clipRight,"%d");
+	SAVE_PARAM("clipTop",_clipTop,"%d");
+	SAVE_PARAM("clipBottom",_clipBottom,"%d");
+}
+
 /*! @file
  * @brief Implements VisionObjectEvent, which provides information about objects recognized in the camera image
  * @author alokl (Creator)
- * @author Ignacio Herrero Reder <nhr at dte uma es> (VisionObjectInfo Boundary Box - bug 74)
+ * @author Ignacio Herrero Reder &lt; nhr at dte uma es &gt; (VisionObjectInfo Boundary Box - bug 74)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2005/01/12 21:48:17 $
+ * $Date: 2005/08/07 04:11:03 $
  */
diff -urdN ../Tekkotsu_2.3/Events/VisionObjectEvent.h ./Events/VisionObjectEvent.h
--- ../Tekkotsu_2.3/Events/VisionObjectEvent.h	Wed Jan 12 16:48:17 2005
+++ ./Events/VisionObjectEvent.h	Sun Aug  7 00:11:03 2005
@@ -7,47 +7,87 @@
 //! Extends EventBase to also include location in the visual field and distance (though distance is not implimented yet)
 class VisionObjectEvent : public EventBase {
 public:
-	//! Constructor
-  VisionObjectEvent()
-		: EventBase(EventBase::visObjEGID,(unsigned int)-1,EventBase::statusETID,0),_x1(0),_x2(0),_y1(0),_y2(0),
-			_clipLeft(false), _clipRight(false), _clipTop(false), _clipBottom(false)
-	{}
-	
-	//! Constructor, pass a type id and source id
-  VisionObjectEvent(EventTypeID_t tid, unsigned int sid)
-		: EventBase(EventBase::visObjEGID,sid,tid,0),_x1(0),_x2(0),_y1(0),_y2(0),
-			_clipLeft(false), _clipRight(false), _clipTop(false), _clipBottom(false)
+	//! Constructor, pass a source id and type id -- mainly useful for deactivate events since all object parameters are going to be set to 0
+	/*! @param sid The source ID for the object being detected -- you can define your own values, some are already set in ProjectInterface, but can be reassigned during your project's startup
+	 *  @param tid The type ID for the event
+	 */
+  explicit VisionObjectEvent(unsigned int sid=0,EventTypeID_t tid=EventBase::deactivateETID)
+		: EventBase(EventBase::visObjEGID,sid,tid,0),
+			_x1(0),_x2(0),_y1(0),_y2(0), _area(0),
+			_clipLeft(false), _clipRight(false), _clipTop(false), _clipBottom(false),
+			_xRange(0), _yRange(0), _frame(0)
 	{}
 		
 	//! Constructor, pass the type id, source id, left, right, top, bottom, x range, and y range
-  VisionObjectEvent(EventTypeID_t tid, unsigned int sid, float x1, float x2, float y1, float y2, float rx, float ry)
-		: EventBase(EventBase::visObjEGID,sid,tid,0),_x1(x1),_x2(x2),_y1(y1),_y2(y2),
-			_clipLeft(_x1<=-rx), _clipRight(_x2>=rx), _clipTop(_y1<=-ry), _clipBottom(_y2>=ry)
+	/*! @param sid The source ID for the object being detected -- you can define your own values, some are already set in ProjectInterface, but can be reassigned during your project's startup
+	 *  @param tid The type ID for the event
+	 *  @param x1 The leftmost extent of the object, in generalized coordinates (see #_x1)
+	 *  @param x2 The rightmost extent of the object in generalized coordinates (see #_x2)
+	 *  @param y1 The topmost extent of the object, in generalized coordinates (see #_y1)
+	 *  @param y2 The bottommost extent of the object, in generalized coordinates (see #_y2)
+	 *  @param objarea The area of the object being detected, in squared generalized coordinates (see #_area)
+	 *  @param rx The plus/minus range of the x coordinates (generally xres/xres for cameras which are wider than they are high)
+	 *  @param ry The plus/minus range of the y coordinates (camera yres/xres for cameras which are wider than they are high)
+	 */
+  VisionObjectEvent(unsigned int sid, EventTypeID_t tid, float x1, float x2, float y1, float y2,float objarea, float rx, float ry)
+		: EventBase(EventBase::visObjEGID,sid,tid,0),
+			_x1(x1),_x2(x2),_y1(y1),_y2(y2), _area(objarea),
+			_clipLeft(_x1<=-rx), _clipRight(_x2>=rx), _clipTop(_y1<=-ry), _clipBottom(_y2>=ry),
+			_xRange(rx), _yRange(ry), _frame(0)
 	{}
 	
+ 	//! Constructor, pass the type id, source id, left, right, top, bottom, x range, y range, and frame_number
+	/*! @param sid The source ID for the object being detected -- you can define your own values, some are already set in ProjectInterface, but can be reassigned during your project's startup
+	 *  @param tid The type ID for the event
+	 *  @param x1 The leftmost extent of the object, in generalized coordinates (see #_x1)
+	 *  @param x2 The rightmost extent of the object in generalized coordinates (see #_x2)
+	 *  @param y1 The topmost extent of the object, in generalized coordinates (see #_y1)
+	 *  @param y2 The bottommost extent of the object, in generalized coordinates (see #_y2)
+	 *  @param objarea The area of the object being detected, in squared generalized coordinates (see #_area)
+	 *  @param rx The plus/minus range of the x coordinates (generally xres/xres for cameras which are wider than they are high)
+	 *  @param ry The plus/minus range of the y coordinates (camera yres/xres for cameras which are wider than they are high)
+	 *  @param frame The camera frame number the object was detected in (see #_frame)
+	 */
+  VisionObjectEvent(unsigned int sid, EventTypeID_t tid, float x1, float x2, float y1, float y2, float objarea, float rx, float ry,unsigned int frame)
+		: EventBase(EventBase::visObjEGID,sid,tid,0),
+			_x1(x1),_x2(x2),_y1(y1),_y2(y2), _area(objarea),
+			_clipLeft(_x1<=-rx), _clipRight(_x2>=rx), _clipTop(_y1<=-ry), _clipBottom(_y2>=ry),
+			_xRange(rx),_yRange(ry), _frame(frame)
+	{} 
+  
 	//! destructor
 	virtual ~VisionObjectEvent() {}
   
+	virtual EventBase* clone() const { return new VisionObjectEvent(*this); }
+
+	virtual unsigned int getClassTypeID() const { return makeClassTypeID("VISO"); }
+
 	//!@name Attribute Accessors
-  float getLeft() const { return _x1;} //!< returns the initial x coordinate of the Bounding Box
-  VisionObjectEvent& setLeft(float x1) { _x1=x1; return *this;} //!< sets the initial x coordinate of the Bounding Box
+  float getLeft() const { return _x1;} //!< returns the initial x (#_x1) coordinate of the Bounding Box (inclusive value)
+  VisionObjectEvent& setLeft(float x1) { _x1=x1; return *this;} //!< sets the initial x (#_x1) coordinate of the Bounding Box
   
-  float getRight() const { return _x2;} //!< returns the final x coordinate of the Bounding Box
-  VisionObjectEvent& setRight(float x2) { _x2=x2; return *this;} //!< sets the final x coordinate of the Bounding Box
+  float getRight() const { return _x2;} //!< returns the final x (#_x2) coordinate of the Bounding Box (inclusive value)
+  VisionObjectEvent& setRight(float x2) { _x2=x2; return *this;} //!< sets the final x (#_x2) coordinate of the Bounding Box
   
-	float getTop() const { return _y1;} //!< returns the initial y coordinate of the Bounding Box
-  VisionObjectEvent& setTop(float y1) { _y1=y1; return *this;} //!< sets the initial y coordinate of the Bounding Box
+	float getTop() const { return _y1;} //!< returns the initial y (#_y1) coordinate of the Bounding Box (inclusive value)
+  VisionObjectEvent& setTop(float y1) { _y1=y1; return *this;} //!< sets the initial y (#_y1) coordinate of the Bounding Box
   
-  float getBottom() const { return _y2;} //!< returns the final y coordinate of the Bounding Box
-  VisionObjectEvent& setBottom(float y2) { _y2=y2; return *this;} //!< sets the final y coordinate of the Bounding Box
+  float getBottom() const { return _y2;} //!< returns the final y (#_y2) coordinate of the Bounding Box (inclusive value)
+  VisionObjectEvent& setBottom(float y2) { _y2=y2; return *this;} //!< sets the final y (#_y2) coordinate of the Bounding Box
+
+	float getObjectArea() const { return _area; } //!< returns the object's #_area within the camera, in squared generalized coordinates (multiply by the major camera resolution to get pixel area)
+	VisionObjectEvent& setObjectArea(float objarea) { _area=objarea; return *this; } //!< returns the object's #_area within the camera, in squared generalized coordinates (multiply by the major camera resolution to get pixel area)
 	//@}
  
 	//!@name Calculated Attributes
   float getCenterX() const { return (_x1+_x2)/2; } //!< returns the center along x
   float getCenterY() const { return (_y1+_y2)/2; } //!< returns the center along y
-	float getWidth() const { return _x2-_x1; } //!< return width along x
-	float getHeight() const { return _x2-_x1; } //!< return height along y
-  float getArea() const { return (_x2-_x1)*(_y2-_y1); } //!< returns the final x coordinate of the Bounding Box
+  float getWidth() const { return _x2-_x1; } //!< return width along x
+  float getHeight() const { return _y2-_y1; } //!< return height along y
+  float getBoundaryArea() const { return (_x2-_x1)*(_y2-_y1); } //!< returns the area of the bounding box, just multiplication of width*height, (multiply by the major camera resolution to get pixel area)
+  float getXrange() const{ return  _xRange;}//!< returns the maximum x value
+  float getYrange() const{return _yRange;}//!< returns the maximum y value
+  unsigned int getFrame() const{return _frame;}//!< returns number of frame when the event was generated
 	//@}
 
   //!@name Object out of bounds Detection Functions
@@ -61,30 +101,36 @@
 	virtual std::string getDescription(bool showTypeSpecific=true, unsigned int verbosity=0) const;
 	
 	virtual unsigned int getBinSize() const;
-	virtual unsigned int LoadBuffer(const char buf[], unsigned int len);
-	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
+	virtual unsigned int LoadBinaryBuffer(const char buf[], unsigned int len);
+	virtual unsigned int SaveBinaryBuffer(char buf[], unsigned int len) const;
+	virtual void LoadXML(xmlNode* node);
+	virtual void SaveXML(xmlNode * node) const;
 
 protected:
 	float _x1;  //!< a value representing location in visual field - from -1 if on the left edge to 1 if it's on the right edge
-	float _x2;  //!< a value representing location in visual field - from -1 if on the bottom edge to 1 if it's on the top edge
-	float _y1;  //!< top boundary, in approximate range (+/- 160/208) for ERS-7; actual values vary depending on aspect ratio to keep square coordinates
-	float _y2;  //!< top boundary, in approximate range (+/- 160/208) for ERS-7; actual values vary depending on aspect ratio to keep square coordinates
+	float _x2;  //!< a value representing location in visual field - from -1 if on the left edge to 1 if it's on the right edge
+	float _y1;  //!< top boundary, in range of @f$ \pm\frac{160}{208} @f$) for ERS-7; actual values vary depending on aspect ratio to keep square coordinates
+	float _y2;  //!< bottom boundary, in approximately @f$ \pm\frac{160}{208} @f$ for ERS-7; actual values vary depending on aspect ratio to keep square coordinates
+	float _area; //!< area of the actual object within bounding box as set by generator, in same units as getBoundaryArea() (squared generalized coordinates -- multiply by the major camera resolution to get pixel area)
 	bool _clipLeft;   //!< flag to indicate left boundary is on or beyond the camera image's boundary
 	bool _clipRight;  //!< flag to indicate right boundary is on or beyond the camera image's boundary
 	bool _clipTop;    //!< flag to indicate top boundary is on or beyond the camera image's boundary
 	bool _clipBottom; //!< flag to indicate bottom boundary is on or beyond the camera image's boundary
+	float _xRange; //!< Max range of X dimension
+	float _yRange; //!< Max range of Y dimension
+	unsigned int _frame; //!< Number of frame when the event was generated.
 };
 
 /*! @file
  * @brief Describes VisionObjectEvent, which provides information about objects recognized in the camera image
  * @author alokl (Creator)
- * @author Ignacio Herrero Reder <nhr at dte uma es> (VisionObjectInfo Boundary Box - bug 74)
+ * @author Ignacio Herrero Reder &lt; nhr at dte uma es &gt; (VisionObjectInfo Boundary Box - bug 74, frame number - bug 143)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2005/01/12 21:48:17 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/IPC/CVS/Entries ./IPC/CVS/Entries
--- ../Tekkotsu_2.3/IPC/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./IPC/CVS/Entries	Wed Aug 10 11:03:18 2005
@@ -0,0 +1,19 @@
+/ListMemBuf.h/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/LockScope.h/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/MessageQueue.h/1.12/Thu Aug  4 21:32:16 2005//Ttekkotsu-2_4
+/MessageReceiver.cc/1.7/Thu Jul 28 18:22:16 2005//Ttekkotsu-2_4
+/MessageReceiver.h/1.5/Thu Jul 28 18:22:16 2005//Ttekkotsu-2_4
+/MutexLock.cc/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/MutexLock.h/1.6/Tue Jul 26 03:22:02 2005//Ttekkotsu-2_4
+/ProcessID.cc/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/ProcessID.h/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/RCRegion.cc/1.3/Thu Jun 23 20:17:54 2005//Ttekkotsu-2_4
+/RCRegion.h/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/RegionRegistry.h/1.2/Wed Jun  1 05:47:46 2005//Ttekkotsu-2_4
+/SemaphoreManager.cc/1.4/Thu Jun 23 20:18:56 2005//Ttekkotsu-2_4
+/SemaphoreManager.h/1.5/Wed Jun 15 03:40:05 2005//Ttekkotsu-2_4
+/SharedObject.cc/1.2/Wed Jun  1 05:47:47 2005//Ttekkotsu-2_4
+/SharedObject.h/1.3/Mon Jun 13 20:29:48 2005//Ttekkotsu-2_4
+/Thread.cc/1.6/Mon Aug  1 23:17:59 2005//Ttekkotsu-2_4
+/Thread.h/1.4/Mon Aug  1 23:17:59 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/IPC/CVS/Repository ./IPC/CVS/Repository
--- ../Tekkotsu_2.3/IPC/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./IPC/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/IPC
diff -urdN ../Tekkotsu_2.3/IPC/CVS/Root ./IPC/CVS/Root
--- ../Tekkotsu_2.3/IPC/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./IPC/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/IPC/CVS/Tag ./IPC/CVS/Tag
--- ../Tekkotsu_2.3/IPC/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./IPC/CVS/Tag	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/IPC/ListMemBuf.h ./IPC/ListMemBuf.h
--- ../Tekkotsu_2.3/IPC/ListMemBuf.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/ListMemBuf.h	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,353 @@
+//-*-c++-*-
+#ifndef INCLUDED_ListMemBuf_h
+#define INCLUDED_ListMemBuf_h
+
+//! Provides some degree of dynamic allocation of a templated type from a buffer of set size.
+/*! Think of this as a self-contained mini-malloc...
+	  
+    This is handy for classes which inhabit a shared memory region, where
+    it's a bad idea to have pointers to other memory.  By instantiating one
+    of these in your class, you can allocate space internally for up to
+    MAX objects of type T_t.  ListMemBuf will worry about keeping track
+    of which ones are in use or are free.
+
+    Each time you request a entry to be created, the destructor will be
+    called followed by the the defaul constructor before it is given to
+    you, so the fields should be reliably 'fresh', not what was in the
+    entry last time it was used.
+*/
+template < class T_t, unsigned int MAX, class idx_t=unsigned short >
+class ListMemBuf {
+	public:
+	
+	ListMemBuf(); //!<constructor
+	~ListMemBuf(); //!<destructor
+	
+	//!Allows outside access to storage type
+	typedef T_t T;
+	//!Allows outside access to number of entries
+	static const unsigned int MAX_ENTRIES = MAX;
+	//!Allows outside access to index type
+	typedef idx_t index_t;
+	
+	static index_t getMaxCapacity() { return MAX_ENTRIES; } //!<returns the maximum number of objects which can be used at any given time
+	index_t size() const { return cursize; } //!<returns the current number of objects in use
+	index_t countf() const; //!< for debugging, should equal size
+	index_t countb() const; //!< for debugging, should equal size
+	bool empty() const { return cursize==0; } //!<returns true if no objects are in use
+
+	inline T& operator[](unsigned int x) { return *reinterpret_cast<T*>(entries[x].data); } //!<allows direct access to elements - be careful, can access 'free' elements this way
+	inline const T& operator[](unsigned int x) const { return *reinterpret_cast<const T*>(entries[x].data); } //!<allows direct access to elements - be careful, can access 'free' elements this way
+
+	inline index_t begin() const { return activeBegin; } //!<returns index of first used entry
+	T& front() { return *reinterpret_cast<T*>(entries[activeBegin].data); } //!< returns reference to first used entry
+	const T& front() const { return *reinterpret_cast<const T*>(entries[activeBegin].data); } //!< returns const reference to first used entry
+
+	inline index_t end() const { return (index_t)-1; } //!<returns the one-past-end index
+	T& back() { return *reinterpret_cast<T*>(entries[activeBack].data); } //!<returns reference to last used entry
+	const T& back() const { return *reinterpret_cast<const T*>(entries[activeBack].data); } //!<returns const reference to last used entry
+
+	index_t new_front(); //!<pushes a 'blank' entry on the front of the used list
+	index_t push_front(const T& data) { index_t tmp=new_front(); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<pushes an entry on the front of the used chain and assigns @a data to it
+	void pop_front(); //!<pops the front of the used chain
+	void pop_front(T& ret) { ret=front(); pop_front(); } //!<pops the front of the chain into @a ret
+
+	index_t new_back(); //!<pushes a 'blank' entry on the back of the used list
+	index_t push_back(const T& data) { index_t tmp=new_back(); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<pushes an entry on the back of the used chain and assigns @a data to it
+	void pop_back(); //!<pops the last of the used chain
+	void pop_back(T& ret) { ret=back(); pop_back(); } //!<pops the last of the used chain into @a ret
+
+	index_t new_before(index_t x); //!<inserts a 'blank' entry before element @a x in the used chain
+	index_t push_before(index_t x, const T& data) { index_t tmp=new_before(x); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<inserts a 'blank' entry before element @a x in the used chain and assigns @a data to it
+
+	index_t new_after(index_t x) { return new_before(next(x)); } //!<inserts a 'blank' entry after element @a x in the used chain
+	index_t push_after(index_t x, const T& data) { index_t tmp=new_after(x); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<inserts a 'blank' entry after element @a x in the used chain and assigns @a data to it
+
+	void erase(index_t x); //!<removes element @a x from the used chain
+	void clear(); //!<frees all used entries
+
+	void swap(index_t a, index_t b); //!<swaps the two entries' position in the list
+
+	index_t next(index_t x) const { return x==end()?activeBegin:entries[x].next; } //!< returns the next used element following @a x
+	index_t prev(index_t x) const { return x==end()?activeBack:entries[x].prev; } //!< returns the preceeding used element following @a x
+ 
+	protected:
+	index_t pop_free(); //!<removes an element from the front of the free list, returns its index
+	void push_free(index_t x); //!<pushes @a x onto the back of the free list
+	
+	//!holds data about an entry in the free/used lists
+	struct entry_t {
+		//!constructor
+		entry_t() : next(static_cast<index_t>(-1)), prev(static_cast<index_t>(-1)) {}
+		double data[(sizeof(T)-1)/sizeof(double)+1]; //!<The data being stored, not actually an instantiation of T, but big enough to hold it.  (Funky array size is to ensure proper alignment of contents)
+		index_t next; //!<The next element in the used or free chain
+		index_t prev; //!<The previous element in the used chain, invalid if in the free chain
+	};
+	entry_t entries[MAX_ENTRIES]; //!<the main block of data
+	index_t activeBegin; //!<beginning of used chain
+	index_t activeBack; //!<end of used chain
+	index_t freeBegin; //!<beginning of free chain
+	index_t freeBack; //!<end of free chain
+	index_t cursize; //!< current number of used elements
+};
+
+template < class T, unsigned int MAX, class index_t >
+ListMemBuf<T,MAX,index_t>::ListMemBuf()
+	: activeBegin(end()), activeBack(end()), freeBegin(end()), freeBack(end()), cursize(0)
+{
+	for(unsigned int x=0; x+1<MAX_ENTRIES; x++)
+		entries[x].next=x+1;
+	entries[MAX_ENTRIES-1].next=end();
+	freeBegin=0;
+	freeBack=MAX_ENTRIES-1;
+}
+
+template < class T, unsigned int MAX, class index_t >
+ListMemBuf<T,MAX,index_t>::~ListMemBuf() {
+	clear();
+}
+
+template < class T, unsigned int MAX, class index_t>
+index_t
+ListMemBuf<T,MAX,index_t>::countf() const {
+	int x=0;
+	for(index_t c=begin(); c!=end(); c=next(c))
+		x++;
+	return x;
+}
+
+template < class T, unsigned int MAX, class index_t>
+index_t
+ListMemBuf<T,MAX,index_t>::countb() const {
+	int x=0;
+	for(index_t c=end(); c!=begin(); c=prev(c))
+		x++;
+	return x;
+}
+
+template < class T, unsigned int MAX, class index_t >
+index_t
+ListMemBuf<T,MAX,index_t>::new_front() {
+	index_t tmp = pop_free();
+	if(tmp==end())
+		return end();
+	entries[tmp].prev=end();
+	entries[tmp].next=activeBegin;
+	if(activeBegin!=end())
+		entries[activeBegin].prev=tmp;
+	else
+		activeBack=tmp;
+	activeBegin=tmp;
+	return tmp;
+}
+
+template < class T, unsigned int MAX, class index_t >
+index_t
+ListMemBuf<T,MAX,index_t>::new_back() {
+	index_t tmp = pop_free();
+	if(tmp==end())
+		return end();
+	entries[tmp].prev=activeBack;
+	entries[tmp].next=end();
+	if(activeBack!=end())
+		entries[activeBack].next=tmp;
+	else
+		activeBegin=tmp;
+	activeBack=tmp;
+	return tmp;
+}
+
+template < class T, unsigned int MAX, class index_t >
+index_t
+ListMemBuf<T,MAX,index_t>::new_before(index_t x) {
+	if(x==end())
+		return new_back();
+	if(entries[x].prev==end())
+		return new_front();
+	index_t tmp = pop_free();
+	if(tmp==end())
+		return end();
+	entries[tmp].next=x;
+	entries[tmp].prev=entries[x].prev;
+	entries[x].prev=tmp;
+	entries[ entries[tmp].prev ].next = tmp;
+	return tmp;
+}
+
+template < class T, unsigned int MAX, class index_t >
+void
+ListMemBuf<T,MAX,index_t>::pop_front() {
+	index_t tmp = activeBegin;
+	activeBegin = entries[activeBegin].next;
+	if(activeBegin==end())
+		activeBack=end();
+	else
+		entries[activeBegin].prev = end();
+	push_free(tmp);
+}
+
+template < class T, unsigned int MAX, class index_t >
+void
+ListMemBuf<T,MAX,index_t>::pop_back() {
+	index_t tmp = activeBack;
+	activeBack = entries[activeBack].prev;
+	if(activeBack==end())
+		activeBegin=end();
+	else
+		entries[activeBack].next = end();
+	push_free(tmp);
+}
+
+template < class T, unsigned int MAX, class index_t >
+void
+ListMemBuf<T,MAX,index_t>::erase(index_t x) {
+	if(x==activeBegin) {
+		pop_front();
+		return;
+	}
+	if(x==activeBack) {
+		pop_back();
+		return;
+	}
+	entries[ entries[x].next ].prev = entries[x].prev;
+	entries[ entries[x].prev ].next = entries[x].next;
+	push_free(x);
+}
+
+template < class T, unsigned int MAX, class index_t >
+void
+ListMemBuf<T,MAX,index_t>::clear() {
+	if(cursize!=0) {
+		for(index_t it=activeBegin; it!=end(); it=entries[it].next)
+			operator[](it).~T();
+		if(freeBack==end())
+			freeBegin=activeBegin;
+		else
+			entries[freeBack].next=activeBegin;
+		freeBack=activeBack;
+		activeBegin=activeBack=end();
+	}
+	cursize=0;
+}
+
+template < class T, unsigned int MAX, class index_t >
+void
+ListMemBuf<T,MAX,index_t>::swap(index_t a, index_t b) {
+	if(a==b || a==end() || b==end())
+		return;
+	if(entries[a].prev==b) {
+		entries[a].prev=entries[b].prev;
+		entries[b].next=entries[a].next;
+		entries[a].next=b;
+		entries[b].prev=a;
+		if(entries[a].prev!=end())
+			entries[entries[a].prev].next=a;
+		else
+			activeBegin=a;
+		if(entries[b].next!=end())
+			entries[entries[b].next].prev=b;
+		else
+			activeBack=b;
+	} else if(entries[a].next==b) {
+		entries[a].next=entries[b].next;
+		entries[b].prev=entries[a].prev;
+		entries[a].prev=b;
+		entries[b].next=a;
+		if(entries[a].next!=end())
+			entries[entries[a].next].prev=a;
+		else
+			activeBack=a;
+		if(entries[b].prev!=end())
+			entries[entries[b].prev].next=b;
+		else
+			activeBegin=b;
+	} else {
+		index_t tmpp=entries[a].prev, tmpn=entries[a].next;
+		entries[a].prev=entries[b].prev;
+		entries[a].next=entries[b].next;
+		entries[b].prev=tmpp;
+		entries[b].next=tmpn;
+		if(entries[a].prev!=end())
+			entries[entries[a].prev].next=a;
+		else
+			activeBegin=a;
+		if(entries[a].next!=end())
+			entries[entries[a].next].prev=a;
+		else
+			activeBack=a;
+		if(entries[b].prev!=end())
+			entries[entries[b].prev].next=b;
+		else
+			activeBegin=b;
+		if(entries[b].next!=end())
+			entries[entries[b].next].prev=b;
+		else
+			activeBack=b;
+	}
+	/*
+	// Front Back => Front Back
+	//  a     b       b     a
+	//  a     -       b     -
+	//  b     a       a     b
+	//  b     -       a     -
+	//  -     a       -     b
+	//  -     b       -     a
+	if(activeBegin==a) {
+		activeBegin=b;
+		if(activeBack==b)
+			activeBack=a;
+	} else if(activeBegin==b) {
+		activeBegin=a;
+		if(activeBack==a)
+			activeBack=b;
+	} else {
+		if(activeBack==a)
+			activeBack=b;
+		else if(activeBack=b)
+			activeBack==a;
+	}
+	*/
+}
+
+/*! free list is a queue... pop front, push back - hopefully more robust with multi-threads
+    is purposely sloppy with unused links, a little faster*/
+template < class T, unsigned int MAX, class index_t >
+index_t
+ListMemBuf<T,MAX,index_t>::pop_free() {
+	if(freeBegin==end())
+		return end();
+	index_t tmp=freeBegin;
+	if(freeBegin==freeBack)
+		freeBegin=freeBack=end();
+	else
+		freeBegin=entries[freeBegin].next;
+	cursize++;
+	new (entries[tmp].data) T;  //calls constructor so that the data is "fresh"
+	return tmp;
+}
+
+/*! @see pop_free() */
+template < class T, unsigned int MAX, class index_t >
+void
+ListMemBuf<T,MAX,index_t>::push_free(index_t x) {
+	if(freeBack==end())
+		freeBegin=x;
+	else
+		entries[freeBack].next=x;
+	freeBack=x;
+	cursize--;
+	operator[](x).~T(); //to match the constructor call in pop_free() (or the entry_t constructor during initialization)
+}
+
+/*! @file
+ * @brief Defines ListMemBuf, which provides some degree of dynamic allocation of a templated type from a buffer of set size.
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:46 $
+ */
+ 
+ #endif
diff -urdN ../Tekkotsu_2.3/IPC/LockScope.h ./IPC/LockScope.h
--- ../Tekkotsu_2.3/IPC/LockScope.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/LockScope.h	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,34 @@
+//-*-c++-*-
+#ifndef INCLUDED_LockScope_h_
+#define INCLUDED_LockScope_h_
+
+#include "MutexLock.h"
+#include "ProcessID.h"
+
+//! Locks a MutexLock until the LockScope goes out of scope
+/*! This can help prevent forgetting to do it if you function has multiple return points */
+template<unsigned int num_doors>
+class LockScope {
+public:
+	//!constructor, locks @a lock with the current process's id (ProcessID::getID())
+	LockScope(MutexLock<num_doors>& lock) : l(lock) {l.lock(ProcessID::getID());}
+	//!constructor, locks @a lock with @a id
+	LockScope(MutexLock<num_doors>& lock, int id) : l(lock) {l.lock(id);}
+	//!destructor, releases lock received in constructor
+	~LockScope() { l.unlock(); }
+protected:
+	MutexLock<num_doors>& l; //!< the lock
+};
+
+/*! @file
+ * @brief Defines LockScope, which locks a MutexLock until the LockScope goes out of scope
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:46 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/IPC/MessageQueue.h ./IPC/MessageQueue.h
--- ../Tekkotsu_2.3/IPC/MessageQueue.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/MessageQueue.h	Thu Aug  4 17:32:16 2005
@@ -0,0 +1,313 @@
+//-*-c++-*-
+#ifndef INCLUDED_MessageQueue_h_
+#define INCLUDED_MessageQueue_h_
+
+#ifdef PLATFORM_APERIOS
+#  warning MessageQueue is not Aperios compatable
+#else
+
+#include "ListMemBuf.h"
+#include "RCRegion.h"
+#include "LockScope.h"
+#include <exception>
+
+//! Defines the interface for sending new shared memory regions between processes
+/*! This base class holds all of the template-independent code to allow general
+ *  operations on MessageQueues.  The templated version of MessageQueue provides
+ *  concrete implementation, which is what you would instantiate.
+ *  
+ *  Each message entails its own shared memory region, as compared to
+ *  SharedQueue, where a single large buffer is maintained, and all messages are
+ *  copied into the common buffer.  This class is better for large regions since
+ *  it can avoid copying data around. */
+class MessageQueueBase {
+public:
+
+	//!constructor
+	MessageQueueBase()
+		: lock(), overflowPolicy(THROW_BAD_ALLOC), isClosed(false), reportDroppings(false), numMessages(0),
+			numReceivers(0), messagesRead()
+	{}
+	//!destructor
+	virtual ~MessageQueueBase() {}
+	
+	
+	//!An interface to allow you to receive callbacks when a message has been read from a MessageQueue, subscribed via an external calss which is monitoring the queue's MessageQueueBase::pollStatus() (e.g. LoadFileThread)
+	class StatusListener {
+	public:
+		//! destructor -- does nothing
+		virtual ~StatusListener() {}
+		
+		//! Called after a message has been read by all receivers, and thus has been removed from the queue
+		/*! In order to allow this to happen, a thread must repeatedly call
+		 *  MessageQueueBase::pollStatus() in order to check if other processes have
+		 *  read their messages since the last pollStatus call.
+		 *
+		 *  Don't assume that because you receive this callback there is space in
+		 *  the queue -- an earlier listener may have already added a message, or
+		 *  the queue might have been already waiting to send a message if
+		 *  #overflowPolicy is #WAIT
+		 *
+		 *  @param which The MessageQueueBase which has had message(s) read
+		 *  @param howmany The number of message which have been cleared */
+		virtual void messagesRead(MessageQueueBase& which, unsigned int howmany)=0;
+	};
+
+	//! Checks to see how many messages have been processed (read by all receivers and removed from queue) since the last call to pollStatus()
+	virtual unsigned int pollStatus() {
+		AutoLock autolock(lock);
+		unsigned int read=messagesRead;
+		messagesRead=0;
+		return read;
+	}
+
+	
+	//! The storage type for message entry indicies
+	/*! This index is to be used with accessor functions, but may be recycled for
+	 *  a new message after all receivers have read the previous message.  If you
+	 *  wish to have a unique message identifier, see getMessageSN() */
+	typedef unsigned short index_t;
+	
+	
+	//!< add one to the receiver reference count
+	virtual void addReceiver()=0;
+	//!< remove one from the receiver reference count
+	virtual void removeReceiver()=0;
+	//! return the receiver reference count
+	virtual unsigned int getNumReceivers() const { return numReceivers; }
+
+
+	//! post a message into the queue -- a shared reference is added, the caller retains control current reference
+	/*! Thus, if you are sending a region and do not intend to use it again, call
+	 *  RCRegion::RemoveReference() after sending to free the sender's memory.
+	 *  Otherwise, you can continue to access the region, even as the receiver
+	 *  accesses it as well.  If both sides retain references, you can use the
+	 *  region as a shared memory area for future communication.  (beware of race
+	 *  conditions!) */
+	virtual void sendMessage(RCRegion * rcr)=0;
+	//! request access to a particular message, increments read counter -- do not call more than once per receiver!
+	/*! The message is marked read and will be popped from the queue if all
+	 *  receivers have read the message as well.  The caller inherits a reference
+	 *  to the returned region -- call RemoveReference when you are done with
+	 *  it */
+	virtual RCRegion * readMessage(index_t msg)=0;
+	//! request access to a particular message, does not mark message -- call as often as you like
+	/*! The caller inherits a reference to the returned region -- call
+	 *  RemoveReference when you are done with it */
+	virtual RCRegion * peekMessage(index_t msg)=0;
+	//! increments read counter -- do not call more than once per receiver!
+	virtual void markRead(index_t msg)=0;
+	//! do not allow any new messages to be posted
+	virtual void close() { AutoLock autolock(lock); isClosed=true; }
+
+	virtual void setReportDroppings(bool report) { reportDroppings=report; }
+	virtual bool getReportDroppings() const { return reportDroppings; }
+	
+	
+	//! Each message gets a unique, monotonically increasing serial number; this function returns that number (#serialNumber)
+	virtual unsigned int getMessageSN(index_t msg)=0;
+	
+	
+	//! a typedef to make it easier to obtain a lock on the queue for the extent of a scope
+	typedef LockScope<ProcessID::NumProcesses> AutoLock;
+	//! returns a lock on the queue for the scope of the returned storage
+	AutoLock getLock() const { return AutoLock(lock); }
+
+	
+	virtual index_t oldest() const=0;          //!< return oldest message still in the queue (may or may not have been read by this process)
+	virtual index_t newer(index_t it) const=0; //!< return the next message in the queue (may or may not have been read by this process)
+	virtual index_t older(index_t it) const=0; //!< return the previous message in the queue (may or may not have been read by this process)
+	virtual index_t newest() const=0;          //!< return most recent message added to the queue (may or may not have been read by this process)
+	virtual bool isEnd(index_t it) const=0;    //!< returns true if @a it is the one-past-the-end of the queue
+	
+	//! an enumerations of policies for dealing with overflow, pass to setOverflowPolicy()
+	enum OverflowPolicy_t {
+		DROP_OLDEST,     //!< the oldest unread message is dropped
+		DROP_NEWEST,     //!< the most recently added message is dropped (i.e. the overflowing message is ignored)
+		WAIT,            //!< the adding process/thread polls until space is available
+		THROW_BAD_ALLOC  //!< throw a std::bad_alloc exception (falls through to abort() if you don't catch it)
+	};
+	//! allows you to pick how to handle running out of space in the queue, see OverflowPolicy_t
+	void setOverflowPolicy(OverflowPolicy_t op) { overflowPolicy=op; }
+	//! returns the current overflow policy, see OverflowPolicy_t
+	OverflowPolicy_t getOverflowPolicy() const { return overflowPolicy; }
+	
+protected:
+	//! data storage needed for each message
+	struct entry {
+		entry() : id(), sn(), numRead(0) {} //!< constructor
+		entry(unsigned int serialNumber, RCRegion* r)
+			: id(r->ID()), sn(serialNumber), numRead(0) {} //!< constructor, pass message info
+		RCRegion::Identifier id; //! the identifier for the shared memory region so that other regions can attach it
+		unsigned int sn; //!< serial number for this message (not the same as its index in the queue -- indicies are reused, this id is unique to this message
+		unsigned int numRead; //!< a count of the number of receivers which have read this message
+	};
+	mutable MutexLock<ProcessID::NumProcesses> lock; //!< a lock to grant serial access to the queue
+	OverflowPolicy_t overflowPolicy; //!< the choice of how to handle message overflow -- see OverflowPolicy_t
+	bool isClosed; //!< if true, new messages will be rejected
+	bool reportDroppings; //!< if true, output will be sent on cerr when overflow occurs
+	unsigned int numMessages; //!< number of messages which have been sent (serial number of next message)
+	unsigned int numReceivers; //!< how many receivers to expect
+	unsigned int messagesRead; //!< number of messages which have been read and removed from queue since last call to pollStatus()
+};
+
+//! An implementation of MessageQueueBase, which provides mechanisms for sending shared memory regions between processes
+/*! @see MessageQueueBase */
+template<unsigned int MAX_UNREAD>
+class MessageQueue : public MessageQueueBase {
+public:
+	//! total number of messages which can be backed up in the queue
+	static const unsigned int CAPACITY=MAX_UNREAD;
+	
+	//! constructor
+	MessageQueue() : MessageQueueBase(), mq() {}
+	
+	virtual ~MessageQueue() {
+		//lock shouldn't be necessary -- refcount should ensure the containing
+		//region isn't deleted until only one process has access anyway
+		//AutoLock autolock(lock);
+		while(!mq.empty()) {
+			RCRegion * rcr = RCRegion::attach(mq.front().id);
+			rcr->RemoveSharedReference();
+			rcr->RemoveReference();
+			mq.pop_front();
+		}
+	}
+	
+	virtual void addReceiver() {
+		AutoLock autolock(lock);
+		numReceivers++;
+	}
+	
+	virtual void removeReceiver() {
+		AutoLock autolock(lock);
+		numReceivers--;
+		for(index_t it=mq.begin(); it!=mq.end(); it=mq.next(it)) {
+			if(mq[it].numRead==numReceivers) {
+				//all *remaining* processes have gotten a look, remove the neutral MessageQueue reference
+				RCRegion * rcr = RCRegion::attach(mq[it].id);
+				rcr->RemoveSharedReference();
+				rcr->RemoveReference();
+				it=mq.prev(it);
+				mq.erase(mq.next(it));
+				messagesRead++;
+			}
+		}
+	}
+	
+	virtual void sendMessage(RCRegion * rcr) {
+		AutoLock autolock(lock);
+		if(numReceivers==0) {
+			//if(reportDroppings)
+			//std::cerr << "Warning: MessageQueue dropping " << rcr->ID().key << " because there are no receivers" << std::endl;
+			return;
+		}
+		if(isClosed) {
+			if(reportDroppings)
+				std::cerr << "Warning: MessageQueue dropping " << rcr->ID().key << " because queue is closed" << std::endl;
+			return;
+		}
+		rcr->AddSharedReference();
+		if(mq.size()==mq.getMaxCapacity()) {
+			switch(overflowPolicy) {
+				case DROP_OLDEST: {
+					if(reportDroppings)
+						std::cerr << "WARNING: MessageQueue full, dropping oldest unread message (" << mq.front().id.key << ")" << std::endl;
+					RCRegion * eldest = RCRegion::attach(mq.front().id);
+					eldest->RemoveSharedReference();
+					mq.pop_front();
+					eldest->RemoveReference();
+				} break;
+				case DROP_NEWEST:
+					if(reportDroppings)
+						std::cerr << "WARNING: MessageQueue full, dropping newest unread message (" << rcr->ID().key << ")" << std::endl;
+					rcr->RemoveSharedReference();
+					return;
+				case WAIT:
+					if(reportDroppings)
+						std::cerr << "WARNING: MessageQueue full, waiting for readers to catch up" << std::endl;
+					while(mq.size()==mq.getMaxCapacity()) {
+						//have to release locks so readers can get access
+						unsigned int ll=lock.get_lock_level();
+						lock.releaseAll();
+						usleep(MutexLockBase::usleep_granularity*15);
+						for(unsigned int i=0; i<ll; i++)
+							lock.lock(ProcessID::getID());
+					}
+					break;
+				case THROW_BAD_ALLOC:
+					if(reportDroppings)
+						std::cerr << "WARNING: MessageQueue full, throwing bad_alloc exception" << std::endl;
+					rcr->RemoveSharedReference();
+					throw std::bad_alloc();
+					break;
+			}
+		}
+		if(mq.push_back(entry(numMessages++,rcr))==mq.end()) {
+			//our overflow policy should've prevented this
+			std::cerr << "ERROR: MessageQueue unable to add message; buggy overflow policy?" << std::endl;
+			exit(EXIT_FAILURE);
+		}
+	}
+	
+	virtual RCRegion * readMessage(index_t msg) {
+		AutoLock autolock(lock);
+		RCRegion * rcr = RCRegion::attach(mq[msg].id);
+		mq[msg].numRead++;
+		if(mq[msg].numRead==numReceivers) {
+			//all processes have gotten a look, remove the neutral MessageQueue reference
+			rcr->RemoveSharedReference();
+			mq.erase(msg);
+			messagesRead++;
+		}
+		return rcr;
+	}
+	
+	virtual RCRegion * peekMessage(index_t msg) {
+		//AutoLock autolock(lock); //I don't think a lock is necessary here
+		return RCRegion::attach(mq[msg].id);
+	}
+	
+	virtual void markRead(index_t msg) {
+		AutoLock autolock(lock);
+		mq[msg].numRead++;
+		if(mq[msg].numRead==numReceivers) {
+			//all processes have gotten a look, remove the neutral MessageQueue reference
+			RCRegion * rcr = RCRegion::attach(mq[msg].id);
+			rcr->RemoveSharedReference();
+			rcr->RemoveReference();
+			mq.erase(msg);
+			messagesRead++;
+		}
+	}
+
+	virtual unsigned int getMessageSN(index_t msg) { /*AutoLock autolock(lock);*/ return mq[msg].sn; }
+	
+	virtual index_t oldest() const { AutoLock autolock(lock); return mq.begin(); }
+	virtual index_t newer(index_t it) const { AutoLock autolock(lock); return mq.next(it); }
+	virtual index_t older(index_t it) const { AutoLock autolock(lock); return mq.prev(it); }
+	virtual index_t newest() const { AutoLock autolock(lock); return mq.prev(mq.end()); }
+	virtual bool isEnd(index_t it) const { AutoLock autolock(lock); return it==mq.end() || it>=mq_t::MAX_ENTRIES; }
+	
+protected:
+	//! shorthand for the type of data storage of message entries
+	typedef ListMemBuf<entry,MAX_UNREAD,index_t> mq_t;
+	
+	//! the data storage of message entries
+	mq_t mq;
+};
+
+/*! @file
+ * @brief Defines MessageQueue, which provides mechanisms for sending shared memory regions between processes
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.12 $
+ * $State: Exp $
+ * $Date: 2005/08/04 21:32:16 $
+ */
+
+#endif //APERIOS check
+
+#endif //INCLUDED
diff -urdN ../Tekkotsu_2.3/IPC/MessageReceiver.cc ./IPC/MessageReceiver.cc
--- ../Tekkotsu_2.3/IPC/MessageReceiver.cc	Wed Dec 31 19:00:00 1969
+++ ./IPC/MessageReceiver.cc	Thu Jul 28 14:22:16 2005
@@ -0,0 +1,136 @@
+#ifndef PLATFORM_APERIOS
+
+#include "MessageReceiver.h"
+//#include "local/sim/Process.h"
+//#include <iostream>
+//using namespace std;
+
+MessageReceiver::MessageReceiver(MessageQueueBase& mq, bool (*callback) (RCRegion*)/*=NULL*/, bool startThread/*=true*/)
+: Thread(), queue(mq), nextMessage(0), lastProcessedMessage(-1U), process(callback), sleeptime(1000), curit((index_t)-1)
+{
+	queue.addReceiver();
+	if(startThread)
+		start();
+}
+
+MessageReceiver::~MessageReceiver() {
+	if(isRunning())
+		queue.removeReceiver();
+}
+
+RCRegion * MessageReceiver::peekNextMessage() {
+	MessageQueueBase::AutoLock autolock(queue.getLock());
+	if(queue.isEnd(curit)) {
+		index_t it=queue.newest(); //start with the newest
+		while(!queue.isEnd(it) && queue.getMessageSN(it)>=nextMessage)
+			it=queue.older(it); //scan back to the first already read by this process
+		curit=it=queue.newer(it); //go to the following one (first unread)
+	}
+	if(queue.isEnd(curit))
+		return NULL;
+	return queue.peekMessage(curit);
+}
+
+RCRegion * MessageReceiver::getNextMessage() {
+	MessageQueueBase::AutoLock autolock(queue.getLock());
+	index_t it; //will be set to the current message to return; curit will be set to the following message
+	if(queue.isEnd(curit)) {
+		it=queue.newest(); //start with the newest
+		while(!queue.isEnd(it) && queue.getMessageSN(it)>=nextMessage)
+			it=queue.older(it); //scan back to the first already read by this process
+		curit=it=queue.newer(it); //go to the following one (first unread)
+	} else {
+		it=curit;
+		while(!queue.isEnd(it) && queue.getMessageSN(it)<nextMessage)
+			it=queue.newer(it); //scan forward to next message not read by this process
+		curit=it;
+	}
+	if(queue.isEnd(it))
+		return NULL;
+	nextMessage=queue.getMessageSN(it)+1;
+	curit=queue.newer(it); //next time, start on (or peek at) the one after this
+	return queue.readMessage(it);
+}
+
+void MessageReceiver::markRead() {
+	if(queue.isEnd(curit))
+		return;
+	nextMessage=queue.getMessageSN(curit)+1;
+	queue.markRead(curit);
+	curit=queue.newer(curit); //next time, start on (or peek at) the one after this
+}
+
+void MessageReceiver::waitNextMessage() {
+	for(;;) {
+		RCRegion * ans=peekNextMessage();
+		if(ans!=NULL)
+			return;
+		usleep(sleeptime);
+	}
+}
+
+unsigned int MessageReceiver::runloop() {
+	RCRegion * msg;
+	//cout << Process::getName() << " runloop" << endl;
+	while((msg=peekNextMessage())!=NULL) {
+		//cout << Process::getName() << " got " << msg->ID().key << ' ' << lastProcessedMessage << ' ' << queue.getMessageSN(curit) << ' ' << curit << endl;
+		bool used=false;
+		if(lastProcessedMessage!=queue.getMessageSN(curit)) {
+			//cout << Process::getName() << " process" << endl;
+			lastProcessedMessage=queue.getMessageSN(curit);
+			used=process(msg);
+			if(used)
+				markRead(); // message was consumed, mark it read so next peek will get the next
+			//cout << used << ' ' << curit;
+			//if(!queue.isEnd(curit))
+			//cout << lastProcessedMessage << ' ' << queue.getMessageSN(curit);
+			//cout << endl;
+		}
+		msg->RemoveReference();
+		if(!used) //have to break out of the loop to sleep & check interrupts -- otherwise we'll busyloop peeking at the same message
+			break;
+	}
+	return sleeptime;
+}
+
+void MessageReceiver::finish() {
+	if(!isRunning())
+		return;
+	stop();
+	join();
+	RCRegion * msg;
+	//cout << Process::getName() << " finish" << endl;
+	while((msg=peekNextMessage())!=NULL) {
+		//cout << Process::getName() << " got " << msg->ID().key << ' ' << lastProcessedMessage << ' ' << queue.getMessageSN(curit) << ' ' << curit << endl;
+		bool used=false;
+		if(lastProcessedMessage!=queue.getMessageSN(curit)) {
+			//cout << Process::getName() << " process" << endl;
+			lastProcessedMessage=queue.getMessageSN(curit);
+			used=process(msg);
+			if(used)
+				markRead(); // message was consumed, mark it read so next peek will get the next
+			//cout << used << ' ' << curit;
+			//if(!queue.isEnd(curit))
+			//cout << lastProcessedMessage << ' ' << queue.getMessageSN(curit);
+			//cout << endl;
+		}
+		msg->RemoveReference();
+		if(!used) // if the consumer can't process immediately, we're not waiting around -- drop the rest
+			break;
+	}
+	queue.removeReceiver();
+}
+
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
+ * $State: Exp $
+ * $Date: 2005/07/28 18:22:16 $
+ */
+
+#endif //PLATFORM_APERIOS check (aperios doesn't support pthreads...)
diff -urdN ../Tekkotsu_2.3/IPC/MessageReceiver.h ./IPC/MessageReceiver.h
--- ../Tekkotsu_2.3/IPC/MessageReceiver.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/MessageReceiver.h	Thu Jul 28 14:22:16 2005
@@ -0,0 +1,55 @@
+//-*-c++-*-
+#ifndef INCLUDED_MessageReceiver_h_
+#define INCLUDED_MessageReceiver_h_
+
+#ifdef PLATFORM_APERIOS
+#  warning MessageReceiver is not Aperios compatable
+#else
+
+#include "MessageQueue.h"
+#include "Thread.h"
+
+//! description of MessageReceiver
+class MessageReceiver : public Thread {
+public:
+	explicit MessageReceiver(MessageQueueBase& mq, bool (*callback) (RCRegion*)=NULL, bool startThread=true);
+	~MessageReceiver();
+	
+	RCRegion * peekNextMessage();
+	RCRegion * getNextMessage();
+	void markRead();
+	void waitNextMessage();
+	unsigned int runloop();
+	void finish();
+	
+	void setCallback(bool (*callback) (RCRegion*)) { process=callback; }
+	
+protected:
+	typedef MessageQueueBase::index_t index_t;
+	MessageQueueBase& queue;
+	unsigned int nextMessage;
+	unsigned int lastProcessedMessage;
+	bool (*process) (RCRegion*);
+	unsigned int sleeptime;
+	index_t curit;
+	
+private:
+	MessageReceiver(const MessageReceiver& r); //!< don't call
+	MessageReceiver& operator=(const MessageReceiver& r); //!< don't call
+};
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
+ * $State: Exp $
+ * $Date: 2005/07/28 18:22:16 $
+ */
+
+#endif //Aperios check
+
+#endif //INCLUDED
+
diff -urdN ../Tekkotsu_2.3/IPC/MutexLock.cc ./IPC/MutexLock.cc
--- ../Tekkotsu_2.3/IPC/MutexLock.cc	Wed Dec 31 19:00:00 1969
+++ ./IPC/MutexLock.cc	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,19 @@
+#include "MutexLock.h"
+
+unsigned int MutexLockBase::usleep_granularity=5000;
+
+#ifndef PLATFORM_APERIOS
+SemaphoreManager MutexLockBase::preallocated;
+SemaphoreManager* MutexLockBase::semgr=&preallocated;
+#endif
+
+/*! @file 
+* @brief Defines MutexLock, a software only mutual exclusion lock.
+* @author ejt (Creator), Edward A. Lycklama, Vassos Hadzilacos (paper from which this was based)
+*
+* $Author: ejt $
+* $Name: tekkotsu-2_4 $
+* $Revision: 1.2 $
+* $State: Exp $
+* $Date: 2005/06/01 05:47:46 $
+*/
diff -urdN ../Tekkotsu_2.3/IPC/MutexLock.h ./IPC/MutexLock.h
--- ../Tekkotsu_2.3/IPC/MutexLock.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/MutexLock.h	Mon Jul 25 23:22:02 2005
@@ -0,0 +1,500 @@
+//-*-c++-*-
+#ifndef __MUTEX_LOCK_ET__
+#define __MUTEX_LOCK_ET__
+
+#include <iostream>
+#ifndef PLATFORM_APERIOS
+#  include <unistd.h>
+#  include "SemaphoreManager.h"
+#else
+#  include <exception>
+#endif
+
+// If you want to use the same software-only lock on both
+// PLATFORM_LOCAL and Aperios, then uncomment this next line:
+//#define MUTEX_LOCK_ET_USE_SOFTWARE_ONLY
+
+// However, that's probably only of use if you want to debug a problem with the lock itself
+
+
+
+//! The main purpose of this base class is actually to allow setting of usleep_granularity across all locks
+/*! It would be nice if we just put functions in here so we could
+ *  reference locks without regard to the number of doors, but
+ *  then all processes which use the lock would have to have been
+ *  created via fork to handle virtual calls properly, and I don't
+ *  want to put that overhead on the otherwise lightweight SoundPlay
+ *  process under Aperios. */
+class MutexLockBase {
+public:
+	virtual ~MutexLockBase() {} //!< basic destructor
+	
+	static const unsigned int NO_OWNER=-1U; //!< marks as unlocked
+	static unsigned int usleep_granularity; //!< the estimated cost in microseconds of usleep call itself -- value passed to usleep will be 10 times this (only used by software lock implementation on non-Aperios)
+
+	//This section is only needed for the non-software-only locks, using the SemaphoreManager
+#ifndef PLATFORM_APERIOS
+	class no_more_semaphores : public std::exception {
+	public:
+		no_more_semaphores() throw() : std::exception() {}
+		virtual const char* what() const throw() { return "SemaphoreManager::getSemaphore() returned invalid()"; }
+	};
+	
+	//! sets the SemaphoreManager which will hand out semaphores for any and all locks
+	/*! see #preallocated for an explanation of why this function does what it does */
+	static void setSemaphoreManager(SemaphoreManager* mgr) {
+		if(mgr==NULL) {
+			preallocated=*semgr;
+			semgr=&preallocated;
+		} else {
+			*mgr=*semgr;
+			semgr=mgr;
+		}
+	}
+	static SemaphoreManager* getSemaphoreManager() {
+		return semgr;
+	}
+	static void aboutToFork() {
+		preallocated.aboutToFork();
+	}
+protected:
+	//! the global semaphore manager object for all locks, may point to preallocated during process initialization or destruction
+	static SemaphoreManager* semgr;
+	
+	//! if a semaphore needs to be reserved, and #semgr is NULL, use #preallocated's current value and increment it
+	/*! Here's the conundrum: each shared region needs a lock, each
+	 *  lock needs an ID from the semaphore manager, and the semaphore
+	 *  manager needs to be in a shared region to coordinate handing out
+	 *  IDs.  So this is resolved by having the locks check #semgr to see
+	 *  if it is initialized yet, and use this if it is not.
+	 *  Then, when the SemaphoreManager is assigned, we will copy over
+	 *  preallocated IDs from here
+	 *
+	 *  For reference, only MutexLock needs to worry about this because
+	 *  it's the only thing that's going to need an ID before the
+	 *  manager is created.*/
+	static SemaphoreManager preallocated;
+#endif
+};
+
+
+
+#if !defined(PLATFORM_APERIOS) && !defined(MUTEX_LOCK_ET_USE_SOFTWARE_ONLY)
+#include "SemaphoreManager.h"
+
+//! Implements a mutual exclusion lock using semaphores (SYSV style through SemaphoreManager)
+/*! Use this to prevent more than one process from accessing a data structure
+ *  at the same time (which often leads to unpredictable and unexpected results)
+ *
+ *  The template parameter specifies the maximum number of different processes
+ *  which need to be protected.  This needs to be allocated ahead of time, as
+ *  there doesn't seem to be a way to dynamically scale as needed without
+ *  risking possible errors if two processes are both trying to set up at the
+ *  same time.  Also, by using a template parameter, all data structures are
+ *  contained within the class's memory allocation, so no pointers are involved.
+ *
+ *  Locks in this class can be recursive or non-recursive, depending
+ *  whether you call releaseAll() or unlock().  If you lock 5 times, then
+ *  you need to call unlock() 5 times as well before it will be
+ *  unlocked.  However, if you lock 5 times, just one call to releaseAll()
+ *  will undo all 5 levels of locking.
+ *
+ *  Just remember, unlock() releases one level.  But releaseAll() completely unlocks.
+ *
+ *  Note that there is no check that the process doing the unlocking is the one
+ *  that actually has the lock.  Be careful about this.
+ *
+ *  @warning Doing mutual exclusion in software is tricky business, be careful about any
+ *  modifications you make!
+ */
+template<unsigned int num_doors>
+class MutexLock : public MutexLockBase {
+public:
+	//! constructor, gets a new semaphore from the semaphore manager
+	MutexLock()
+		: sem(semgr->getSemaphore()), owner_index(NO_OWNER)
+	{
+		if(sem==semgr->invalid())
+			throw no_more_semaphores();
+		semgr->setValue(sem,0);
+	}
+	
+	//! constructor, use this if you already have a semaphore id you want to use from semaphore manager
+	MutexLock(SemaphoreManager::semid_t semid)
+		: sem(semid), owner_index(NO_OWNER)
+	{
+		if(sem==semgr->invalid())
+			throw no_more_semaphores();
+		semgr->setValue(sem,0);
+	}
+	
+	//! destructor, releases semaphore back to semaphore manager
+	~MutexLock() {
+		owner_index=NO_OWNER;
+		if(semgr!=NULL && !semgr->hadFault())
+			semgr->releaseSemaphore(sem);
+		else
+			std::cerr << "Warning: MutexLock leaked semaphore " << sem << " because SemaphoreManager is NULL" << std::endl;
+	}
+	
+	//! blocks until lock is achieved.  This is done efficiently using a SysV style semaphore
+	/*! You should pass some process-specific ID number as the input - just
+	 *  make sure no other process will be using the same value. */
+	void lock(int id) {
+		if(owner_index!=static_cast<unsigned>(id)) {
+			//have to wait and then claim lock
+			if(semgr!=NULL && !semgr->hadFault())
+				semgr->testZero_add(sem,1);
+			else
+				std::cerr << "Warning: MutexLock assuming lock of " << sem << " because SemaphoreManager is NULL" << std::endl;
+			owner_index=id;
+		} else {
+			//we already have lock, add one to its lock level
+			if(semgr!=NULL && !semgr->hadFault())
+				semgr->raise(sem,1);
+			else
+				std::cerr << "Warning: MutexLock assuming lock of " << sem << " because SemaphoreManager is NULL" << std::endl;
+		}
+	}
+	
+	//! attempts to get a lock, returns true if it succeeds
+	/*! You should pass some process-specific ID number as the input - just
+	 *  make sure no other process will be using the same value.*/
+	bool try_lock(int id) {
+		if(semgr==NULL || semgr->hadFault()) {
+			std::cerr << "Warning: MutexLock assuming try_lock success of " << sem << " because SemaphoreManager is NULL" << std::endl;
+			owner_index=id;
+			return true;
+		}
+		if(owner()==id) {
+			//we already have lock, add one to its lock level
+			semgr->raise(sem,1);
+			return true;
+		} else {
+			if(semgr->testZero_add(sem,1,false)) {
+				owner_index=id;
+				return true;
+			} else
+				return false;
+		}
+	}
+	
+	//! releases one recursive lock-level from whoever has the current lock
+	inline void unlock() {
+		if(semgr==NULL || semgr->hadFault()) {
+			std::cerr << "Warning: MutexLock assuming unlock of " << sem << " from " << owner_index << " because SemaphoreManager is NULL" << std::endl;
+			owner_index=NO_OWNER;
+			return;
+		}
+		if(semgr->getValue(sem)<=0) {
+			std::cerr << "Warning: MutexLock::unlock caused underflow" << std::endl;
+			owner_index=NO_OWNER;
+			return;
+		}
+		if(semgr->getValue(sem)==1)
+			owner_index=NO_OWNER;
+		if(!semgr->lower(sem,1,false))
+			std::cerr << "Warning: MutexLock::unlock caused strange underflow" << std::endl;
+	}
+	
+	//! completely unlocks, regardless of how many times a recursive lock has been obtained
+	void releaseAll() {
+		owner_index=NO_OWNER;
+		if(semgr==NULL || semgr->hadFault()) {
+			std::cerr << "Warning: MutexLock assuming releaseAll of " << sem << " because SemaphoreManager is NULL" << std::endl;
+			return;
+		}
+		semgr->setValue(sem,0);
+	}
+	
+	//! returns the lockcount
+	unsigned int get_lock_level() const {
+		if(semgr==NULL || semgr->hadFault())
+			return (owner_index==NO_OWNER) ? 0 : 1;
+		else
+			return semgr->getValue(sem);
+	}
+	
+	//! returns the current owner's id
+	inline int owner() { return owner_index; }
+	
+protected:
+	SemaphoreManager::semid_t sem; //!< the SysV semaphore number
+	unsigned int owner_index; //!< holds the tekkotsu process id of the current lock owner
+};
+
+
+
+
+#else //SOFTWARE ONLY mutual exclusion, used on Aperios, or if MUTEX_LOCK_ET_USE_SOFTWARE_ONLY is defined
+
+
+
+
+//#define MUTEX_LOCK_ET_USE_SPINCOUNT
+
+//! A software only mutual exclusion lock. (does not depend on processor or OS support)
+/*! Use this to prevent more than one process from accessing a data structure
+ *  at the same time (which often leads to unpredictable and unexpected results)
+ *
+ *  The template parameter specifies the maximum number of different processes
+ *  which need to be protected.  This needs to be allocated ahead of time, as
+ *  there doesn't seem to be a way to dynamically scale as needed without
+ *  risking possible errors if two processes are both trying to set up at the
+ *  same time.  Also, by using a template parameter, all data structures are
+ *  contained within the class's memory allocation, so no pointers are involved.
+ *
+ *  Locks in this class can be recursive or non-recursive, depending
+ *  whether you call releaseAll() or unlock().  If you lock 5 times, then
+ *  you need to call unlock() 5 times as well before it will be
+ *  unlocked.  However, if you lock 5 times, just one call to releaseAll()
+ *  will undo all 5 levels of locking.
+ *
+ *  Just remember, unlock() releases one level.  But releaseAll() completely unlocks.
+ *
+ *  Note that there is no check that the process doing the unlocking is the one
+ *  that actually has the lock.  Be careful about this.
+ *
+ *  @warning Doing mutual exclusion in software is tricky business, be careful about any
+ *  modifications you make!
+ *
+ * Implements a first-come-first-served Mutex as laid out on page 11 of: \n
+ * "A First Come First Served Mutal Exclusion Algorithm with Small Communication Variables" \n
+ * Edward A. Lycklama, Vassos Hadzilacos - Aug. 1991
+*/
+template<unsigned int num_doors>
+class MutexLock : public MutexLockBase {
+ public:
+	//! constructor, just calls the init() function.
+	MutexLock() : doors_used(0), owner_index(NO_OWNER), lockcount(0) { init();	}
+
+	//! blocks (by busy looping on do_try_lock()) until a lock is achieved
+	/*! You should pass some process-specific ID number as the input - just
+	 *  make sure no other process will be using the same value.
+	 *  @todo - I'd like to not use a loop here */
+	void lock(int id);
+
+	//! attempts to get a lock, returns true if it succeeds
+	/*! You should pass some process-specific ID number as the input - just
+	 *  make sure no other process will be using the same value.*/
+	bool try_lock(int id);
+
+	//! releases one recursive lock-level from whoever has the current lock
+	inline void unlock();
+
+	//! completely unlocks, regardless of how many times a recursive lock has been obtained
+	void releaseAll() { lockcount=1; unlock(); }
+	
+	//! returns the lockcount
+	unsigned int get_lock_level() const { return lockcount;	}
+
+	//! returns the current owner's id
+	inline int owner() { return owner_index==NO_OWNER ? NO_OWNER : doors[owner_index].id; }
+
+	//! allows you to reset one of the possible owners, so another process can take its place.  This is not tested
+	void forget(int id);
+
+#ifdef MUTEX_LOCK_ET_USE_SPINCOUNT
+	inline unsigned int getSpincount() { return spincount; } //!< returns the number of times the spin() function has been called
+	inline unsigned int resetSpincount() { spincount=0; } //!< resets the counter of the number of times the spin() function has been called
+#endif
+	
+ protected:
+	//! Does the work of trying to get a lock
+	/*! Pass @c true for @a block if you want it to use FCFS blocking
+	 *  instead of just returning right away if another process has the lock */
+	bool do_try_lock(unsigned int index, bool block);
+
+	//! returns the internal index mapping to the id number supplied by the process
+	unsigned int lookup(int id); //may create a new entry
+
+#ifdef MUTEX_LOCK_ET_USE_SPINCOUNT
+	volatile unsigned int spincount; //!< handy to track how much time we're wasting
+	void init() { spincount=0; }//memset((void*)doors,0,sizeof(doors)); } //!< just resets spincount
+	inline void spin() {
+		spincount++;
+#ifndef PLATFORM_APERIOS
+		usleep(usleep_granularity*10); //this is a carefully chosen value intended to solve all the world's problems (not)
+#endif
+	} //!< if you find a way to sleep for a few microseconds instead of busy waiting, put it here
+#else
+	void init() { } //!< Doesn't do anything if you have the MUTEX_LOCK_ET_USE_SPINCOUNT undef'ed.  Used to do a memset, but that was causing problems....
+	//memset((void*)doors,0,sizeof(doors)); } 
+	inline void spin() {
+#ifndef PLATFORM_APERIOS
+		usleep(usleep_granularity*10); //this is a carefully chosen value intended to solve all the world's problems (not)
+#endif
+	} //!< If you find a way to sleep for a few microseconds instead of busy waiting, put it here
+#endif
+		
+	//! Holds per process shared info, one of these per process
+	struct door_t {
+		door_t() : id(NO_OWNER), FCFS_in_use(false), BL_ready(false), BL_in_use(false), turn('\0'), next_turn_bit('\0') {} //!< constructor
+		//door_t(int i) : id(i), FCFS_in_use(false), BL_ready(false), BL_in_use(false), next_turn_bit('\0') {}
+		int id; //!< process ID this doorway is assigned to
+		volatile bool FCFS_in_use; //!< In FCFS doorway, corresponds to 'c_i'
+		volatile bool BL_ready; //!< Signals past FCFS doorway, ready for BL doorway, corresponds to 'v_i'
+		volatile bool BL_in_use; //!< Burns-Lamport doorway, corresponds to 'x_i'
+		volatile unsigned char turn; //!< clock pulse, initial value doesn't matter
+		unsigned char next_turn_bit; //!< selects which bit of turn will be flipped next
+	};
+
+	door_t doors[num_doors]; //!< holds all the doors
+	unsigned int doors_used; //!< counts the number of doors used
+	unsigned int owner_index; //!< holds the door index of the current lock owner
+	unsigned int lockcount; //!< the depth of the lock, 0 when unlocked
+};
+
+
+template<unsigned int num_doors>
+void
+MutexLock<num_doors>::lock(int id) {
+	if(owner()!=id)
+		if(!do_try_lock(lookup(id),true)) {
+			//spin(); //note the block argument above -- should never spin if that is actually working
+			std::cout << "Warning: lock() failed to achieve lock" << std::endl;
+		}
+	lockcount++;
+}
+
+
+template<unsigned int num_doors>
+bool
+MutexLock<num_doors>::try_lock(int id) {
+	if(owner()==id) {
+		lockcount++;
+		return true;
+	} else {
+		if(do_try_lock(lookup(id),false)) {
+			lockcount++;
+			return true;
+		} else
+			return false;
+	}
+}
+
+
+template<unsigned int num_doors>
+void
+MutexLock<num_doors>::unlock() {
+	if(lockcount==0)
+		std::cerr << "Warning: MutexLock::unlock caused underflow" << std::endl;
+	else if(--lockcount==0)
+		if(owner_index!=NO_OWNER) {
+			unsigned int tmp = owner_index;
+			owner_index=NO_OWNER;
+			doors[tmp].BL_in_use=false;
+			doors[tmp].BL_ready=false;
+			// *** Lock has been released *** //
+		}
+}
+
+
+//! If you define this to do something more interesting, can use it to see what's going on in the locking process
+#define mutexdebugout(i,c) {}
+//#define mutexdebugout(i,c) { std::cout << ((char)(i==0?c:((i==1?'M':'a')+(c-'A')))) << std::flush; }
+
+
+template<unsigned int num_doors>
+bool
+MutexLock<num_doors>::do_try_lock(unsigned int i, bool block) {
+	if(i==NO_OWNER) {
+		std::cerr << "WARNING: new process attempted to lock beyond num_doors ("<<num_doors<<")" << std::endl;
+		return false;
+	}
+	unsigned char S[num_doors]; // a local copy of everyone's doors
+	// *** Entering FCFS doorway *** //
+//	pprintf(TextOutputStream,"**%d**\n",i);
+mutexdebugout(i,'A');
+	doors[i].FCFS_in_use=true;
+	for(unsigned int j=0; j<num_doors; j++)
+		S[j]=doors[j].turn;
+	doors[i].next_turn_bit=1-doors[i].next_turn_bit;
+	doors[i].turn^=(1<<doors[i].next_turn_bit);
+	doors[i].BL_ready=true;
+	doors[i].FCFS_in_use=false;
+	// *** Leaving FCFS doorway *** //
+mutexdebugout(i,'B');
+	for(unsigned int j=0; j<num_doors; j++) {
+mutexdebugout(i,'C');
+		while(doors[j].FCFS_in_use || (doors[j].BL_ready && S[j]==doors[j].turn))
+			if(block)
+				spin();
+			else {
+				doors[i].BL_ready=false;
+				return false;
+			}
+mutexdebugout(i,'D');
+	}
+	// *** Entering Burns-Lamport *** //
+mutexdebugout(i,'E');
+	do {
+		doors[i].BL_in_use=true;
+		for(unsigned int t=0; t<i; t++)
+			if(doors[t].BL_in_use) {
+				doors[i].BL_in_use=false;
+				if(!block) {
+					doors[i].BL_ready=false;
+					return false;
+				}
+mutexdebugout(i,'F');
+				while(doors[t].BL_in_use)
+					spin();
+mutexdebugout(i,'G');
+				break;
+			}
+	} while(!doors[i].BL_in_use);
+	for(unsigned int t=i+1; t<num_doors; t++)
+		while(doors[t].BL_in_use)
+			spin();
+	// *** Leaving Burns-Lamport ***//
+	// *** Lock has been given *** //
+mutexdebugout(i,'H');
+	owner_index=i;
+	return true;
+}
+
+
+template<unsigned int num_doors>
+unsigned int
+MutexLock<num_doors>::lookup(int id) {
+	// TODO - this could break if two new processes are adding themselves at the same time
+	//        or an id is being forgotten at the same time
+	//I'm expecting a very small number of processes to be involved
+	//probably not worth overhead of doing something fancy like a sorted array
+	unsigned int i;
+	for(i=0; i<doors_used; i++)
+		if(doors[i].id==id)
+			return i;
+	if(i==num_doors)
+		return NO_OWNER;
+	doors[i].id=id;
+	doors_used++;
+	return i;
+}
+
+
+template<unsigned int num_doors>
+void
+MutexLock<num_doors>::forget(int id) { //not tested thoroughly (or at all?)
+	unsigned int i = lookup(id);
+	do_try_lock(i,true);
+	doors[i].id=doors[--doors_used].id;
+	doors[doors_used].id=NO_OWNER;
+	release();
+}
+
+#endif //MUTEX_LOCK_ET_USE_SOFTWARE_ONLY
+
+/*! @file 
+ * @brief Defines MutexLock, a software only mutual exclusion lock.
+ * @author ejt (Creator), Edward A. Lycklama, Vassos Hadzilacos (paper from which this was based)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
+ * $State: Exp $
+ * $Date: 2005/07/26 03:22:02 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/IPC/ProcessID.cc ./IPC/ProcessID.cc
--- ../Tekkotsu_2.3/IPC/ProcessID.cc	Wed Dec 31 19:00:00 1969
+++ ./IPC/ProcessID.cc	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,15 @@
+#include "ProcessID.h"
+
+ProcessID::ProcessID_t ProcessID::ID=ProcessID::NumProcesses;
+
+/*! @file
+ * @brief Declares the static ProcessID::ID, that's all
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:46 $
+ */
+
diff -urdN ../Tekkotsu_2.3/IPC/ProcessID.h ./IPC/ProcessID.h
--- ../Tekkotsu_2.3/IPC/ProcessID.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/ProcessID.h	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,48 @@
+//-*-c++-*-
+#ifndef INCLUDED_ProcessID_h_
+#define INCLUDED_ProcessID_h_
+
+//! this is a class instead of a namespace so i can limit write access of the ID value to the OObjects
+/*!
+ * Although the ProcessID_t enum specifies the maximum number of processes
+ * in its NumProcesses value, this doesn't have to correspond to the actual
+ * number of active processes.  If you want an element of dynamicism to launch
+ * and/or close processes at runtime, simply increase the NumProcesses to a 
+ * higher value so that space can be allocated for those processes in shared 
+ * memory regions for things like attachment pointers or other per-process
+ * data.
+ *
+ * Not all processes *need* to have a named id, they just need a unique id.
+ */
+class ProcessID {
+public:
+	//! Holds ID number for each process
+	enum ProcessID_t {
+		MainProcess,   //!< MainObj process
+		MotionProcess, //!< MotoObj process
+		SoundProcess,  //!< SoundPlay process
+#ifndef PLATFORM_APERIOS
+		SimulatorProcess, //!< for interaction with OS and managing global environment
+#endif
+		NumProcesses   //!< maximum number of 'friendly' processes -- see class docs
+	};
+	
+	static ProcessID_t getID() { return ID; }  //!< returns process's ID number, or if within a virtual function on a shared object, the process which created it (annoying)
+	static void setID(ProcessID_t id) { ID=id; } //!< sets the ID during init (be careful you know what you're doing if you call this)
+	
+private:
+	static ProcessID_t ID; //!< holds ID number
+};
+
+/*! @file
+ * @brief Defines ProcessID - simple little global for checking which process is currently running, kind of. (see ProcessID::getID() )
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:46 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/IPC/RCRegion.cc ./IPC/RCRegion.cc
--- ../Tekkotsu_2.3/IPC/RCRegion.cc	Wed Dec 31 19:00:00 1969
+++ ./IPC/RCRegion.cc	Thu Jun 23 16:17:54 2005
@@ -0,0 +1,506 @@
+#ifndef PLATFORM_APERIOS
+#include "RCRegion.h"
+#include "LockScope.h"
+#include "Shared/debuget.h"
+#include <unistd.h>
+#include <sstream>
+#include <sys/stat.h>
+#include <errno.h>
+
+#if TEKKOTSU_SHM_STYLE!=SYSV_SHM && TEKKOTSU_SHM_STYLE!=POSIX_SHM
+#  error Unknown TEKKOTSU_SHM_STYLE setting
+#endif
+
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+#  include <sys/ipc.h>
+#  include <sys/shm.h>
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+#  include <sys/mman.h>
+#  include <sys/fcntl.h>
+#  ifdef USE_UNBACKED_SHM
+plist::Primitive<bool> RCRegion::useUniqueMemoryRegions(false);
+#  else
+plist::Primitive<std::string> RCRegion::shmRoot("/tmp/tekkotsu_sim/");
+plist::Primitive<bool> RCRegion::useUniqueMemoryRegions(true);
+#  endif
+pid_t RCRegion::rootPID(::getpid());
+#endif
+
+using namespace std;
+
+typedef LockScope<ProcessID::NumProcesses> AutoLock;
+
+key_t RCRegion::nextKey=1024;
+RCRegion::attachedRegions_t RCRegion::attachedRegions;
+bool RCRegion::isFaultShutdown=false;
+
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+//under SYSV shared memory, the keys are just numbers, and it's just as likely that the conflicted
+//region belongs to an unrelated process as it is that the region is from a previous run -- so we
+//take the safe route and rename our own keys
+RCRegion::ConflictResolutionStrategy RCRegion::conflictStrategy=RCRegion::RENAME;
+
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+//under POSIX shared memory, the keys are names, so we can have some confidence that a region
+//with the same name is ours from a previous run, so we replace it to avoid leaking (although
+//it's still possible we're conflicting with another application, but good name choices should
+//mitigate this)
+RCRegion::ConflictResolutionStrategy RCRegion::conflictStrategy=RCRegion::REPLACE;
+
+#endif
+
+RCRegion * RCRegion::attach(const Identifier& rid) {
+	attachedRegions_t::iterator it=attachedRegions.find(rid.key);
+	if(it==attachedRegions.end())
+		return new RCRegion(rid); // the constructor will add entry to attachedRegions
+	else {
+		ASSERTRETVAL((*it).second!=NULL,"ERROR: attached region is NULL!",NULL);
+		(*it).second->AddReference();
+		return (*it).second;
+	}
+}
+
+void RCRegion::AddReference() {
+	AutoLock autolock(*lock,ProcessID::getID());
+	//cout << "AddReference " << id.shmid << ' ' << ProcessID::getID();
+	references[ProcessID::getID()]++;
+	references[ProcessID::NumProcesses]++;
+	//cout << " counts are now:";
+	//for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+	//	cout << ' ' << references[i];
+	//cout << endl;
+}
+
+void RCRegion::RemoveReference() {
+	//cout << "RemoveReference " << id.key << ' ' << ProcessID::getID();
+	if(references[ProcessID::getID()] == 0) {
+		cerr << "Warning: RCRegion reference count underflow on " << id.key << " by " << ProcessID::getID() << "!  ";
+		for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+			cerr << ' ' << references[i];
+		cerr << endl;
+		return;
+	}
+	//if(MutexLockBase::getSemaphoreManager()!=NULL) //check in case this region contained the mutexman and SharedObject just destructed it
+	lock->lock(ProcessID::getID());
+	bool wasLastProcRef=(--references[ProcessID::getID()] == 0);
+	bool wasLastAnyRef=(--references[ProcessID::NumProcesses] == 0);
+	ASSERT(wasLastProcRef || !wasLastAnyRef,"global reference decremented beyond process reference");
+	//if(MutexLockBase::getSemaphoreManager()!=NULL)
+	lock->unlock();
+	if(isFaultShutdown) {
+		cerr << "Process " << ProcessID::getID() << " dereferenced " << id.key << ".  Counts are now:";
+		for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+			cerr << ' ' << references[i];
+		cerr << endl;
+	}
+	if(wasLastProcRef) {
+		//cout << " detach";
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+		if(shmdt(base)<0)
+			perror("Warning: Region detach");
+		base=NULL;
+		references=NULL;
+		if(wasLastAnyRef) {
+			//cout << " delete" << endl;
+			if(shmctl(id.shmid,IPC_RMID,NULL)<0)
+				perror("Warning: Region delete");
+		}
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+		if(munmap(base,calcRealSize(id.size))<0) {
+			perror("Warning: Shared memory unmap (munmap)");
+		}
+		base=NULL;
+		references=NULL;
+		if(wasLastAnyRef) {
+			//cout << " delete" << endl;
+			if(!unlinkRegion()) {
+				int err=errno;
+				if(isFaultShutdown && (err==EINVAL || err==ENOENT))
+					//On a fault shutdown, we initially try to unlink everything right away,
+					// so an error now is just confirmation that it worked
+					cerr << "Region " << id.key << " appears to have been successfully unlinked" << endl;
+				else {
+					cerr << "Warning: Shared memory unlink (shm_unlink) of region " << id.key << " returned " << strerror(err);
+					if(err==EINVAL || err==ENOENT)
+						cerr << "\n         May have already been unlinked by a dying process.";
+					cerr << endl;
+				}
+			} else if(isFaultShutdown)
+				//That shouldn't have succeeded on a faultShutdown...
+				cerr << "Region " << id.key << " appears to have been successfully unlinked (nonstandard)" << endl;
+		}
+#else
+#  error "Unknown TEKKOTSU_SHM_STYLE setting"
+#endif
+		delete this;
+	}
+	//cout << endl;
+}
+
+void RCRegion::AddSharedReference() {
+	AutoLock autolock(*lock,ProcessID::getID());
+	//cout << "AddSharedReference " << id.shmid << ' ' << ProcessID::getID();
+	references[ProcessID::NumProcesses]++;
+	//cout << " counts are now:";
+	//for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+	//	cout << ' ' << references[i];
+	//cout << endl;
+}
+
+void RCRegion::RemoveSharedReference() {
+	AutoLock autolock(*lock,ProcessID::getID());
+	//cout << "RemoveSharedReference " << id.shmid << ' ' << ProcessID::getID();
+	if(references[ProcessID::NumProcesses]==0) {
+		cerr << "Warning: RCRegion shared reference count underflow on " << id.key << " by " << ProcessID::getID() << "!  ";
+		for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+			cerr << ' ' << references[i];
+		cerr << endl;
+		return;
+	}
+	references[ProcessID::NumProcesses]--;
+	//cout << " counts are now:";
+	//for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+	//	cout << ' ' << references[i];
+	//cout << endl;
+}
+
+
+void RCRegion::aboutToFork(ProcessID::ProcessID_t newID) {
+	//cout << "RCRegion aboutToFork to " << newID << endl;
+	attachedRegions_t::const_iterator it=attachedRegions.begin();
+	for(; it!=attachedRegions.end(); ++it) {
+		//cout << "Duplicating attachments for " << (*it).first;
+		(*it).second->references[newID]=(*it).second->references[ProcessID::getID()];
+		(*it).second->references[ProcessID::NumProcesses]+=(*it).second->references[newID];
+		//cout << " counts are now:";
+		//for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+		//	cout << ' ' << (*it).second->references[i];
+		//cout << endl;
+	}
+}
+
+void RCRegion::faultShutdown() {
+	if(isFaultShutdown) {
+		cerr << "WARNING: RCRegion::faultShutdown() called again... ignoring" << endl;
+		return;
+	}
+	isFaultShutdown=true;
+	if(attachedRegions.size()==0) {
+		cerr << "WARNING: RCRegion::faultShutdown() called without any attached regions (may be a good thing?)" << endl;
+		return;
+	}
+#if TEKKOTSU_SHM_STYLE==POSIX_SHM
+	//this may not really work, but it's worth a last-ditch attempt
+	//in case the reference counts are screwed up.
+	attachedRegions_t::const_iterator it=attachedRegions.begin();
+	for(; it!=attachedRegions.end(); ++it) {
+		cerr << "RCRegion::faultShutdown(): Process " << ProcessID::getID() << " unlinking " << (*it).second->id.key << endl;
+#ifdef USE_UNBACKED_SHM
+		shm_unlink(getQualifiedName((*it).second->id.key).c_str());
+#else
+		unlink(getQualifiedName((*it).second->id.key).c_str());
+#endif
+	}
+#endif
+	for(unsigned int i=0; i<100; i++) {
+		unsigned int attempts=ProcessID::NumProcesses;
+		unsigned int lastSize=attachedRegions.size();
+		while(attachedRegions.size()==lastSize && attempts-->0)
+			(*attachedRegions.begin()).second->RemoveReference();
+		if(attempts==-1U) {
+			cout << "Warning: could not dereference " << attachedRegions.begin()->second->id.key << endl;
+			attachedRegions.erase(attachedRegions.begin());
+		}
+		if(attachedRegions.size()==0)
+			break;
+	}
+}
+
+RCRegion::~RCRegion() {
+	attachedRegions.erase(id.key);
+	ASSERT(base==NULL,"destructed with attachment!");
+	ASSERT(references==NULL,"destructed with local references!");
+	//cout << "~RCRegion " << id.shmid << ' ' << ProcessID::getID() << endl;
+}
+	
+unsigned int RCRegion::calcRealSize(unsigned int size) {
+	size=((size+align-1)/align)*align; //round up for field alignment
+	size+=extra; //add room for the reference count
+	unsigned int pagesize=::getpagesize();
+	unsigned int pages=(size+pagesize-1)/pagesize;
+	return pages*pagesize; //round up to the nearest page
+}
+
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+
+void RCRegion::init(size_t sz, key_t sug_key, bool create) {
+	id.size=sz;
+	sz=calcRealSize(sz);
+	if(create) {
+		int flags = 0666 | IPC_CREAT | IPC_EXCL;
+		if(sug_key==IPC_PRIVATE) {
+			if((id.shmid=shmget(sug_key, sz, flags)) < 0) {
+				int err=errno;
+				if(err != EEXIST) {
+					cerr << "ERROR: Getting new private region " << key << " of size " << sz ": " << strerror(err) << " (shmget)" << endl;
+					exit(EXIT_FAILURE);
+				}
+			}
+			id.key=sug_key;
+		} else {
+			nextKey=sug_key;
+			switch(conflictStrategy) {
+				case RENAME:
+					while((id.shmid=shmget(id.key=nextKey++, sz, flags)) < 0) {
+						int err=errno;
+						if(err != EEXIST) {
+							cerr << "ERROR: Getting new region " << key << " of size " << sz ": " << strerror(err) << " (shmget)" << endl;
+							exit(EXIT_FAILURE);
+						}
+					}
+					break;
+				case REPLACE:
+					if((id.shmid=shmget(id.key=nextKey, sz, flags)) >= 0)
+						break;
+					int err=errno;
+					if(err != EEXIST) {
+						cerr << "ERROR: Getting new region " << key << " of size " << sz ": " << strerror(err) << " (shmget)" << endl;
+						exit(EXIT_FAILURE);
+					}
+#ifdef DEBUG
+					cerr << "Warning: conflicted key " << key << ", attempting to replace\n"
+						 << "         (may have been leftover from a previous crash)" << endl;
+#endif
+					if(shmctl(id.shmid,IPC_RMID,NULL)<0)
+						perror("Warning: Region delete from conflict - is another simulator running?");
+					//note fall-through from REPLACE into EXIT - only try delete once, and then recreate and exit if it fails again
+				case EXIT: 
+					if((id.shmid=shmget(id.key=nextKey, sz, flags)) < 0) {
+						int err=errno;
+						cerr << "ERROR: Getting new region " << key << " of size " << sz ": " << strerror(err) << " (shmget)" << endl;
+						exit(EXIT_FAILURE);
+					}
+			}
+		}
+	} else {
+		int flags = 0666;
+		if((id.shmid=shmget(sug_key, sz, flags)) < 0) {
+			int err=errno;
+			cerr << "ERROR: Getting existing region " << key << " of size " << sz ": " << strerror(err) << " (shmget)" << endl;
+			exit(EXIT_FAILURE);
+		}
+		id.key=sug_key;
+	}
+	//cout << "ATTACHING " << id.shmid << " NOW" << endl;
+	base=static_cast<char*>(shmat(id.shmid, NULL, SHM_RND));
+	int err=errno;
+	//cout << "Base is " << (void*)base << endl;
+	if (base == reinterpret_cast<char*>(-1)) {
+		cerr << "ERROR: Attaching region " << key << " of size " << sz << ": " << strerror(err) << " (shmat)" << endl;
+		if(shmctl(id.shmid,IPC_RMID,NULL)<0)
+			perror("Region delete");
+		exit(EXIT_FAILURE);
+	}
+	lock=reinterpret_cast<MutexLock<ProcessID::NumProcesses>*>(base+sz-sizeof(MutexLock<ProcessID::NumProcesses>));
+	references=reinterpret_cast<unsigned int*>(base+sz-extra);
+	if(create) {
+		new (lock) MutexLock<ProcessID::NumProcesses>;
+		AutoLock autolock(*lock,ProcessID::getID());
+		for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+			references[i]=0;
+	}
+	AddReference();
+	attachedRegions[id.key]=this;
+}
+
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+	
+std::string RCRegion::getQualifiedName(const std::string& key) {
+#ifdef USE_UNBACKED_SHM
+	string idval="/";
+#else
+	string idval=shmRoot;
+#endif
+	if(useUniqueMemoryRegions) {
+		char pidstr[10];
+		snprintf(pidstr,10,"%d-",rootPID);
+		idval+=pidstr;
+	}
+	idval+=key;
+	return idval;
+}
+int RCRegion::openRegion(int mode) const {
+#ifdef USE_UNBACKED_SHM
+	return shm_open(getQualifiedName().c_str(),mode,0666);
+#else
+	return open(getQualifiedName().c_str(),mode,0666);
+#endif
+}
+bool RCRegion::unlinkRegion() const {
+#ifdef USE_UNBACKED_SHM
+	return shm_unlink(getQualifiedName().c_str())==0;
+#else
+	return unlink(getQualifiedName().c_str())==0;
+#endif
+}
+void RCRegion::init(size_t sz, const std::string& name, bool create) {
+	id.size=sz; //size of requested region
+	sz=calcRealSize(sz); //add some additional space for region lock and reference counts
+#ifndef USE_UNBACKED_SHM
+	struct stat statbuf;
+	//cout << "Checking " << shmRoot.substr(0,shmRoot.rfind('/')) << endl;
+	if(stat(shmRoot.substr(0,shmRoot.rfind('/')).c_str(),&statbuf)) {
+		for(string::size_type c=shmRoot.find('/',1); c!=string::npos; c=shmRoot.find('/',c+1)) {
+			//cout << "Checking " << shmRoot.substr(0,c) << endl;
+			if(stat(shmRoot.substr(0,c).c_str(),&statbuf)) {
+				mkdir(shmRoot.substr(0,c).c_str(),0777);
+			} else if(!(statbuf.st_mode&S_IFDIR)) {
+				cerr << "*** ERROR " << shmRoot.substr(0,c) << " exists and is not a directory" << endl;
+				cerr << "           Cannot create file-backed shared memory regions in " << shmRoot << endl;
+				exit(EXIT_FAILURE);
+			}
+		}
+		cout << "Created '" << shmRoot.substr(0,shmRoot.rfind('/')) << "' for file-backed shared memory storage" << endl;
+	} else if(!(statbuf.st_mode&S_IFDIR)) {
+		cerr << "*** ERROR " << shmRoot.substr(0,shmRoot.rfind('/')) << " exists and is not a directory" << endl;
+		cerr << "           Cannot create file-backed shared memory regions with prefix " << shmRoot << endl;
+		exit(EXIT_FAILURE);
+	}
+#endif
+	int fd;
+	if(name.size()>=MAX_NAME_LEN)
+		cerr << "*** WARNING RCRegion named " << name << " will be clipped to " << name.substr(0,MAX_NAME_LEN-1) << endl;
+	strncpy(id.key,name.c_str(),MAX_NAME_LEN-1);
+	id.key[MAX_NAME_LEN-1]='\0';
+	if(create) {
+		static unsigned int renameSN=0;
+		switch(conflictStrategy) {
+			case RENAME: {
+				char origName[MAX_NAME_LEN];
+				strncpy(origName,id.key,MAX_NAME_LEN);
+				if((fd=openRegion(O_RDWR|O_CREAT|O_EXCL))>=0)
+					break;
+				do {
+					int err=errno;
+					if(err!=EEXIST) {
+						cerr << "ERROR: Opening new region " << id.key << ": " << strerror(err) << " (shm_open)" << endl;
+						exit(EXIT_FAILURE);
+					}
+					unsigned int p=snprintf(id.key,MAX_NAME_LEN,"%s-%d",origName,++renameSN);
+					if(p>=MAX_NAME_LEN) {
+						cerr << "ERROR: conflicted key " << origName << ", attempting to rename, but generated name is too long" << endl;
+						exit(EXIT_FAILURE);
+					}
+					//id.key[MAX_NAME_LEN-1]='\0';
+#ifdef DEBUG
+					cerr << "Warning: conflicted key " << origName << ", attempting to rename as " << id.key << "\n"
+						<< "         (may have been leftover from a previous crash)" << endl;
+#endif
+				} while((fd=openRegion(O_RDWR|O_CREAT|O_EXCL))<0);
+				break;
+			}
+			case REPLACE: {
+				if((fd=openRegion(O_RDWR|O_CREAT|O_EXCL))>=0)
+					break;
+				int err=errno;
+				if(err!=EEXIST) {
+					cerr << "ERROR: Opening new region " << id.key << ": " << strerror(err) << " (shm_open)" << endl;
+					exit(EXIT_FAILURE);
+				}
+#ifdef DEBUG
+				cerr << "Warning: conflicted key " << id.key << ", attempting to replace\n"
+				     << "         (may have been leftover from a previous crash)" << endl;
+#endif
+				if(!unlinkRegion())
+					perror("Warning: Shared memory unlink (shm_unlink)");
+			}
+			//note fall-through from REPLACE into EXIT - only try delete once, and then recreate and exit if it fails again
+			case EXIT: {
+				if((fd=openRegion(O_RDWR|O_CREAT|O_EXCL))<0) {
+					int err=errno;
+					cerr << "ERROR: Opening new region " << id.key << ": " << strerror(err) << " (shm_open)" << endl;
+					if(err==EEXIST)
+						cerr << "This error suggests a leaked memory region, perhaps from a bad crash on a previous run.\n"
+							<< "You may either be able to use shm_unlink to remove the region, or reboot.\n"
+							<< "Also make sure that no other copies of the simulator are already running." << endl;
+					exit(EXIT_FAILURE);
+				}
+			}
+		}
+		if (ftruncate(fd,sz)<0) {
+			int err=errno;
+			cerr << "ERROR: Sizing region " << id.key << " to " << sz << ": " << strerror(err) << " (ftruncate)" << endl;
+			if(close(fd)<0)
+				perror("Warning: Closing temporary file descriptor from shm_open");
+			if(!unlinkRegion())
+				perror("Warning: Shared memory unlink (shm_unlink)");
+			exit(EXIT_FAILURE);
+		}
+	} else {
+		if((fd=openRegion(O_RDWR))<0) {
+			int err=errno;
+			cerr << "ERROR: Opening existing region " << id.key << ": " << strerror(err) << " (shm_open)" << endl;
+			exit(EXIT_FAILURE);
+		}
+	}
+	base=static_cast<char*>(mmap(NULL,sz,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(off_t)0));	
+	int err=errno;
+	if (base == reinterpret_cast<char*>(-1)) {
+		cerr << "ERROR: Attaching region " << id.key << " of size " << sz << ": " << strerror(err) << " (mmap)" << endl;
+		if(close(fd)<0)
+			perror("Warning: Closing temporary file descriptor from shm_open");
+		if(!unlinkRegion())
+			perror("Warning: Shared memory unlink (shm_unlink)");
+		exit(EXIT_FAILURE);
+	}
+	if(close(fd)<0) {
+		perror("Warning: Closing temporary file descriptor from shm_open");
+	}
+	lock=reinterpret_cast<MutexLock<ProcessID::NumProcesses>*>(base+sz-sizeof(MutexLock<ProcessID::NumProcesses>));
+	references=reinterpret_cast<unsigned int*>(base+sz-extra);
+	if(create) {
+		new (lock) MutexLock<ProcessID::NumProcesses>;
+		AutoLock autolock(*lock,ProcessID::getID());
+		for(unsigned int i=0; i<ProcessID::NumProcesses+1; i++)
+			references[i]=0;
+	}
+	AddReference();
+	attachedRegions[id.key]=this;
+}
+
+#else
+#  error "Unknown TEKKOTSU_SHM_STYLE setting"
+#endif
+
+/*
+ class syserr : public std::exception {
+public:
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+	 syserr(int errnum, const key_t& key, const std::string& msg) throw() : info()
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+	 syserr(int errnum, const std::string& key, const std::string& msg) throw() : info()
+#endif
+ {
+		 stringstream tmp;
+		 tmp << "Exception regarding region " << key << ": " << msg << '(' << strerror(errnum) << ')';
+		 info=tmp.c_str();
+ }
+	 virtual ~syserr() throw() {}
+	 virtual const char * what() const throw() { return info.c_str(); }
+protected:
+			std::string info;
+ };
+ */
+
+/*! @file
+* @brief Implements RCRegion, which provides compatability with the OPEN-R type of the same name
+* @author ejt (Creator)
+*
+* $Author: ejt $
+* $Name: tekkotsu-2_4 $
+* $Revision: 1.3 $
+* $State: Exp $
+* $Date: 2005/06/23 20:17:54 $
+*/
+
+#endif
diff -urdN ../Tekkotsu_2.3/IPC/RCRegion.h ./IPC/RCRegion.h
--- ../Tekkotsu_2.3/IPC/RCRegion.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/RCRegion.h	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,166 @@
+//-*-c++-*-
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/RCRegion.h>
+#else
+#  ifndef INCLUDED_RCRegion_h_
+#  define INCLUDED_RCRegion_h_
+
+#include "Shared/ReferenceCounter.h"
+#include "MutexLock.h"
+#include "ProcessID.h"
+#include "Shared/plist.h"
+#include <sys/types.h>
+#include <map>
+#include <exception>
+
+//do you want to use the SysV shared memory call interface
+//or the POSIX shared memory interface?  They have different
+//strengths/weaknesses on different platforms... :-/
+#ifndef POSIX_SHM
+#  define POSIX_SHM 1
+#endif
+#ifndef SYSV_SHM
+#  define SYSV_SHM 2
+#endif
+#ifndef TEKKOTSU_SHM_STYLE
+#  define TEKKOTSU_SHM_STYLE POSIX_SHM
+#endif
+
+#if TEKKOTSU_SHM_STYLE!=SYSV_SHM && TEKKOTSU_SHM_STYLE!=POSIX_SHM
+#  error Unknown TEKKOTSU_SHM_STYLE setting
+#endif
+
+
+//! provides compatability with the OPEN-R type of the same name
+class RCRegion {
+public:
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+	//! contains all information needed to attach this region from a different process
+	struct Identifier {
+		Identifier() : key(), shmid(), size(0) {}
+		key_t key;
+		int shmid;
+		size_t size;
+	};
+	//! constructor (OPEN-R compatability)
+	explicit RCRegion(size_t sz)
+		: id(), base(NULL), references(NULL), lock(NULL)
+	{ init(sz,nextKey,true); }
+	//! constructor, name isn't used for sysv
+	/*! could hash the name to generate key...? */
+	RCRegion(const std::string&, size_t sz)
+		: id(), base(NULL), references(NULL), lock(NULL)
+	{ init(sz,nextKey,true); }
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+	//! maximum guaranteed length for users' region names (might have a little leeway depending on process ID prefix or tmp path prefix)
+	static const unsigned int MAX_NAME_LEN=64;
+#  ifndef USE_UNBACKED_SHM
+	static plist::Primitive<std::string> shmRoot;
+#  endif
+	static plist::Primitive<bool> useUniqueMemoryRegions;
+	static pid_t rootPID; //!< this is the pid of the original process, used for unique names of memory regions; pid_t is from sys/types.h
+	struct Identifier {
+		Identifier() : size(0) {}
+		char key[MAX_NAME_LEN];
+		size_t size;
+	};
+	//! constructor (OPEN-R compatability, name is autogenerated)
+	explicit RCRegion(size_t sz)
+		: id(), base(NULL), references(NULL), lock(NULL)
+	{
+		char name[RCRegion::MAX_NAME_LEN];
+		static unsigned int sn=0;
+		snprintf(name,RCRegion::MAX_NAME_LEN,"Rgn.%d.%d",ProcessID::getID(),++sn);
+		name[RCRegion::MAX_NAME_LEN-1]='\0';
+		init(sz,name,true);
+	}
+	//! constructor, specify your own name for better debugging accountability (not OPEN-R compatable)
+	RCRegion(const std::string& name, size_t sz)
+		: id(), base(NULL), references(NULL), lock(NULL)
+	{ init(sz,name,true); }
+#endif
+
+	static RCRegion * attach(const Identifier& rid);
+	
+	char * Base() const { return base; }
+	size_t Size() const { return id.size; }
+	static void setNextKey(key_t k) { nextKey=k; }
+	const Identifier& ID() const { return id; }
+	
+	int NumberOfReference() const { return references[ProcessID::NumProcesses]; }
+	int NumberOfLocalReference() const { return references[ProcessID::getID()]; }
+	void AddReference();
+	void RemoveReference();
+	void AddSharedReference();
+	void RemoveSharedReference();
+	
+	static void aboutToFork(ProcessID::ProcessID_t newID);
+	static void faultShutdown();
+	static unsigned int NumberOfAttach() { return attachedRegions.size(); }
+	
+	//! Different methods of handling regions with conflicting keys
+	enum ConflictResolutionStrategy {
+		RENAME,  //!< try another key until we find one that works (better for SYSV, maybe not so smart for POSIX)
+		REPLACE, //!< delete the other region and try again (better for POSIX, maybe not so smart for SYSV)
+		EXIT //!< go home and cry about it
+	};
+	
+	static void setConflictResolution(ConflictResolutionStrategy crs) { conflictStrategy=crs; }
+	static ConflictResolutionStrategy getConflictResolution() { return conflictStrategy; }
+	
+protected:
+	RCRegion(const Identifier& rid)
+		: id(), base(NULL), references(NULL), lock(NULL)
+	{ init(rid.size,rid.key,false); }
+
+	~RCRegion();
+
+	static const unsigned int align=sizeof(unsigned int);
+	static const unsigned int extra=sizeof(unsigned int)*(ProcessID::NumProcesses+1)
+	                                +sizeof(MutexLock<ProcessID::NumProcesses>);
+	static unsigned int calcRealSize(unsigned int size);
+
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+	void init(size_t sz, key_t sug_key, bool create);
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+	std::string getQualifiedName() const { return getQualifiedName(id.key); }
+	static std::string getQualifiedName(const std::string& key);
+	int openRegion(int mode) const;
+	bool unlinkRegion() const;
+	void init(size_t sz, const std::string& name, bool create);
+#endif
+
+	static ConflictResolutionStrategy conflictStrategy;
+	static bool isFaultShutdown;
+									  
+	static key_t nextKey;
+#if TEKKOTSU_SHM_STYLE==SYSV_SHM
+	typedef std::map<key_t,RCRegion*> attachedRegions_t;
+#elif TEKKOTSU_SHM_STYLE==POSIX_SHM
+	typedef std::map<std::string,RCRegion*> attachedRegions_t;
+#endif
+	static attachedRegions_t attachedRegions;
+	
+	Identifier id;
+	char * base;
+	unsigned int * references;
+	MutexLock<ProcessID::NumProcesses> * lock;
+
+private:
+	RCRegion(const RCRegion& r); //!< don't call
+	RCRegion& operator=(const RCRegion& r); //!< don't call
+};
+
+/*! @file
+ * @brief Describes RCRegion, which provides compatability with the OPEN-R type of the same name
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:46 $
+ */
+
+#  endif
+#endif
diff -urdN ../Tekkotsu_2.3/IPC/RegionRegistry.h ./IPC/RegionRegistry.h
--- ../Tekkotsu_2.3/IPC/RegionRegistry.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/RegionRegistry.h	Wed Jun  1 01:47:46 2005
@@ -0,0 +1,114 @@
+//-*-c++-*-
+#ifndef INCLUDED_RegionRegistry_h_
+#define INCLUDED_RegionRegistry_h_
+
+#ifdef PLATFORM_APERIOS
+#  warning RegionRegistry is not Aperios compatable
+#else
+
+#include "ListMemBuf.h"
+#include "RCRegion.h"
+#include "LockScope.h"
+#include "ProcessID.h"
+
+//! Keeps track of currently available shared memory regions
+template<unsigned int MAX_REGIONS, unsigned int NAME_LEN=0>
+class RegionRegistry {
+protected:
+	mutable MutexLock<ProcessID::NumProcesses> lock;
+	typedef LockScope<ProcessID::NumProcesses> AutoLock;
+	
+	//! Holds information regarding a shared memory region available for listening
+	struct entry {
+		//! constructor
+		entry() : id() { name[0]='\0'; }
+		entry(const char n[], RCRegion* r) : id(r->ID()) {
+			strncpy(name,n,NAME_LEN);
+			name[NAME_LEN]='\0';
+		}
+		char name[NAME_LEN+1]; //!< the name for the region
+		RCRegion::Identifier id;
+	};
+	typedef ListMemBuf<entry,MAX_REGIONS> registry_t;
+	registry_t avail;
+
+public:
+	static const unsigned int CAPACITY=MAX_REGIONS;
+	static const unsigned int REGION_NAME_LEN=NAME_LEN;
+	typedef typename registry_t::index_t index_t;
+
+	RegionRegistry() : lock(), avail() {}
+	
+	~RegionRegistry() {
+		AutoLock autolock(lock,ProcessID::getID());
+		avail.clear();
+	}
+	
+	index_t findRegion(const std::string& name) const {
+		AutoLock autolock(lock,ProcessID::getID());
+		if(name.size()>NAME_LEN)
+			std::cerr << "WARNING: RegionRegistry::attach("<<name<<") is too long, max is " << NAME_LEN << std::endl;
+		for(index_t it=begin(); it!=end(); it=next(it))
+			if(name==avail[it].name)
+				return it;
+		return avail.end();
+	}
+
+	index_t registerRegion(const std::string& name, const RCRegion * region) {
+		AutoLock autolock(lock,ProcessID::getID());
+		index_t it=findRegion(name);
+		if(it!=end()) { //found, already registered
+			if(avail[it].regions[ProcessID::getID()]==region)
+				return it; //same one, just return it
+			return end(); // conflict, return invalid
+		}
+		//not found, make a new one
+		return avail.push_back(entry(name.c_str(),region));
+	}
+	
+	RCRegion * registerRegion(const std::string& name, size_t size) {
+		AutoLock autolock(lock,ProcessID::getID());
+		index_t it=findRegion(name);
+		if(it!=end()) {
+			//found, already registered
+			return RCRegion::attach(avail[it].id);
+		} else {
+			//not found:
+			RCRegion * region = new RCRegion(name,size);
+			avail.push_back(entry(name.c_str(),region));
+			return region;
+		}
+	}
+	
+	RCRegion * operator[](index_t it) const {
+		AutoLock autolock(lock,ProcessID::getID());
+		if(it==end())
+			return NULL;
+		return RCRegion::attach(avail[it].id);
+	}
+	
+	void erase(index_t it) {
+		AutoLock autolock(lock,ProcessID::getID());
+		avail.erase(it);
+	}
+	
+	index_t begin() const { return avail.begin(); }
+	index_t next(index_t it) const { return avail.next(it); }
+	index_t end() const { return avail.end(); }
+};
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:46 $
+ */
+
+#endif //Aperios check
+
+#endif //INCLUDED
+
diff -urdN ../Tekkotsu_2.3/IPC/SemaphoreManager.cc ./IPC/SemaphoreManager.cc
--- ../Tekkotsu_2.3/IPC/SemaphoreManager.cc	Wed Dec 31 19:00:00 1969
+++ ./IPC/SemaphoreManager.cc	Thu Jun 23 16:18:56 2005
@@ -0,0 +1,346 @@
+#ifndef PLATFORM_APERIOS
+
+#include "SemaphoreManager.h"
+#include "Shared/debuget.h"
+#include <stdlib.h>
+#include <errno.h>
+#include <stdio.h>
+#include <exception>
+#include <iostream>
+
+//this is for linux compatability -- apparently you're *supposed* to
+//define this yourself? (WTF?)
+#if defined(_SEM_SEMUN_UNDEFINED) || defined(__CYGWIN__)
+union semun
+{
+	int val;
+	struct semid_ds *buf;
+	unsigned short int *array;
+	struct seminfo *__buf;
+};
+#endif
+
+using namespace std;
+
+SemaphoreManager::SemaphoreManager()
+: sems(), nsem(sems_t::MAX_ENTRIES), semid(-1), mysem(sems.end()), refc(sems.end())
+{
+	//the seminfo structure is kernel-private and I can't find a portable way to access
+	//SEMMSL without it.
+	/*semun params; 
+	seminfo info;
+	params.__buf=info;
+	if(semctl(semid,-1,IPC_INFO,params)<0) {
+		perror("WARNING: SemaphoreManager query (semctl)");
+		//we'll just forge ahead with the default value...
+		//exit(EXIT_FAILURE);
+	} else {
+		if(nsem>info.semmsl)
+			nsem=info.semmsl;
+	}*/
+	
+	//So instead we'll do a binary search for the size:
+	unsigned int lowbound=0; //inclusive
+	unsigned int highbound=nsem; //inclusive
+	while(lowbound!=highbound) {
+		semid=semget(IPC_PRIVATE,nsem,IPC_CREAT | IPC_EXCL | 0666);
+		if(semid<0) {
+			if(errno!=EINVAL && errno!=ENOSPC) {
+				perror("ERROR: SemaphoreManager upper limit detection (semget)");
+				exit(EXIT_FAILURE);
+			}
+			//too big
+			highbound=nsem-1;
+		} else {
+			//succeeded -- too low?
+			if(semctl(semid,-1,IPC_RMID)<0) {
+				perror("ERROR: SemaphoreManager destruction (semctl)");
+				exit(EXIT_FAILURE);
+			}
+			lowbound=nsem;
+		}
+		nsem=(lowbound+highbound+1)/2;
+	}
+	if(nsem!=sems_t::MAX_ENTRIES)
+		cerr << "WARNING: System can only allocate " << nsem << " semaphores per set (SEMMSL). " << sems_t::MAX_ENTRIES << " were suggested." << endl;
+	
+	//get the semaphore set
+	semid=semget(IPC_PRIVATE,nsem,IPC_CREAT | IPC_EXCL | 0666);
+	if(semid<0) {
+		perror("ERROR: SemaphoreManager construction (semget)");
+				exit(EXIT_FAILURE);
+	}
+	
+	//initialize to 0 (unlocked)
+	unsigned short int semvals[sems_t::MAX_ENTRIES];
+	for(unsigned int i=0; i<nsem; i++)
+		semvals[i]=0;
+	semun params; 
+	params.array=semvals;
+	if(semctl(semid,-1,SETALL,params)<0) {
+		perror("ERROR: SemaphoreManager construction (semctl)");
+		exit(EXIT_FAILURE);
+	}
+	
+	//burn any extra ids we couldn't actually get from the system
+	if(nsem!=sems_t::MAX_ENTRIES) {
+		//first use up all the IDs
+		while(sems.new_back()!=sems.end()) {}
+		//now free the first nsem
+		for(unsigned int i=0; i<nsem; i++)
+			sems.pop_front();
+	}
+		
+	//take one for ourselves to lock handing out semaphores
+	mysem=sems.new_front();
+	if(mysem==sems.end()) {
+		cerr << "ERROR: could not allocate SemaphoreManager internal lock" << endl;
+		exit(EXIT_FAILURE);
+	}
+	//only one semaphore can be in the process of creation or release at any given time, we have the lock
+	setValue(mysem,1);
+	//take another for ourselves to use as a reference count on the semaphore set
+	refc=sems.new_front();
+	if(refc==sems.end()) {
+		cerr << "ERROR: could not allocate SemaphoreManager reference counter" << endl;
+		exit(EXIT_FAILURE);
+	}
+	//reference count starts at 0 -- underflow is signalled by negative count
+	setValue(refc,0);
+	//cerr << "Semaphore set " << semid << " created" << endl;
+}
+
+SemaphoreManager::SemaphoreManager(const SemaphoreManager& mm)
+: sems(), nsem(mm.nsem), semid(mm.semid), mysem(mm.mysem), refc(mm.refc)
+{
+	ASSERT(mm.semid!=-1,"Copy of SemaphoreManager with invalid semid!");
+	lower(mysem,1); //get a lock on the new set
+	sems=mm.sems; //we didn't copy sems earlier because we need a lock for this
+	raise(refc,1); //add 1 to reference counter for our new set
+	raise(mysem,1); //release lock on new set
+	//cerr << "Semaphore set " << semid << " copied" << endl;
+}
+
+SemaphoreManager& SemaphoreManager::operator=(const SemaphoreManager& mm) {
+	if(&mm==this)
+		return *this;
+	//ASSERT(semid!=-1,"Assignment to SemaphoreManager with invalid semid!");
+	//ASSERT(mm.semid!=-1,"Assignment of SemaphoreManager with invalid semid!");
+	if(semid==mm.semid) {
+		//both reference the same set, just update some fields
+		if(mm.semid!=-1)
+			mm.lower(mm.mysem,1); //get a lock on the new set
+		mysem=mm.mysem;
+		sems=mm.sems;
+		nsem=mm.nsem;
+		if(mm.semid!=-1)
+			mm.raise(mm.mysem,1); //release lock on new set
+	} else {
+		//we're replacing one set with the other, need to dereference our current set
+		//cerr << "Semaphore set " << semid << " dereferenced" << endl;
+		if(semid!=-1) {
+			lower(mysem,1); //lock current set
+			if(!lower(refc,1,false)) { //remove 1 from the reference counter for our current set
+				//ran out of references to the old set, delete it
+				//cerr << "Semaphore set " << semid << " deleted" << endl;
+				sems.erase(refc);
+				sems.erase(mysem);
+				for(semid_t it=sems.begin(); it!=sems.end(); it=sems.next(it))
+					cerr << "Warning: semaphore id " << it << " from set " << semid << " was still active when the set was dereferenced" << endl;
+				if(semctl(semid,-1,IPC_RMID)<0) {
+					perror("ERROR: SemaphoreManager deletion from operator= (semctl)");
+					exit(EXIT_FAILURE);
+				}
+				semid=-1;
+			} else
+				raise(mysem,1); // it's still referenced, unlock for others
+		}
+		if(mm.semid!=-1)
+			mm.lower(mm.mysem,1); //get a lock on the new set
+		mysem=mm.mysem;
+		sems=mm.sems;
+		nsem=mm.nsem;
+		semid=mm.semid;
+		if(mm.semid!=-1) {
+			raise(refc=mm.refc,1); //add 1 to reference counter for our new set
+			mm.raise(mm.mysem,1); //release lock on new set
+		}
+		//cerr << "Semaphore set " << semid << " assigned" << endl;
+	}
+	return *this;
+}
+
+SemaphoreManager::~SemaphoreManager() {
+	if(semid==-1)
+		return;
+	//cerr << "Semaphore set " << semid << " dereferenced" << endl;
+	lower(mysem,1); //lock current set
+	if(!lower(refc,1,false)) { //remove 1 from the reference counter for our current set
+		//ran out of references to the old set, delete it
+		//cerr << "Semaphore set " << semid << " deleted" << endl;
+		/* // on the final shutdown, the process-local copies can't tell if semaphores were freed remotely
+		sems.erase(refc);
+		sems.erase(mysem);
+		for(semid_t it=sems.begin(); it!=sems.end(); it=sems.next(it))
+			cerr << "Warning: semaphore id " << it << " from set " << semid << " was still active when the set was dereferenced" << endl;
+		*/
+		if(semctl(semid,-1,IPC_RMID)<0) {
+			perror("ERROR: SemaphoreManager deletion from destructor (semctl)");
+			exit(EXIT_FAILURE);
+		}
+		semid=-1;
+	} else
+		raise(mysem,1);
+}
+
+void SemaphoreManager::aboutToFork() {
+	raise(refc,1);
+}
+
+void SemaphoreManager::faultShutdown() {
+	if(semctl(semid,-1,IPC_RMID)<0)
+		perror("WARNING: SemaphoreManager faultShutdown (semctl)");
+	semid=-1;
+}
+
+SemaphoreManager::semid_t SemaphoreManager::getSemaphore() {
+	lower(mysem,1);
+	semid_t id=sems.new_front();
+	raise(mysem,1);
+	return id;
+}
+void SemaphoreManager::releaseSemaphore(semid_t id) {
+	lower(mysem,1);
+	sems.erase(id);
+	raise(mysem,1);
+}
+
+bool SemaphoreManager::lower(semid_t id, unsigned int x, bool block/*=true*/) const {
+	sembuf sb={id,-x,(block?0:IPC_NOWAIT)};
+	while(semop(semid,&sb,1)<0) {
+		if(errno==EAGAIN)
+			return false;
+		perror("ERROR: SemaphoreManager unable to lower semaphore (semop)");
+		if(errno==EINTR) {
+			cerr << "       I was interrupted.  Trying again...";
+		} else {
+			cerr << "       ";
+			if(errno==EIDRM) {
+				cerr << "Semaphore set has been removed.  " << endl;
+			}
+			if(errno==EINVAL) {
+				cerr << "Semaphore set was deleted.  " << endl;
+			}
+			//prevent recuring problems
+			cerr << "Goodbye" << endl;
+			exit(EXIT_FAILURE);
+		}
+	}
+	return true;
+}
+void SemaphoreManager::raise(semid_t id, unsigned int x) const {
+	sembuf sb={id,x,0};
+	if(semop(semid,&sb,1)<0) {
+		perror("ERROR: SemaphoreManager unable to raise semaphore (semop)");
+	}
+}
+int SemaphoreManager::getValue(semid_t id) const {
+	int ans=semctl(semid,id,GETVAL);
+	if(ans<0)
+		perror("ERROR: SemaphoreManager getValue (semctl)");
+	return ans;
+}
+void SemaphoreManager::setValue(semid_t id, int x) const {
+	semun params; 
+	params.val=x;
+	if(semctl(semid,id,SETVAL,params)<0) {
+		perror("ERROR: SemaphoreManager::setValue (semctl)");
+		exit(EXIT_FAILURE);
+	}
+}
+bool SemaphoreManager::testZero(semid_t id, bool block/*=true*/) const {
+	sembuf sb={id,0,(block?0:IPC_NOWAIT)};
+	while(semop(semid,&sb,1)<0) {
+		int theErr=errno; //need to store this value right away so it doesn't get overwritten while we're processing it
+		if(theErr==EAGAIN)
+			return false;
+		if(theErr!=EINTR) { // && theErr!=ERESTART?
+			perror("ERROR: SemaphoreManager unable to testZero() (semop)");
+			cerr << "       ";
+			if(theErr==EIDRM) {
+				cerr << "Semaphore set has been removed.  " << endl;
+			} else if(theErr==EINVAL) {
+				cerr << "Semaphore set was deleted.  " << endl;
+			} else {
+				cerr << "Error code was " << theErr << endl;
+			}
+			cerr << "Goodbye" << endl;
+			exit(EXIT_FAILURE);
+		} //else cerr << "       I was interrupted.  Trying again...";
+	}
+	return true;
+}
+bool SemaphoreManager::testZero_add(semid_t id, unsigned int x, bool testblock/*=true*/, bool addblock/*=true*/) const {
+	//cerr << "testZero_add of " << id << " in " << semid << endl;
+	sembuf sb[2]={
+		{id,0,(testblock?0:IPC_NOWAIT)},
+		{id,x,(addblock?0:IPC_NOWAIT)}
+	};
+	while(semop(semid,sb,2)<0) {
+		int theErr=errno; //need to store this value right away so it doesn't get overwritten while we're processing it
+		if(theErr==EAGAIN)
+			return false;
+		if(theErr!=EINTR) { // && theErr!=ERESTART?
+			perror("ERROR: SemaphoreManager unable to testZero_add() (semop)");
+			cerr << "       ";
+			if(theErr==EIDRM) {
+				cerr << "Semaphore set has been removed.  " << endl;
+			} else if(theErr==EINVAL) {
+				cerr << "Semaphore set was deleted.  " << endl;
+			} else {
+				cerr << "Error code was " << theErr << endl;
+			}
+			cerr << "Goodbye" << endl;
+			exit(EXIT_FAILURE);
+		} //else cerr << "       I was interrupted.  Trying again...";
+	}
+	return true;
+}
+bool SemaphoreManager::add_testZero(semid_t id, unsigned int x, bool addblock/*=true*/, bool testblock/*=true*/) const {
+	sembuf sb[2]={
+		{id,x,(addblock?0:IPC_NOWAIT)},
+		{id,0,(testblock?0:IPC_NOWAIT)}
+	};
+	while(semop(semid,sb,2)<0) {
+		int theErr=errno; //need to store this value right away so it doesn't get overwritten while we're processing it
+		if(theErr==EAGAIN)
+			return false;
+		if(theErr!=EINTR) { // && theErr!=ERESTART?
+			perror("ERROR: SemaphoreManager unable to add_testZero() (semop)");
+			cerr << "       ";
+			if(theErr==EIDRM) {
+				cerr << "Semaphore set has been removed.  " << endl;
+			} else if(theErr==EINVAL) {
+				cerr << "Semaphore set was deleted.  " << endl;
+			} else {
+				cerr << "Error code was " << theErr << endl;
+			}
+			cerr << "Goodbye" << endl;
+			exit(EXIT_FAILURE);
+		} //else cerr << "       I was interrupted.  Trying again...";
+	}
+	return true;
+}
+
+/*! @file
+ * @brief Implements SemaphoreManager, which initializes, manages, and releases a set of System V style semaphores
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/06/23 20:18:56 $
+ */
+
+#endif //Aperios check
diff -urdN ../Tekkotsu_2.3/IPC/SemaphoreManager.h ./IPC/SemaphoreManager.h
--- ../Tekkotsu_2.3/IPC/SemaphoreManager.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/SemaphoreManager.h	Tue Jun 14 23:40:05 2005
@@ -0,0 +1,73 @@
+//-*-c++-*-
+#ifndef INCLUDED_SemaphoreManager_h_
+#define INCLUDED_SemaphoreManager_h_
+
+#ifdef PLATFORM_APERIOS
+#  warning SemaphoreManager is not Aperios compatable, this is not going to compile
+#else
+
+#include "ListMemBuf.h"
+#include <sys/types.h>
+#include <sys/sem.h>
+
+#ifndef SYSTEM_MAX_SEM
+#define SYSTEM_MAX_SEM 250
+#endif
+
+//! initializes, manages, and releases a set of System V style semaphores
+/*! Should be initialized pre-fork into a shared region */
+class SemaphoreManager {
+protected:
+	static const unsigned int MAX_SEM=SYSTEM_MAX_SEM; //!wouldn't want to claim the entire system's worth, even if we could
+	typedef ListMemBuf<bool,MAX_SEM> sems_t;
+	sems_t sems;
+	
+public:
+	typedef sems_t::index_t semid_t;
+	
+	SemaphoreManager();
+	SemaphoreManager(const SemaphoreManager& mm);
+	SemaphoreManager& operator=(const SemaphoreManager& mm);
+	~SemaphoreManager();
+	
+	void aboutToFork();
+	void faultShutdown();
+	bool hadFault() const { return semid==-1; }
+
+	semid_t getSemaphore();
+	void releaseSemaphore(semid_t id);
+
+	bool lower(semid_t id, unsigned int x, bool block=true) const;
+	void raise(semid_t id, unsigned int x) const;
+	int getValue(semid_t id) const;
+	void setValue(semid_t id, int x) const;
+	bool testZero(semid_t id, bool block=true) const;
+	bool testZero_add(semid_t id, unsigned int x, bool testblock=true, bool addblock=true) const;
+	bool add_testZero(semid_t id, unsigned int x, bool addblock=true, bool testblock=true) const;
+	
+	unsigned int available() const { return sems_t::MAX_ENTRIES-sems.size(); }
+	unsigned int used() const { return sems.size()-(sems_t::MAX_ENTRIES-nsem); }
+	semid_t invalid() const { return sems.end(); }
+
+protected:
+	unsigned int nsem;
+	int semid;
+	semid_t mysem;
+	semid_t refc;
+};
+
+/*! @file
+ * @brief Defines SemaphoreManager, which initializes, manages, and releases a set of System V style semaphores
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
+ * $State: Exp $
+ * $Date: 2005/06/15 03:40:05 $
+ */
+
+#endif //Aperios check
+
+#endif //INCLUDED
+
diff -urdN ../Tekkotsu_2.3/IPC/SharedObject.cc ./IPC/SharedObject.cc
--- ../Tekkotsu_2.3/IPC/SharedObject.cc	Wed Dec 31 19:00:00 1969
+++ ./IPC/SharedObject.cc	Wed Jun  1 01:47:47 2005
@@ -0,0 +1,17 @@
+#include "SharedObject.h"
+
+#ifndef PLATFORM_APERIOS
+unsigned int SharedObjectBase::serialNumber=0;
+#endif
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:47 $
+ */
+
diff -urdN ../Tekkotsu_2.3/IPC/SharedObject.h ./IPC/SharedObject.h
--- ../Tekkotsu_2.3/IPC/SharedObject.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/SharedObject.h	Mon Jun 13 16:29:48 2005
@@ -0,0 +1,185 @@
+//-*-c++-*-
+#ifndef INCLUDED_SharedObject_h
+#define INCLUDED_SharedObject_h
+
+#include "RCRegion.h"
+#include <stdexcept>
+
+//! It's nice to have a parent class of SharedObject (which is what you probably want to be reading) so that you can pass around the data structure without worrying about what type is inside the shared memory region.
+/*! See MotionManager for an example on how to use this. */
+class SharedObjectBase {
+public:
+	void* data() const { return rcr->Base(); } //!< returns a pointer to the data region
+	RCRegion * getRegion() const { return rcr; } //!< returns the OPEN-R memory region, should you need it
+
+protected:
+	//! constructor, protected because you shouldn't need to create this directly, just a common interface to all templates of SharedObject
+	SharedObjectBase() : rcr(NULL) {}
+	//! copy constructor, adds a reference to the existing region (shallow copy)
+	SharedObjectBase(const SharedObjectBase& sob) : rcr(sob.rcr) {
+		rcr->AddReference();
+	}
+	//! assignment, adds a reference to the existing region (shallow copy)
+	SharedObjectBase& operator=(const SharedObjectBase& sob) {
+		if(rcr==sob.rcr)
+			return *this;
+		removeRef();
+		rcr=sob.rcr;
+		rcr->AddReference();
+	}
+	//< destructor
+	virtual ~SharedObjectBase() {} 
+
+	//!removes a reference from #rcr, and if necessary, destructs its data
+	virtual void removeRef()=0;
+	
+	RCRegion * rcr; //!< the pointer to the shared memory region this is in charge of
+	
+#ifndef PLATFORM_APERIOS
+	static unsigned int serialNumber;
+#endif
+};	
+
+
+//! This templated class allows convenient creation of any type of class wrapped in a shared memory region
+/*! @see MotionManager for an example on how to use this.*/
+template<class MC>
+class SharedObject : public SharedObjectBase {
+public:
+	//!if you really need more than 5 arguments for your class, well, you're one crazy puppy but if you really want to, just make more like shown... (yay templates!)
+	//!@name templated contructors - allows you to pass constructor arguments on to the object being created
+
+	//! Creates the class with the default constructor
+	SharedObject() : SharedObjectBase() {
+		rcr=createRCRegion();
+		new (rcr->Base()) MC;
+	}
+	//! Creates the class, passing its constructor t1
+	template<class T1> explicit SharedObject(const T1& t1) : SharedObjectBase() {
+		rcr=createRCRegion();
+		new (rcr->Base()) MC(t1);
+	}
+	//! Creates the class, passing its constructor t1 and t2
+	template<class T1, class T2> SharedObject(const T1& t1, const T2& t2) : SharedObjectBase(){
+		rcr=createRCRegion();
+		new (rcr->Base()) MC(t1,t2);
+	}
+	//! Creates the class, passing its constructor t1, t2, and t3
+	template<class T1, class T2, class T3> SharedObject(const T1& t1, const T2& t2, const T3& t3) : SharedObjectBase(){
+		rcr=createRCRegion();
+		new (rcr->Base()) MC(t1,t2,t3);
+	}
+	//! Creates the class, passing its constructor t1, t2, t3 and t4
+	template<class T1, class T2, class T3, class T4> SharedObject(const T1& t1, const T2& t2, const T3& t3, const T4& t4) : SharedObjectBase(){
+		rcr=createRCRegion();
+		new (rcr->Base()) MC(t1,t2,t3,t4);
+	}
+	//! Creates the class, passing its constructor t1, t2, t3, t4 and t5 - if you need more arguments, just add them
+	template<class T1, class T2, class T3, class T4, class T5> SharedObject(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) : SharedObjectBase(){
+		rcr=createRCRegion();
+		new (rcr->Base()) MC(t1,t2,t3,t4,t5);
+	}
+
+	//! Constructs from a pre-existing region, laying claim to the caller's reference to the region - region's creator is responsible for initialization
+	/*! In other words, this SharedObject doesn't AddReference, but will
+	 *  RemoveReference when the time is right (upon destruction).  If
+	 *  you want to maintain an reference of your own to the region, you
+	 *  will need to call AddReference yourself. */
+	explicit SharedObject(RCRegion * r) : SharedObjectBase() {
+		rcr=r;
+		if(rcr->Size()!=sizeof(MC)) {
+#ifdef PLATFORM_APERIOS
+			std::cerr << "ERROR: SharedObject(RCRegion* r) region size ("<<rcr->Size()<<") does not match size of SharedObject type ("<<sizeof(MC)<<")" << std::endl;
+#else
+			std::cerr << "ERROR: SharedObject(RCRegion* r) region "<<rcr->ID().key<<" size ("<<rcr->Size()<<") does not match size of SharedObject type ("<<sizeof(MC)<<")" << std::endl;
+#endif
+			throw std::invalid_argument("SharedObject(RCRegion* r): region size does not match sizeof(type)");
+		}
+	}
+	//@}
+	
+	//< destructor
+	virtual ~SharedObject() { removeRef(); }
+	
+	MC* operator->() const { return dataCasted(); } //!< smart pointer to the underlying class
+	MC& operator*() const { return *dataCasted(); } //!< smart pointer to the underlying class
+	MC& operator[](int i) const { return dataCasted()[i]; } //!< smart pointer to the underlying class
+
+protected:
+	MC* dataCasted() const { return static_cast<MC*>(data()); } //!< returns a correctly typed pointer to the object's memory
+	
+	//!removes a reference from #rcr, and if necessary, destructs its data
+	virtual void removeRef() {
+		if(rcr) {
+			//std::cout << "~SharedObjectBase(): rcr->NumberOfReference()==" << rcr->NumberOfReference() << std::endl;
+			if(rcr->NumberOfReference()>0) {
+				if(rcr->NumberOfReference()==1)
+					dataCasted()->~MC(); //call destructor
+				rcr->RemoveReference();
+			} else
+				std::cerr << "WARNING: SharedObjectBase destructed without reference" << std::endl;
+			rcr=NULL;
+		}
+	}
+	
+	//! creates and returns RCRegion of correct size for current class.  Adds a reference (which is removed in the destructor)
+	static RCRegion * createRCRegion() {
+#ifdef PLATFORM_APERIOS
+		RCRegion * r = new RCRegion(calcsize());
+#else
+		char name[RCRegion::MAX_NAME_LEN];
+		snprintf(name,RCRegion::MAX_NAME_LEN,"ShdObj.%d.%d",ProcessID::getID(),++serialNumber);
+		name[RCRegion::MAX_NAME_LEN-1]='\0';
+		RCRegion * r = new RCRegion(name,calcsize());
+#endif
+		//cout << "SIZE is " << r->Size() << endl;
+		//cout << "BASE is " << (void*)r->Base() << endl;
+		//std::cout << "createRCRegion(): rcr->NumberOfReference()==" << r->NumberOfReference() << std::endl;
+		//r->AddReference();
+		//std::cout << "createRCRegion()NOW: rcr->NumberOfReference()==" << r->NumberOfReference() << std::endl;
+		return r;
+	}
+
+	//!Calculates the size of the memory region to be used, (on Aperios, rounding up to the nearest page size)
+	/*! Not sure this is completely necessary, but may be nice.  Of course, this also means even
+	 *  small regions are going to be at least 4K (current page size)  If memory gets tight or we
+	 *  get a lot of little regions floating around, this might be worth checking into */
+	static unsigned int calcsize() {
+#ifndef PLATFORM_APERIOS
+		return sizeof(MC);
+#else
+		size_t size = sizeof(MC);
+		sError error;
+		size_t page_size;
+		error = GetPageSize(&page_size);
+		if (error != sSUCCESS) {
+			cout << "error: " << error << " getting page size in SharedMem" << endl;
+			page_size = 4096;
+		}
+		
+		int new_size,num_pages;
+		num_pages = (size+page_size-1)/page_size;
+		new_size = num_pages*page_size;
+		//cout << "req" << size << "new" << new_size << "ps" << page_size << endl;
+		/*
+		cout << "data size is " << sizeof(MC) << endl;
+		cout << "PAGE is " << page_size << endl;
+		cout << "reserved " << new_size << " bytes" << endl;
+		*/
+		return new_size;
+#endif //!PLATFORM_APERIOS
+	}
+};
+
+/*! @file
+ * @brief Defines SharedObject, a wrapper for objects in order to facilitate sending them between processes
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/13 20:29:48 $
+ */
+
+#endif //INCLUDED_SharedObject_h
diff -urdN ../Tekkotsu_2.3/IPC/Thread.cc ./IPC/Thread.cc
--- ../Tekkotsu_2.3/IPC/Thread.cc	Wed Dec 31 19:00:00 1969
+++ ./IPC/Thread.cc	Mon Aug  1 19:17:59 2005
@@ -0,0 +1,202 @@
+#ifndef PLATFORM_APERIOS
+#include "Thread.h"
+
+#include <pthread.h>
+#include <string.h>
+#include <iostream>
+#include <signal.h>
+#include <unistd.h>
+
+using namespace std;
+
+struct Threadstorage_t {
+	Threadstorage_t() : threadInfo(), threadAttr() {
+		if(int err=pthread_attr_init(&threadAttr))
+			cerr << "Threadstorage_t constructor, pthread_attr_init: " << strerror(err) << endl;;
+	}
+	~Threadstorage_t() {
+		if(int err=pthread_attr_destroy(&threadAttr))
+			cerr << "Threadstorage_t destructor, pthread_attr_destroy: " << strerror(err) << endl;
+	}
+	pthread_t threadInfo;
+	pthread_attr_t threadAttr;
+private:
+	Threadstorage_t(const Threadstorage_t& r); //!< don't call
+	Threadstorage_t& operator=(const Threadstorage_t& r); //!< don't call
+};
+
+Thread::Thread() : pt(new Threadstorage_t), running(false), returnValue(NULL) {}
+
+Thread::~Thread() {
+	//can only happen externally
+	if(running) {
+		stop();
+		join();
+	}
+	if(pt==NULL) {
+		std::cerr << "Thread storage already deleted!?!?!" << std::endl;
+		*(int*)NULL=0xDEADDEAD;
+	}
+	delete pt;
+	pt=NULL;
+}
+
+void Thread::start() {
+	if(running) {
+		std::cerr << "Thread::start() -- thread is already running!" << std::endl;
+		std::cerr << "   make another instance if you want to run another copy of this thread" << std::endl;
+		return;
+	}
+	running=true;
+	if(int err=pthread_create(&pt->threadInfo, &pt->threadAttr, launch, this))
+		cerr << "Thread start(), pthread_create: " << strerror(err) << endl;
+}
+
+void * Thread::run() {
+	for(;;) {
+		unsigned int sleeptime=runloop();
+		if(sleeptime==-1U)
+			return returnValue;
+		usleep(sleeptime);
+		testCancel();
+	}
+	return NULL; //never happens
+}
+
+void Thread::stop() {
+	if(int err=pthread_cancel(pt->threadInfo))
+		cerr << "Thread cancel(), pthread_cancel: " << strerror(err) << endl;
+}
+
+void Thread::kill() {
+	if(int err=pthread_kill(pt->threadInfo,SIGALRM))
+		cerr << "Thread stop(), pthread_kill(SIGALRM): " << strerror(err) << endl;
+}
+
+void Thread::murder() {
+	if(int err=pthread_detach(pt->threadInfo))
+		cerr << "Thread kill(), thread_detach: " << strerror(err) << endl;
+	if(int err=pthread_kill(pt->threadInfo,SIGSTOP))
+		cerr << "Thread kill(), pthread_kill(SIGSTOP): " << strerror(err) << endl;
+	running=false;
+}
+
+void * Thread::join() {
+	void * ans=NULL;
+	if(int err=pthread_join(pt->threadInfo, &ans))
+		cerr << "Thread join(), pthread_join: " << strerror(err) << endl;
+	return ans;
+}
+
+void Thread::testCancel() {
+	pthread_testcancel();
+}
+
+void * Thread::launch(void * msg) {
+	if(int err=pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL))
+		cerr << "Thread launch(), pthread_setcanceltype: " << strerror(err) << endl;
+	if(int err=pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL))
+		cerr << "Thread launch(), pthread_setcanceltype: " << strerror(err) << endl;
+	signal(SIGALRM,Thread::handle_signal);
+	void * ans=NULL;
+	{
+		//These pthread functions actually define a scope between them
+		//I've added braces of my own to make this explicitly clear
+		pthread_cleanup_push(Thread::handle_exit,msg);
+		static_cast<Thread*>(msg)->run();
+		pthread_cleanup_pop(true);
+	}
+	return ans;
+}
+
+void Thread::handle_signal(int /*sig*/) {
+	pthread_exit(NULL);
+}
+
+void Thread::handle_exit(void * th) {
+	static_cast<Thread*>(th)->running=false;
+}
+
+namespace ThreadNS {
+		
+	struct LockStorage {
+		LockStorage() : mutex(), attr() {
+			pthread_mutexattr_init(&attr);
+			pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
+			pthread_mutex_init(&mutex,&attr);
+		}
+		~LockStorage() {
+			pthread_mutexattr_destroy(&attr);
+			pthread_mutex_destroy(&mutex);
+		}
+		LockStorage(const LockStorage& ls) : mutex(ls.mutex), attr(ls.attr) {}
+		LockStorage& operator=(const LockStorage& ls) { mutex=ls.mutex; attr=ls.attr; return *this; }
+		void lock() {
+			pthread_mutex_lock(&mutex);
+		}
+		bool trylock() {
+			return !pthread_mutex_trylock(&mutex);
+		}
+		void unlock() {
+			pthread_mutex_unlock(&mutex);
+		}
+		pthread_mutex_t mutex;
+		pthread_mutexattr_t attr;
+	};
+
+	map<int,struct LockStorage*> Lock::ids;
+	bool Lock::issetup=false;
+
+	Lock::Lock() : my_id() {
+		if(!issetup)
+			setup();
+		ids[-1]->lock();
+		my_id=(--ids.end())->first+1;
+		ids[my_id]=new LockStorage;
+		ids[-1]->unlock();
+	}
+	/*
+	Lock::Lock(int ident, bool autolock/ *=true* /) : my_id(ident) {
+		if(!issetup)
+			setup();
+		if(ids.find(my_id)==ids.end()) {
+			ids[-1]->lock();
+			ids[my_id]=new LockStorage;
+			ids[-1]->unlock();
+		}
+		if(autolock)
+			ids[my_id]->lock();
+	}
+	*/
+	Lock::~Lock() {
+		ids[my_id]->unlock();
+	}
+
+	void Lock::lock() {
+		ids[my_id]->lock();
+	}
+	bool Lock::trylock() {
+		return ids[my_id]->trylock();
+	}
+	void Lock::unlock() {
+		ids[my_id]->unlock();
+	}
+	void Lock::setup() {
+		issetup=true;
+		ids[-1]=new LockStorage;
+	}
+
+}
+
+#endif // PLATFORM check
+
+/*! @file
+* @brief Describes the Thread class and its AutoThread templated subclass
+* @author ejt (Creator)
+*
+* $Author: ejt $
+* $Name: tekkotsu-2_4 $
+* $Revision: 1.6 $
+* $State: Exp $
+* $Date: 2005/08/01 23:17:59 $
+*/
diff -urdN ../Tekkotsu_2.3/IPC/Thread.h ./IPC/Thread.h
--- ../Tekkotsu_2.3/IPC/Thread.h	Wed Dec 31 19:00:00 1969
+++ ./IPC/Thread.h	Mon Aug  1 19:17:59 2005
@@ -0,0 +1,76 @@
+//-*-c++-*-
+#ifndef INCLUDED_Thread_h_
+#define INCLUDED_Thread_h_
+
+#ifdef PLATFORM_APERIOS
+#  warning Thread class is not Aperios compatable
+#else
+
+#include <stddef.h>
+#include <map>
+
+namespace ThreadNS {
+	class Lock {
+	public:
+		Lock();
+		explicit Lock(const Lock& l, bool autolock=true) : my_id(l.my_id) { if(autolock) lock(); }
+		//explicit Lock(int ident, bool autolock=true);
+		~Lock();
+		void lock();
+		bool trylock();
+		void unlock();
+		int getID() const { return my_id; }
+	protected:
+		static std::map<int,struct LockStorage*> ids;
+		static bool issetup;
+		static void setup();
+		int my_id;
+	};	
+}	
+
+//! description of Thread
+class Thread {
+public:
+	typedef ThreadNS::Lock Lock;
+	Thread();
+	virtual ~Thread()=0;
+	
+	virtual void start();
+	virtual void * run();
+	virtual unsigned int runloop() { return -1U; }
+	virtual void stop();
+	virtual void kill();
+	virtual void murder();
+	virtual void * join();
+	virtual bool isRunning() const { return running; }
+	
+protected:
+	virtual void testCancel();
+	static void * launch(void * msg);
+	static void handle_signal(int sig);
+	static void handle_exit(void * th);
+	
+	struct Threadstorage_t * pt;
+	bool running;
+	void * returnValue;
+
+private:
+	Thread(const Thread& r); //!< don't call
+	Thread& operator=(const Thread& r); //!< don't call
+};
+
+#endif //Aperios check
+
+#endif
+
+/*! @file
+* @brief Describes the Thread class and its AutoThread templated subclass
+* @author ejt (Creator)
+*
+* $Author: ejt $
+* $Name: tekkotsu-2_4 $
+* $Revision: 1.4 $
+* $State: Exp $
+* $Date: 2005/08/01 23:17:59 $
+*/
+
diff -urdN ../Tekkotsu_2.3/MMCombo/MMCombo.cc ./MMCombo/MMCombo.cc
--- ../Tekkotsu_2.3/MMCombo/MMCombo.cc	Tue Jan 11 18:10:44 2005
+++ ./MMCombo/MMCombo.cc	Wed Dec 31 19:00:00 1969
@@ -1,782 +0,0 @@
-#include "MMCombo.h"
-#include "Shared/WorldState.h"
-#include "Shared/Profiler.h"
-#include "Shared/debuget.h"
-#include "Shared/Config.h"
-#include "Shared/SharedObject.h"
-#include "Shared/ProcessID.h"
-#include "Events/EventRouter.h"
-#include "Behaviors/BehaviorBase.h"
-#include "Motion/MotionManager.h"
-#include "Motion/Kinematics.h"
-#include "SoundPlay/SoundManager.h"
-#include "Events/DataEvent.h"
-#include "Events/TextMsgEvent.h"
-#include "Events/FilterBankEvent.h"
-#include "Shared/WMclass.h"
-
-#include "Shared/ERS210Info.h"
-#include "Shared/ERS220Info.h"
-#include "Shared/ERS7Info.h"
-
-#include "Shared/ProjectInterface.h"
-
-#include <OPENR/OSyslog.h>
-#include <OPENR/core_macro.h>
-#include <OPENR/OFbkImage.h>
-
-using namespace std;
-
-MMCombo::MMCombo()
-	: OObject(), motmanMemRgn(NULL), worldStateMemRgn(NULL),
-		soundManagerMemRgn(NULL), eventTranslatorQueueMemRgn(NULL),
-		runLevel(0), num_open(0), etrans(), RPOPENR_isready(true), isStopped(true)
-{
-	for(unsigned int i=0; i<NumOutputs; i++) {
-		primIDs[i]=oprimitiveID_UNDEF;
-		open[i]=false;
-	}
-	Profiler::initBuckets();
-}
-
-
-OStatus
-MMCombo::DoInit(const OSystemEvent&)
-{
-	cout << objectName << "::DoInit() " << endl;
-
-	isStopped=false;
-
-	NEW_ALL_SUBJECT_AND_OBSERVER;
-	REGISTER_ALL_ENTRY;
-	SET_ALL_READY_AND_NOTIFY_ENTRY;
-		
-	// make sure the library doesn't drop data "for" us on this reliable communication channel
-	observer[obsReceiveWorldState]->SetBufCtrlParam(0,1,1);
-	observer[obsReceiveMotionManager]->SetBufCtrlParam(0,1,1);
-	observer[obsReceiveSoundManager]->SetBufCtrlParam(0,1,1);
-	observer[obsMotionManagerComm]->SetBufCtrlParam(0,1,MotionManager::MAX_MOTIONS+1);
-	//+1 to MAX_MOTIONS so we can get a delete message after we've filled up
-
-	cout << objectName << ": sbjRegisterWorldState==" << sbjRegisterWorldState << " selector==" << subject[sbjRegisterWorldState]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsReceiveWorldState==" << obsReceiveWorldState << " selector==" << observer[obsReceiveWorldState]->GetID().GetSelector() << '\n'
-			 << objectName << ": sbjRegisterMotionManager==" << sbjRegisterMotionManager << " selector==" << subject[sbjRegisterMotionManager]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsReceiveMotionManager==" << obsReceiveMotionManager << " selector==" << observer[obsReceiveMotionManager]->GetID().GetSelector() << '\n'
-			 << objectName << ": sbjRegisterEventTranslatorQueue==" << sbjRegisterEventTranslatorQueue << " selector==" << subject[sbjRegisterEventTranslatorQueue]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsReceiveEventTranslatorQueue==" << obsReceiveEventTranslatorQueue << " selector==" << observer[obsReceiveEventTranslatorQueue]->GetID().GetSelector() << '\n'
-			 << objectName << ": sbjMoveJoint==" << sbjMoveJoint << " selector==" << subject[sbjMoveJoint]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsSensorFrame==" << obsSensorFrame << " selector==" << observer[obsSensorFrame]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsImage==" << obsImage << " selector==" << observer[obsImage]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsMic==" << obsMic << " selector==" << observer[obsMic]->GetID().GetSelector() << '\n'
-			 << objectName << ": sbjMotionManagerComm==" << sbjMotionManagerComm << " selector==" << subject[sbjMotionManagerComm]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsMotionManagerComm==" << obsMotionManagerComm << " selector==" << observer[obsMotionManagerComm]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsReceiveSoundManager==" << obsReceiveSoundManager << " selector==" << observer[obsReceiveSoundManager]->GetID().GetSelector() << '\n'
-			 << objectName << ": sbjSoundManagerComm==" << sbjSoundManagerComm << " selector==" << subject[sbjSoundManagerComm]->GetID().GetSelector() << '\n'
-			 << objectName << ": sbjRPOPENRSendString==" << sbjRPOPENRSendString << " selector==" << subject[sbjRPOPENRSendString]->GetID().GetSelector() << '\n'
-			 << objectName << ": obsRPOPENRReceiveString==" << obsRPOPENRReceiveString << " selector==" << observer[obsRPOPENRReceiveString]->GetID().GetSelector() << '\n'
-			 << flush;
-
-	if(strcmp(objectName,"MainObj")==0)
-		ProcessID::setID(ProcessID::MainProcess);
-	else if(strcmp(objectName,"MotoObj")==0)
-		ProcessID::setID(ProcessID::MotionProcess);
-		
-	//Read config file
-	config=new Config("/ms/config/tekkotsu.cfg");
-
-	erouter = new EventRouter;
-
-	if(strcmp(objectName,"MainObj")==0) {
-		bool isSlowOutput[NumOutputs];
-		for(unsigned int i=0; i<NumOutputs; i++)
-			isSlowOutput[i]=!IsFastOutput[i];
-
-		SetupOutputs(isSlowOutput);
-
-		//Request power status updates
-		OPowerStatus observationStatus;
-		observationStatus.Set(orsbALL,obsbALL,opsoREMAINING_CAPACITY_NOTIFY_EVERY_CHANGE,opsoTEMPERATURE_NOTIFY_EVERY_CHANGE,opsoTIME_DIF_NOTIFY_EVERY_CHANGE,opsoVOLUME_NOTIFY_EVERY_CHANGE);
-		OServiceEntry entry(myOID_, Extra_Entry[entryGotPowerEvent]);
-		OStatus result = OPENR::ObservePowerStatus(observationStatus, entry);
-		if(result != oSUCCESS) {
-			OSYSLOG1((osyslogERROR, "%s : %s %d","MMCombo::DoStart()","OPENR::ObservePowerStatus() FAILED", result));
-			return oFAIL;
-		}
-		
-    //Setup wireless
-    wireless = new Wireless();
-    sout=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*12);
-    serr=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*4);
-    wireless->setDaemon(sout);
-    wireless->setDaemon(serr);
-		serr->setFlushType(SocketNS::FLUSH_BLOCKING);
-    sout->setTextForward();
-    serr->setForward(sout);
-
-		//worldStateMemRgn -> state setup
-		worldStateMemRgn = InitRegion(sizeof(WorldState));
-		state=new ((WorldState*)worldStateMemRgn->Base()) WorldState;
-
-		//eventTranslatorQueueMemRgn -> etrans setup
-		eventTranslatorQueueMemRgn = InitRegion(sizeof(EventTranslator::Queue_t));
-		EventTranslator::Queue_t * etransq=new ((EventTranslator::Queue_t*)eventTranslatorQueueMemRgn->Base()) EventTranslator::Queue_t;
-		etrans.setQueue(etransq);
-		MotionCommand::setQueue(etransq);
-
-	}
-	if(strcmp(objectName,"MotoObj")==0) {
-		SetupOutputs(IsFastOutput);
-    OPENR::SetMotorPower(opowerON);
-		OPENR::EnableJointGain(oprimitiveID_UNDEF); //oprimitiveID_UNDEF means enable all
-
-    //Setup wireless
-    wireless = new Wireless();
-    sout=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*6);
-    serr=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*2);
-    wireless->setDaemon(sout);
-    wireless->setDaemon(serr);
-		serr->setFlushType(SocketNS::FLUSH_BLOCKING);
-    sout->setTextForward();
-    serr->setForward(sout);
-		
-		//motmanMemRgn -> motman setup
-		motmanMemRgn = InitRegion(sizeof(MotionManager));
-		motman = new (motmanMemRgn->Base()) MotionManager();
-		motman->InitAccess(subject[sbjMotionManagerComm]);
-	}
-	kine = new Kinematics();
-
-	ProjectInterface::startupBehavior.AddReference();
-
-	cout << objectName << "::DoInit()-DONE" << endl;
-	return oSUCCESS;
-}
-
-OStatus
-MMCombo::DoStart(const OSystemEvent&)
-{
-	cout << objectName << "::DoStart() " << endl;
-
-	// initialize the current power status, doesn't always give us
-	// a power update right away otherwise
-	if(strcmp(objectName,"MainObj")==0) {
-		wireless->listen(sout, config->main.console_port);
-		wireless->listen(serr, config->main.stderr_port);
-		OPowerStatus power;
-		OPENR::GetPowerStatus(&power);
-		state->read(power,erouter);
-	}
-
-	if(strcmp(objectName,"MotoObj")==0) {
-		wireless->listen(sout, config->motion.console_port);
-		wireless->listen(serr, config->motion.stderr_port);
-	}
-	
-	isStopped=false;
-
-	ENABLE_ALL_SUBJECT;
-	ASSERT_READY_TO_ALL_OBSERVER;
-
-	addRunLevel();
-	
-	cout << objectName << "::DoStart()-DONE" << endl;
-	return oSUCCESS;
-}
-
-OStatus
-MMCombo::DoStop(const OSystemEvent&)
-{
-	cout << objectName << "::DoStop()..." << endl;
-	if(strcmp(objectName,"MainObj")==0) {
-		ProjectInterface::startupBehavior.DoStop();
-		wireless->close(sout);
-		wireless->close(serr);
-	}
-	DISABLE_ALL_SUBJECT;
-	DEASSERT_READY_TO_ALL_OBSERVER;
-	isStopped=true;
-	cout << objectName << "::DoStop()-DONE" << endl;
-	return oSUCCESS;
-}
-
-OStatus
-MMCombo::DoDestroy(const OSystemEvent&)
-{
-	cout << objectName << "::DoDestroy()..." << endl;
-	ProjectInterface::startupBehavior.RemoveReference();
-	if(strcmp(objectName,"MainObj")==0) {
-		delete erouter;
-		motmanMemRgn->RemoveReference();
-	}
-	if(strcmp(objectName,"MotoObj")==0) {
-		worldStateMemRgn->RemoveReference();
-		eventTranslatorQueueMemRgn->RemoveReference();
-	}
-	soundManagerMemRgn->RemoveReference();
-	DELETE_ALL_SUBJECT_AND_OBSERVER;
-	cout << objectName << "::DoDestroy()-DONE" << endl;
-	return oSUCCESS;
-}
-
-/*! Called when MotoObj is initially ready as well as when it has finished
- *  processing the previous message - we only want to do this the first time
- *  otherwise we infinite loop. */
-void
-MMCombo::ReadyRegisterWorldState(const OReadyEvent&){
-	static bool is_init=true;
-	if(is_init) {
-		is_init=false;
-		cout << objectName << " Registering WorldState" << endl;
-		if(strcmp(objectName,"MainObj")==0) {
-			subject[sbjRegisterWorldState]->SetData(worldStateMemRgn);
-			subject[sbjRegisterWorldState]->NotifyObservers();
-		}
-	}
-}
-
-void
-MMCombo::GotWorldState(const ONotifyEvent& event){
-	cout << objectName << "-GOTWORLDSTATE..." << flush;
-	//	PROFSECTION("GotMemRegion()",state->mainProfile);
-	if(strcmp(objectName,"MotoObj")==0) {
-		ASSERT(event.NumOfData()==1,"Too many WorldStates");
-		worldStateMemRgn = event.RCData(0);
-		worldStateMemRgn->AddReference();
-		state = reinterpret_cast<WorldState*>(worldStateMemRgn->Base());
-	}
-  observer[obsReceiveWorldState]->AssertReady();
-	cout << "done" << endl;
-}
-
-		
-/*! Called when MainObj is initially ready as well as when it has finished
- *  processing the previous message - we only want to do this the first time
- *  otherwise we infinite loop. */
-void
-MMCombo::ReadyRegisterMotionManager(const OReadyEvent&){
-	static bool is_init=true;
-	if(is_init) {
-		is_init=false;
-		cout << objectName << " Registering MotionManager" << endl;
-		if(strcmp(objectName,"MotoObj")==0) {
-			subject[sbjRegisterMotionManager]->SetData(motmanMemRgn);
-			subject[sbjRegisterMotionManager]->NotifyObservers();
-		}
-	}
-}
-
-void
-MMCombo::GotMotionManager(const ONotifyEvent& event){
-	cout << objectName << "-GOTWORLDSTATE..." << flush;
-	//	PROFSECTION("GotMemRegion()",state->motoProfile);
-	if(strcmp(objectName,"MainObj")==0) {
-		ASSERT(event.NumOfData()==1,"Too many MotionManagers");
-		motmanMemRgn = event.RCData(0);
-		motmanMemRgn->AddReference();
-		motman = reinterpret_cast<MotionManager*>(motmanMemRgn->Base());
-		cout << "MAIN INIT MOTMAN..." << flush;
-		//			hexout(event.RCData(event_data_id)->Base(),128);
-		motman->InitAccess(subject[sbjMotionManagerComm]);
-		addRunLevel();
-	}
-  observer[obsReceiveMotionManager]->AssertReady();
-	cout << "done" << endl;
-}
-
-/*! Called when MotoObj is initially ready as well as when it has finished
- *  processing the previous message - we only want to do this the first time
- *  otherwise we infinite loop. */
-void
-MMCombo::ReadyRegisterEventTranslatorQueue(const OReadyEvent&){
-	static bool is_init=true;
-	if(is_init) {
-		is_init=false;
-		cout << objectName << " Registering EventTranslatorQueue" << endl;
-		if(strcmp(objectName,"MainObj")==0) {
-			subject[sbjRegisterEventTranslatorQueue]->SetData(eventTranslatorQueueMemRgn);
-			subject[sbjRegisterEventTranslatorQueue]->NotifyObservers();
-		}
-	}
-}
-
-void
-MMCombo::GotEventTranslatorQueue(const ONotifyEvent& event){
-	cout << objectName << "-GOTEventTranslatorQueue..." << flush;
-	//	PROFSECTION("GotMemRegion()",state->mainProfile);
-	if(strcmp(objectName,"MotoObj")==0) {
-		ASSERT(event.NumOfData()==1,"Too many EventTranslatorQueue");
-		eventTranslatorQueueMemRgn = event.RCData(0);
-		eventTranslatorQueueMemRgn->AddReference();
-		EventTranslator::Queue_t * etransq=reinterpret_cast<EventTranslator::Queue_t*>(eventTranslatorQueueMemRgn->Base());
-		etrans.setQueue(etransq);
-		MotionCommand::setQueue(etransq);
-		//MotionCommands enqueue directly, so there shouldn't be any riff-raff to catch
-		//but just in case, subscribe to everything except erouterEGID
-		for(unsigned int i=0; i<EventBase::numEGIDs; i++)
-			if(i!=EventBase::erouterEGID)
-				erouter->addTrapper(&etrans,static_cast<EventBase::EventGeneratorID_t>(i));
-	}
-  observer[obsReceiveEventTranslatorQueue]->AssertReady();
-	cout << "done" << endl;
-}
-
-		
-void
-MMCombo::ReadySendJoints(const OReadyEvent& sysevent) {
-
-	if(isStopped) {
-		//cout << "BAH!ReadySendJoints" << endl;
-		return;
-	}
-
-	static unsigned int id=-1U;
-	Profiler::Timer timer;
-	if(ProcessID::getID()==ProcessID::MotionProcess) {
-		if(state) {
-			if(id==-1U)
-				id=state->motionProfile.getNewID("ReadySendJoints()");
-			timer.setID(id,&state->motionProfile);
-		}
-	}	else if(ProcessID::getID()==ProcessID::MainProcess) {
-		if(id==-1U)
-			id=state->mainProfile.getNewID("ReadySendJoints()");
-		timer.setID(id,&state->mainProfile);
-	}
-
-	if(num_open==0) //If we don't have any joints to open, leave now. (i.e. MainObj on a 220, has no ears)
-		return;
-
-	// Find an unused command vector
-	RCRegion* rgn=NULL;
-	for (unsigned int i = 0; i < NUM_COMMAND_VECTOR; i++) {
-		if (region[i]->NumberOfReference() == 1) {
-			rgn=region[i];
-			/*			if(strcmp(objectName,"MainObj")==0) {
-							static unsigned int lasttime=get_time();
-							unsigned int thistime=get_time();
-							cout << '*' << i << ' ' << thistime << '\t' << (thistime-lasttime) << endl;
-							lasttime=thistime;
-							}*/
-			break;
-		}
-	}
-	ASSERTRET(rgn!=NULL,"Could not find unused command vector");
-	ASSERTRET(rgn->Base()!=NULL,"Bad Command Vector");
-	OCommandVectorData* cmdVecData = reinterpret_cast<OCommandVectorData*>(rgn->Base());
-	
-	// Update the outputs (note that Main is doing the ears)
-	//I'm using an id compare instead of the slightly more readable strcmp for a tiny bit of speed
-	bool isERS7;
-	if(state!=NULL)
-		isERS7=state->robotDesign&WorldState::ERS7Mask;
-	else {
-		char robotDesignStr[orobotdesignNAME_MAX + 1];
-		memset(robotDesignStr, 0, sizeof(robotDesignStr));
-		if (OPENR::GetRobotDesign(robotDesignStr) != oSUCCESS) {
-			cout << objectName << "::SetupOutputs - OPENR::GetRobotDesign() failed." << endl;
-			return;
-		}
-		isERS7=(strcmp(robotDesignStr,"ERS-7")==0);
-	}		
-	if(ProcessID::getID()==ProcessID::MotionProcess) {
-		float outputs[NumFrames][NumOutputs];
-		if(state!=NULL) {
-			motman->getOutputs(outputs);
-			motman->updatePIDs(primIDs);
-			motman->updateWorldState();
-		} else {
-			for(unsigned int f=0; f<NumFrames; f++)
-				for(unsigned int i=0; i<NumOutputs; i++)
-					outputs[f][i]=0;
-		}
-			
-		// Should be a relatively simple matter to copy angles into commands...
-		unsigned int used=0; //but only copy open joints (so main does ears on 210, motion does everything else)
-		for(unsigned int i=PIDJointOffset; i<PIDJointOffset+NumPIDJoints; i++)
-			if(open[i]) {
-				float cal=config->motion.calibration[i-PIDJointOffset];
-				OJointCommandValue2* jval = reinterpret_cast<OJointCommandValue2*>(cmdVecData->GetData(used)->value);
-				for(unsigned int frame=0; frame<NumFrames; frame++)
-					jval[frame].value = (slongword)(outputs[frame][i]*1e6*cal);
-				used++;
-			}
-		if(isERS7) {
-			// except if it's an ERS-7, we have to use different data structures for some of the leds and the ears
-			for(unsigned int i=LEDOffset; i<ERS7Info::FaceLEDPanelOffset; i++)
-				if(open[i]) {
-					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumFrames; frame++)
-						jval[frame].led = calcLEDValue(i-LEDOffset,outputs[frame][i]);
-					used++;
-				}
-			// for instance, this virtual mode thing, which is global to all the affected LEDs
-			OLED3Mode curMode[NumFrames];
-			for(unsigned int frame=0; frame<NumFrames; frame++)
-				curMode[frame]=(calcLEDValue(ERS7Info::LEDABModeOffset-LEDOffset,sqrt(clipRange01(outputs[frame][ERS7Info::LEDABModeOffset])))==oledON?oled3_MODE_B:oled3_MODE_A);
-			for(unsigned int i=ERS7Info::FaceLEDPanelOffset; i<LEDOffset+NumLEDs; i++)
-				if(open[i]) {
-					OLEDCommandValue3* jval = reinterpret_cast<OLEDCommandValue3*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumFrames; frame++) {
-						jval[frame].intensity = static_cast<sword>(255*clipRange01(outputs[frame][i]));
-						jval[frame].mode=curMode[frame];
-					}
-					used++;
-				}
-			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
-				if(open[i]) {
-					OJointCommandValue4* jval = reinterpret_cast<OJointCommandValue4*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
-						jval[frame].value = (outputs[frame][i]<.5?ojoint4_STATE0:ojoint4_STATE1);
-					used++;
-				}
-		} else {
-			for(unsigned int i=LEDOffset; i<LEDOffset+NumLEDs; i++)
-				if(open[i]) {
-					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumFrames; frame++)
-						jval[frame].led = calcLEDValue(i-LEDOffset,outputs[frame][i]);
-					used++;
-				}
-			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
-				if(open[i]) {
-					OJointCommandValue3* jval = reinterpret_cast<OJointCommandValue3*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
-						jval[frame].value = (outputs[frame][i]<.5?ojoint3_STATE1:ojoint3_STATE0);
-					used++;
-				}
-		}
-	}	else if(ProcessID::getID()==ProcessID::MainProcess) {
-		// Just copy over the current ear state from WorldState
-		unsigned int used=0; //but only copy open joints (so main does ears, motion does everything else)
-		if(isERS7) {
-			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
-				if(open[i]) {
-					OJointCommandValue4* jval = reinterpret_cast<OJointCommandValue4*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
-						jval[frame].value = (state->outputs[i]<.5?ojoint4_STATE0:ojoint4_STATE1);
-					used++;
-				}
-		} else {
-			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
-				if(open[i]) {
-					OJointCommandValue3* jval = reinterpret_cast<OJointCommandValue3*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
-						jval[frame].value = (state->outputs[i]<.5?ojoint3_STATE1:ojoint3_STATE0);
-					used++;
-				}
-		}
-	}
-
-	// Send outputs to system
-	subject[sbjMoveJoint]->SetData(rgn);
-
-	// The first time this is called, we actually need to send *two* buffers
-	// in order to get the double buffering going... (well, actually generalized
-	// for NUM_COMMAND_VECTOR level buffering)
-	static unsigned int initCount=1;
-	if(initCount<NUM_COMMAND_VECTOR) {
-		initCount++;
-		ReadySendJoints(sysevent);
-	} else //recursive base case
-		subject[sbjMoveJoint]->NotifyObservers();
-}
-
-void
-MMCombo::GotSensorFrame(const ONotifyEvent& event){
-	//	if(state && state->buttons[RFrPawOffset])
-	//	cout << "SENSOR..."<<flush;
-	if(isStopped) {
-		//cout << "BAH!GotSensorFrame" << endl;
-		return;
-	}
-
-	PROFSECTION("GotSensorFrame()",state->mainProfile);
-	etrans.translateEvents();
-
-  OSensorFrameVectorData* rawsensor = reinterpret_cast<OSensorFrameVectorData*>(event.RCData(0)->Base());
-	state->read(rawsensor[0],erouter);
-	erouter->processTimers();
-	static unsigned int throwaway=1; //i thought the first few sensor updates might be flakey, but now i think not.  But a good way to delay startup.
-	if(throwaway!=0) {
-		throwaway--;
-		if(throwaway==0)
-			addRunLevel();
-	}
-  observer[obsSensorFrame]->AssertReady();
-	//	if(state && state->buttons[RFrPawOffset])
-	//	cout << "done" << endl;
-}
-
-void
-MMCombo::GotImage(const ONotifyEvent& event){
-	if(isStopped) {
-		//cout << "BAH!GotImage" << endl;
-		return;
-	}
-
-	PROFSECTION("GotImage()",state->mainProfile);
-	etrans.translateEvents();
-
-  erouter->processTimers();
-  
-	WMvari(int, frame_counter, 0);
-	++frame_counter;
-	
-	erouter->postEvent(new DataEvent<const OFbkImageVectorData*>(reinterpret_cast<const OFbkImageVectorData*>(event.Data(0)),EventBase::visOFbkEGID,0,EventBase::statusETID));
-	
-  erouter->processTimers();
-  
-  observer[obsImage]->AssertReady();
-}
-
-void
-MMCombo::GotAudio(const ONotifyEvent& event){
-	if(isStopped) {
-		//cout << "BAH!GotAudio" << endl;
-		return;
-	}
-
-	PROFSECTION("GotAudio()",state->mainProfile);
-	etrans.translateEvents();
-
-	for (int i = 0; i < event.NumOfData(); i++) {
-		erouter->postEvent(new DataEvent<const OSoundVectorData*>(reinterpret_cast<const OSoundVectorData*>(event.Data(i)),EventBase::micOSndEGID,0,EventBase::statusETID));
-		erouter->processTimers();
-	}
-  
-  observer[obsMic]->AssertReady();
-}
-
-void
-MMCombo::GotPowerEvent(void * msg){
-	if(isStopped) {
-		//cout << "BAH!GotPowerEvent" << endl;
-		return;
-	}
-
-	//	cout << "POWER..."<<flush;
-	PROFSECTION("PowerEvent()",state->mainProfile);
-	etrans.translateEvents();
-
-	static bool first=true;
-	if(first) {
-		addRunLevel();
-		first=false;
-	}
-	const OPowerStatus* result = &static_cast<OPowerStatusMessage*>(msg)->powerStatus;
-	state->read(*result,erouter);
-	erouter->processTimers();
-	// this part watches to see if the power button is pressed to shutdown the robot
-	// i'm leaving this low-level because there's not much else you can do anyway...
-	// the hardware kills power to the motors, and as far as we can tell, you can't
-	// turn them back on.
-	if(state->powerFlags[PowerSourceID::PauseSID]) {
-		cout << "%%%%%%%  Pause button was pushed! %%%%%%%" << endl;
-		OBootCondition bc(0);
-		OPENR::Shutdown(bc);
-	}
-	//	cout << "done" << endl;
-}
-
-void
-MMCombo::GotMotionMsg(const ONotifyEvent& event){
-	if(isStopped) {
-		//cout << "BAH!GotMotionMsg" << endl;
-		return;
-	}
-
-	//	cout << "RECEIVE..."<<flush;
-	if(motman!=NULL)
-		motman->receivedMsg(event);
-	else
-		cout << "*** WARNING Main dropping MotionCommand (motman not ready) " << endl;
-	observer[obsMotionManagerComm]->AssertReady();
-	//	cout << "done" << endl;
-}
-
-void
-MMCombo::GotSoundManager(const ONotifyEvent& event) {
-	cout << objectName << "-GOTSOUNDMANAGER..." << flush;
-	//	PROFSECTION("GotMemRegion()",state->mainProfile);
-	ASSERT(event.NumOfData()==1,"Too many SoundManagers");
-	soundManagerMemRgn = event.RCData(0);
-	soundManagerMemRgn->AddReference();
-	sndman = reinterpret_cast<SoundManager*>(soundManagerMemRgn->Base());
-  observer[obsReceiveSoundManager]->AssertReady();
-	sndman->InitAccess(subject[sbjSoundManagerComm]);
-	addRunLevel();
-	cout << "done" << endl;
-}
-
-void
-MMCombo::OpenPrimitives()
-{
-	for(unsigned int i=0; i<NumOutputs; i++)
-		if(open[i]) {
-			OStatus result = OPENR::OpenPrimitive(PrimitiveName[i], &primIDs[i]);
-			if (result != oSUCCESS)
-				OSYSLOG1((osyslogERROR, "%s : %s %d","MMCombo::DoInit()","OPENR::OpenPrimitive() FAILED", result));
-		}
-}
-
-void
-MMCombo::SetupOutputs(const bool to_open[NumOutputs])
-{
-	char robotDesignStr[orobotdesignNAME_MAX + 1];
-	memset(robotDesignStr, 0, sizeof(robotDesignStr));
-	if (OPENR::GetRobotDesign(robotDesignStr) != oSUCCESS) {
-		cout << objectName << "::SetupOutputs - OPENR::GetRobotDesign() failed." << endl;
-		return;
-	} else {
-		if(strcmp(robotDesignStr,"ERS-210")==0) {
-			for(unsigned int j=0; j<NumOutputs; j++)
-				open[j]=to_open[j] && ERS210Info::IsRealERS210[j];
-		} else if(strcmp(robotDesignStr,"ERS-220")==0) {
-			for(unsigned int j=0; j<NumOutputs; j++)
-				open[j]=to_open[j] && ERS220Info::IsRealERS220[j];
-		} else if(strcmp(robotDesignStr,"ERS-7")==0) {
-			for(unsigned int j=0; j<NumOutputs; j++)
-				open[j]=to_open[j] && ERS7Info::IsRealERS7[j];
-		} else {
-			cout << "MMCombo::SetupOutputs - ERROR: Unrecognized model: "<<robotDesignStr<<"\nSorry..."<<endl;
-			return;
-		}
-	}
-	
-	// count how many we're opening
-	for(unsigned int j=0; j<NumOutputs; j++)
-		if(open[j])
-			num_open++;
-
-	if(num_open==0) //If we don't have any joints to open, leave now. (i.e. MainObj on a 220, has no ears, and on ERS-7, all joints are full speed)
-		return;
-
-	OpenPrimitives();
-
-	// request memory regions
-	for (unsigned int i = 0; i < NUM_COMMAND_VECTOR; i++) {
-		MemoryRegionID      cmdVecDataID;
-		OCommandVectorData* cmdVecData;
-		OStatus result = OPENR::NewCommandVectorData(num_open,&cmdVecDataID,&cmdVecData);
-		if (result != oSUCCESS)
-			OSYSLOG1((osyslogERROR, "%s : %s %d","MMCombo::NewCommandVectorData()","OPENR::NewCommandVectorData() FAILED", result));
-		region[i] = new RCRegion(cmdVecData->vectorInfo.memRegionID,cmdVecData->vectorInfo.offset,(void*)cmdVecData,cmdVecData->vectorInfo.totalSize);
-		cmdVecData->SetNumData(num_open);
-
-		// initialize the outputs we just opened
-		unsigned int used=0;
-		ASSERT(cmdVecData==reinterpret_cast<OCommandVectorData*>(region[i]->Base())," should be equal!?");
-		for(unsigned int j=PIDJointOffset; j<PIDJointOffset+NumPIDJoints; j++)
-			if(open[j]) {
-				OCommandInfo* info = cmdVecData->GetInfo(used++);
-				info->Set(odataJOINT_COMMAND2, primIDs[j], NumFrames);
-			}
-		if(strcmp(robotDesignStr,"ERS-7")==0) {
-			// this part's the same as usual, except stop when we get to face leds
-			for(unsigned int j=LEDOffset; j<ERS7Info::FaceLEDPanelOffset; j++)
-				if(open[j]) {
-					OCommandInfo* info = cmdVecData->GetInfo(used);
-					info->Set(odataLED_COMMAND2, primIDs[j], NumFrames);
-					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumFrames; frame++)
-						jval[frame].period = 1;
-					used++;
-				}
-			//we have to use OLEDCommandValue3 on the face and back LEDs if it's an ERS-7
-			for(unsigned int j=ERS7Info::FaceLEDPanelOffset; j<LEDOffset+NumLEDs; j++)
-				if(open[j]) {
-					OCommandInfo* info = cmdVecData->GetInfo(used);
-					info->Set(odataLED_COMMAND3, primIDs[j], NumFrames);
-					OLEDCommandValue3* jval = reinterpret_cast<OLEDCommandValue3*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumFrames; frame++)
-						jval[frame].period = 1;
-					used++;
-				}
-			//also have to use OJointCommandValue4 on the ears now
-			for(unsigned int j=BinJointOffset; j<BinJointOffset+NumBinJoints; j++)
-				if(open[j]) {
-					OCommandInfo* info = cmdVecData->GetInfo(used);
-					info->Set(odataJOINT_COMMAND4, primIDs[j], NumSlowFrames);
-					OJointCommandValue4* jval = reinterpret_cast<OJointCommandValue4*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumFrames; frame++)
-						jval[frame].period = 1;
-					used++;
-				}
-		} else {
-			for(unsigned int j=LEDOffset; j<LEDOffset+NumLEDs; j++)
-				if(open[j]) {
-					OCommandInfo* info = cmdVecData->GetInfo(used);
-					info->Set(odataLED_COMMAND2, primIDs[j], NumFrames);
-					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
-					for(unsigned int frame=0; frame<NumFrames; frame++)
-						jval[frame].period = 1;
-					used++;
-				}
-			for(unsigned int j=BinJointOffset; j<BinJointOffset+NumBinJoints; j++)
-				if(open[j]) {
-					OCommandInfo* info = cmdVecData->GetInfo(used);
-					info->Set(odataJOINT_COMMAND3, primIDs[j], NumSlowFrames);
-					used++;
-				}
-		}
-	}
-}
-
-/*! Will round up size to the nearest page */
-RCRegion*
-MMCombo::InitRegion(unsigned int size) {
-	unsigned int pagesize=4096;
-	sError err=GetPageSize(&pagesize);
-	ASSERT(err==sSUCCESS,"Error "<<err<<" getting page size");
-	unsigned int pages=(size+pagesize-1)/pagesize;
-	return new RCRegion(pages*pagesize);
-}
-
-void
-MMCombo::addRunLevel() {
-	runLevel++;
-	if(runLevel==readyLevel) {
-		cout << "START UP BEHAVIOR..." << flush;
-		ProjectInterface::startupBehavior.DoStart();
-		cout << "START UP BEHAVIOR-DONE" << endl;
-	}
-}
-
-void
-MMCombo::RPOPENR_notify(const ONotifyEvent& event) {
-  const char *buf = (const char *)event.Data(0);
-  observer[event.ObsIndex()]->AssertReady();
-
-  /* usercode: message received
-   * an example could be- */
-  // RPOPENR_send("yeah i received your message", 29);
-
-  /* create TextMsg event which can contain strings
-   * comment this out if you want to handle the received data exclusively
-   */
-  erouter->postEvent(new TextMsgEvent(buf));
-}
-
-int
-MMCombo::RPOPENR_send(char *buf, int bufsize) {
-  if (RPOPENR_isready && bufsize>0) {
-    RPOPENR_isready=false;
-    subject[sbjRPOPENRSendString]->SetData(buf, bufsize);
-    subject[sbjRPOPENRSendString]->NotifyObservers();
-    return bufsize;
-  }
-  return 0;
-}
-
-/*! @file
- * @brief Implements MMCombo, the OObject which "forks" (sort of) into Main and Motion processes
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.62 $
- * $State: Exp $
- * $Date: 2005/01/11 23:10:44 $
- */
-
-
diff -urdN ../Tekkotsu_2.3/MMCombo/MMCombo.h ./MMCombo/MMCombo.h
--- ../Tekkotsu_2.3/MMCombo/MMCombo.h	Tue Sep 28 19:07:04 2004
+++ ./MMCombo/MMCombo.h	Wed Dec 31 19:00:00 1969
@@ -1,155 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_MMCombo_h_
-#define INCLUDED_MMCombo_h_
-
-#include "Shared/debuget.h"
-#include "Shared/RobotInfo.h"
-#include "Wireless/Wireless.h"
-#include "Events/EventTranslator.h"
-
-#include "MMCombo/entry.h"
-#include <OPENR/OObject.h>
-#include <OPENR/OSubject.h>
-#include <OPENR/OObserver.h>
-#include "def.h"
-
-//! Contains code for both MainObj and MotoObj processes
-/*! Why go to all this trouble?  Virtual functions and polymorphism!  Instead
- *  of writing my own object typing and serialization system, I would rather
- *  just use C++'s.  But function lookups of the run time type information (RTTI)
- *  will break unless the object that created the object and the object that's
- *  actually calling the function agree on what object A's information is.
- *
- *  The easiest way to guarantee this is to compile them as one object, and
- *  then replace the strings in the source binary with strings for each of
- *  the final objects so they'll each have their own identity, but share
- *  the same code.
- *
- *  This is as close as I can get to a "fork", which is what i really want.
- */
-class MMCombo : public OObject {
-public:
-	//! constructor
-	MMCombo();
-	virtual ~MMCombo() {} //!< destructor
-	
-	OSubject*    subject[numOfSubject];   //!< holds information for each of our subjects (data we provide)
-	OObserver*   observer[numOfObserver]; //!< holds information for each of the sources we're observing
-	
-	virtual OStatus DoInit   (const OSystemEvent&);      //!< first call (after constructor), set up memory
-	virtual OStatus DoStart  (const OSystemEvent&);      //!< second call, ask for messages
-	virtual OStatus DoStop   (const OSystemEvent&);      //!< next to last call, stop sending and receiving messages
-	virtual OStatus DoDestroy(const OSystemEvent&);      //!< last call (before destructor), clean up memory here
-	
-	void ReadyRegisterWorldState(const OReadyEvent&);    //!< main only, send out the state global
-	void GotWorldState(const ONotifyEvent& event);       //!< motion only, called when state global is received
-	void ReadyRegisterMotionManager(const OReadyEvent&); //!< motion only, send out motman global
-	void GotMotionManager(const ONotifyEvent& event);    //!< main only, called when motman global is received
-	void ReadyRegisterEventTranslatorQueue(const OReadyEvent&);    //!< main only, send out the EventTranslatorQueue
-	void GotEventTranslatorQueue(const ONotifyEvent& event);       //!< motion only, called when EventTranslatorQueue is received
-	
-	void ReadySendJoints(const OReadyEvent& event);      //!< motion only (until main does ears again, then both) calls SendJoints, if DoStart has already been called
-	void GotSensorFrame(const ONotifyEvent& event);      //!< main only, called when new sensor information is available
-	void GotImage(const ONotifyEvent& event);            //!< main only, called when a new image is available
-// paris start
-	void GotAudio(const ONotifyEvent& event);            //!< main only, called when a new audio buffer is available
-// paris end
-	void GotPowerEvent(void * msg);                      //!< main only, called when a power event occurs (can be just status events)
-	
-	void GotMotionMsg(const ONotifyEvent& event);        //!< both, called when a new MotionManagerMsg has been received
-	
-	void GotSoundManager(const ONotifyEvent& event);     //!< both, called when the sndman global is received
-
-  void ListenCont (void* msg) { wireless->ListenCont(msg); }  //!< main only, called when //ALTODO
-  void BindCont   (void* msg) { wireless->BindCont(msg); }    //!< main only, called when //ALTODO
-  void ConnectCont(void* msg) { wireless->ConnectCont(msg); } //!< main only, called when //ALTODO
-  void SendCont   (void* msg) { wireless->SendCont(msg); }    //!< main only, called when //ALTODO
-  void ReceiveCont(void* msg) { wireless->ReceiveCont(msg); } //!< main only, called when //ALTODO
-  void CloseCont  (void* msg) { wireless->CloseCont(msg); }   //!< main only, called when //ALTODO
-
-  bool RPOPENR_isReady() { return RPOPENR_isready; }          //!< main only, called when //ALTODO
-  int RPOPENR_send(char *buf, int bufsize);                   //!< main only, called when //ALTODO
-  
-  void RPOPENR_ready(const OReadyEvent& /*event*/) { RPOPENR_isready=true; } //!< main only, called when //ALTODO
-  void RPOPENR_notify(const ONotifyEvent& event);                            //!< main only, called when //ALTODO
- 
-protected:
-	void OpenPrimitives();                               //!< both, called from SetupOutputs() (mostly for motion, but main does ears), uses #open to tell which to open
-	void SetupOutputs(const bool to_open[NumOutputs]);   //!< both, called from DoInit() (mostly for motion, but main does ears)
-	RCRegion* InitRegion(unsigned int size);             //!< both, called to set up a shared memory region of a given size
-
-  RCRegion * motmanMemRgn;     //!< Motion creates, Main receives
-  RCRegion * worldStateMemRgn; //!< Main creates, Motion receives
-  RCRegion * soundManagerMemRgn; //!< SoundPlay creates, Main & Motion receives
-	RCRegion * eventTranslatorQueueMemRgn; //!< Main creates, Motion (& SoundPlay) receive
-
-	OPrimitiveID primIDs[NumOutputs];    //!< both, Main ears only, Motion the rest
-	static const unsigned int NUM_COMMAND_VECTOR=2; //!< both, for double buffering
-	RCRegion*    region[NUM_COMMAND_VECTOR]; //!< both, the actual buffers
-
-	float  ledActivation[NumLEDs]; //!< Motion, used for partial LED activation
-
-	unsigned int runLevel;           //!< Main, incremented until all sections are ready
-	static const unsigned int readyLevel=5; //!< Main, runLevel at which StartBehavior is created. (1st power event, 1st sensor event, motman init, sndman init, MainObj::DoStart())
-	void addRunLevel();              //!< Main, checks runLevel and creates StartBehavior when ready
-
-	bool open[NumOutputs];    //!< both, holds information regarding which outputs are open in ("controlled by") this process
-	unsigned int num_open;  //!< both, count of how many are open
-
-	EventTranslator etrans; //!< both, allows events to be sent between processes (from other processes besides these two too)
-
-  bool RPOPENR_isready;  //!< true if we've received a ready message from a remote process
-
-	bool isStopped; //!< true if we've received a DoStart and no DoStop - we need this because sometimes an extra message seems to slip in after we've been told to stop, in which case we should ignore it
-
-	//! Motion only, maintains the activation level of the LEDs, returns whether it should be 'fired'
-	inline OLEDValue calcLEDValue(unsigned int i,float x) {
-		if(x<=0.0) {
-			ledActivation[i]*=.9; //decay activation... resets to keeps LEDs in sync, looks a little better
-			return oledOFF;
-		} else if(x>=1.0) {
-			return oledON;
-		} else {
-			x*=x; // squared to "gamma correct" - we can see a single pulse better than a single flicker - after image and all that
-			ledActivation[i]+=x;
-			if(ledActivation[i]>=1.0) {
-				ledActivation[i]-=1.0;
-				return oledON;
-			} else {
-				return oledOFF;
-			}						
-		}
-	}
-
-	//! returns @a f clipped to be between 0 and 1
-	inline static float clipRange01(float f) {
-		if(f>1)
-			return 1;
-		if(f<0)
-			return 0;
-		return f;
-	}
-
-private:
-//	WorldStateSerializer* wstateserializer;
-	MMCombo(const MMCombo&); //!< should never be called...
-	MMCombo& operator=(const MMCombo&); //!< should never be called...
-};
-
-/*! @file
- * @brief Describes MMCombo, the OObject which "forks" (sort of) into Main and Motion processes
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.26 $
- * $State: Exp $
- * $Date: 2004/09/28 23:07:04 $
- */
-
-#endif
-
-
-
-
-
diff -urdN ../Tekkotsu_2.3/MMCombo/MMCombo.ocf ./MMCombo/MMCombo.ocf
--- ../Tekkotsu_2.3/MMCombo/MMCombo.ocf	Fri Nov  1 14:21:29 2002
+++ ./MMCombo/MMCombo.ocf	Wed Dec 31 19:00:00 1969
@@ -1,3 +0,0 @@
-object MMCombo 16384 16384 128 cache notlb kernel
-#as opposed to: object mmcombo 3072 16384 128 cache tlb user
-#if we were using protected memory
diff -urdN ../Tekkotsu_2.3/MMCombo/stub.cfg ./MMCombo/stub.cfg
--- ../Tekkotsu_2.3/MMCombo/stub.cfg	Tue Sep 28 19:07:04 2004
+++ ./MMCombo/stub.cfg	Wed Dec 31 19:00:00 1969
@@ -1,27 +0,0 @@
-ObjectName : MMCombo
-NumOfSubject   : 7
-NumOfObserver  : 9
-Service : "MMCombo.RegisterWorldState.WorldState.S"          , null, ReadyRegisterWorldState()
-Service : "MMCombo.ReceiveWorldState.WorldState.O"           , null, GotWorldState()
-Service : "MMCombo.RegisterMotionManager.MotionManager.S"    , null, ReadyRegisterMotionManager()
-Service : "MMCombo.ReceiveMotionManager.MotionManager.O"     , null, GotMotionManager()
-Service : "MMCombo.RegisterEventTranslatorQueue.EventTranslatorQueue.S"    , null, ReadyRegisterEventTranslatorQueue()
-Service : "MMCombo.ReceiveEventTranslatorQueue.EventTranslatorQueue.O"     , null, GotEventTranslatorQueue()
-Service : "MMCombo.MoveJoint.OCommandVectorData.S"           , null, ReadySendJoints()
-Service : "MMCombo.SensorFrame.OSensorFrameVectorData.O"     , null, GotSensorFrame()
-Service : "MMCombo.Image.OFbkImageVectorData.O"              , null, GotImage()
-Service : "MMCombo.Mic.OSoundVectorData.O"                   , null, GotAudio()
-Service : "MMCombo.MotionManagerComm.MotionManagerMsg.S"     , null, null
-Service : "MMCombo.MotionManagerComm.MotionManagerMsg.O"     , null, GotMotionMsg()
-Service : "MMCombo.ReceiveSoundManager.SoundManager.O"       , null, GotSoundManager()
-Service : "MMCombo.SoundManagerComm.SoundManagerMsg.S"       , null, null
-Service : "MMCombo.RPOPENRSendString.char.S"                   , null, RPOPENR_ready()
-Service : "MMCombo.RPOPENRReceiveString.char.O"                , null, RPOPENR_notify()
-
-Extra : GotPowerEvent()
-Extra : ListenCont()
-Extra : BindCont()
-Extra : ConnectCont()
-Extra : SendCont()
-Extra : ReceiveCont()
-Extra : CloseCont()
diff -urdN ../Tekkotsu_2.3/Makefile ./Makefile
--- ../Tekkotsu_2.3/Makefile	Tue Dec 21 18:53:12 2004
+++ ./Makefile	Sun Aug  7 00:11:02 2005
@@ -1,17 +1,238 @@
 ############### FRAMEWORK MAKEFILE ################
-############# $Name: tekkotsu-2_3 $ ###############
-############### $Revision: 1.30 $ #################
-########## $Date: 2004/12/21 23:53:12 $ ###########
+############# $Name: tekkotsu-2_4 $ ###############
+############### $Revision: 1.33 $ #################
+########## $Date: 2005/08/07 04:11:02 $ ###########
 
+# Make sure the default target is 'all' by listing it first
 all:
-	@echo INSTALLATION INSTRUCTIONS:
-	@cat INSTALL
 
-update install clean allclean:
-	@echo You should be running \'$(MAKE)\' from your project directory...
-	@echo Nothing to be done here.
+
+###################################################
+##             ENVIRONMENT SETUP                 ##
+###################################################
+# Use the default project Environment.conf if none has been
+# specified.  If a project initiated make, it should have
+# defined this variable for us to use its configuration.
+TEKKOTSU_ROOT:=$(shell pwd | sed 's/ /\\ /g')
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEKKOTSU_ROOT)/project/Environment.conf
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+
+
+#############  MAKEFILE VARIABLES  ################
+
+# Would you like some more compiler flags?  We like lots of warnings.
+# There are some files with exceptions to these flags - MMCombo*.cc
+# need to have optimizations turned off, and several TinyFTPD sources
+# have -Weffc++ and -DOPENR_DEBUG turned off.  If you want to modify
+# these exceptions, look in the middle of the 'Makefile Machinery'
+# section. (grep/search for the file name)
+
+ifeq ($(TEKKOTSU_TARGET_PLATFORM),PLATFORM_APERIOS)
+  PLATFORM_FLAGS= \
+	  -isystem $(OPENRSDK_ROOT)/OPEN_R/include/MCOOP \
+	  -isystem $(OPENRSDK_ROOT)/OPEN_R/include/R4000 \
+	  -isystem $(OPENRSDK_ROOT)/OPEN_R/include \
+	  -isystem aperios/include \
+	  $(if $(TEKKOTSU_DEBUG),-DOPENR_DEBUG,) \
+	  `aperios/bin/xml2-config --cflags`
+else
+  PLATFORM_FLAGS=`xml2-config --cflags`
+endif
+
+CXXFLAGS= \
+	$(if $(TEKKOTSU_DEBUG),-g -fno-inline -DDEBUG,) \
+	$(if $(TEKKOTSU_DEBUG),,-O2 -frename-registers -fomit-frame-pointer) \
+	-pipe -ffast-math -fno-common \
+	-Wall -W -Wshadow -Wlarger-than-8192 -Wpointer-arith -Wcast-qual \
+	-Woverloaded-virtual -Weffc++ -Wdeprecated -Wnon-virtual-dtor \
+	-I$(TEKKOTSU_ROOT) -I$(TEKKOTSU_ROOT)/Motion/roboop \
+	-I$(TEKKOTSU_ROOT)/Shared/newmat \
+	-D$(TEKKOTSU_TARGET_PLATFORM)  -D$(TEKKOTSU_TARGET_MODEL) \
+	$(PLATFORM_FLAGS)
+
+INCLUDE_PCH=$(if $(TEKKOTSU_PCH),-include $(TK_BD)/$(TEKKOTSU_PCH))
+
+
+###################################################
+##              SOURCE CODE LIST                 ##
+###################################################
+
+# Find all of the source files: (except temp files in build directory)
+# You shouldn't need to change anything here unless you want to add
+# external libraries or new directories for the search
+SRCSUFFIX:=.cc
+SRC_DIRS:=Behaviors Events IPC Motion Shared Sound Vision Wireless
+SRCS:=$(shell find $(SRC_DIRS) -name "*$(SRCSUFFIX)")
+
+# We should also make sure these libraries are ready to go
+# Note we've been lucky that these libraries happen to use a different
+# source suffix, so we don't have to filter them out of SRCS
+USERLIBS:= Motion/roboop \
+           Shared/newmat \
+
+
+###################################################
+##             MAKEFILE MACHINERY                ##
+###################################################
+# Hopefully, you shouldn't have to change anything down here...
+
+.PHONY: all compile clean cleanDeps reportTarget docs dox doc alldocs cleanDoc updateLibs $(USERLIBS) tools platformBuild update install
+
+all:
+	@echo "Running $(MAKE) from the root directory will first build the"
+	@echo "Tekkotsu library for Aperios (AIBO), and then for the local"
+	@echo "platform.  The Environment.conf from the template project"
+	@echo "directory will be used, which currently contains:"
+	@echo "";
+	@echo "  Target model: $(TEKKOTSU_TARGET_MODEL)"
+	@echo "  Build directory: $(TEKKOTSU_BUILDDIR)"
+	@echo "";
+	@echo "You will want to run make from your project directory in order"
+	@echo "to produce executables..."
+	@echo ""
+	export TEKKOTSU_TARGET_PLATFORM=PLATFORM_APERIOS; \
+	$(MAKE) compile
+	export TEKKOTSU_TARGET_PLATFORM=PLATFORM_LOCAL; \
+	$(MAKE) compile
+	@echo "Build successful."
+
+update install:
+	@echo "You probably want to be running make from within your project's directory"
+	@echo "You can run $(MAKE) from within the root Tekkotsu directory to build"
+	@echo "libtekkotsu.a for both Aperios and the host platform, which will then"
+	@echo "be linked against by the projects and tools."
+	@echo "However, only a project can install or update to memory stick."
+	@echo "You can use the template project directory if you want to build a stick"
+	@echo "with the standard demo behaviors."
+
+# Don't want to try to remake this - give an error if not found
+$(TEKKOTSU_ROOT)/project/Environment.conf:
+	@echo "Could not find Environment file - check the default project directory still exists"
+	@exit 1
+
+# The object file for each of the source files
+OBJS:=$(addprefix $(TK_BD)/,$(SRCS:$(SRCSUFFIX)=.o))
+
+# list of all source files of all components, sorted to remove
+# duplicates.  This gives us all the source files which we care about,
+# all in one place.
+DEPENDS:=$(addprefix $(TK_BD)/,$(SRCS:$(SRCSUFFIX)=.d) $(addsuffix .d,$(TEKKOTSU_PCH)))
+
+
+ifeq ($(TEKKOTSU_TARGET_PLATFORM),PLATFORM_APERIOS)
+include aperios/Makefile.aperios
+else
+include local/Makefile.local
+endif
+
+%.gch:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst $(TK_BD)/%,%,$*); \
+	echo "Pre-compiling $$src..."; \
+	$(CXX) $(CXXFLAGS) -x c++-header -c $$src -o $@ > $*.log 2>&1; \
+        retval=$$?; \
+        cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+        test $$retval -eq 0;
+
+%.d:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.d,%.cc,$(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$@)); \
+	if [ ! -f "$$src" ] ; then \
+		echo "Generating source file '$$src'"; \
+		$(MAKE) "$$src" ; \
+	fi; \
+	echo "$@..." | sed 's@.*$(TK_BD)/@Generating @'; \
+	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
+
+$(TK_BD)/$(TEKKOTSU_PCH).d:
+	@mkdir -p $(dir $@)
+	@src=$(TEKKOTSU_PCH); \
+	echo "$@..." | sed 's@.*$(TK_BD)/@Generating @'; \
+	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.gch)" -MM "$$src" > $@
+
+ifneq ($(MAKECMDGOALS),)
+ifeq ($(filter clean% docs dox doc alldocs,$(MAKECMDGOALS)),)
+-include $(DEPENDS)
+ifeq ($(TEKKOTSU_TARGET_PLATFORM),PLATFORM_APERIOS)
+-include $(TK_BD)/aperios/aperios.d
+endif
+endif
+endif
+
+compile: tools reportTarget updateLibs platformBuild
+
+tools:
+	@$(MAKE) -C tools
 
 dox docs doc:
 	docs/builddocs --update --tree --search --detailed
 
-.PHONY: all update install dox docs doc
\ No newline at end of file
+alldocs:
+	docs/builddocs --update --all --tree --search --detailed
+
+reportTarget:
+	@echo " ** Targeting $(TEKKOTSU_TARGET_MODEL) for build on $(TEKKOTSU_TARGET_PLATFORM) ** ";
+	@echo " ** TEKKOTSU_DEBUG is $(if $(TEKKOTSU_DEBUG),ON ,OFF) ** ";
+
+updateLibs: $(USERLIBS)
+
+$(USERLIBS):
+	@echo "$@:"; \
+	export TEKKOTSU_ENVIRONMENT_CONFIGURATION="$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)"; \
+	$(MAKE) -C "$@"
+
+$(TK_BD)/libtekkotsu.a: $(OBJS)
+	@echo "Linking object files..."
+	@printf "$@ <- "; echo "[...]" | sed 's@$(TK_BD)/@@g';
+	@rm -f $@;
+	@$(AR) $@ $(OBJS);
+	@$(AR2) $@
+
+%.h :
+	@if [ "$(notdir $@)" = "def.h" -o "$(notdir $@)" = "entry.h" ] ; then \
+		echo "WARNING: You shouldn't be seeing this message.  Report that you did." ; \
+		echo "         Try a clean recompile." ; \
+	fi;
+	@echo "ERROR: Seems to be a missing header file '$@'...";
+	@echo "       Someone probably forgot to check a file into CVS.";
+	@echo "       I'll try to find where it's being included from:";
+	@find . -name "*.h" -exec grep -H "$(notdir $@)" \{\} \; ;
+	@find . -name "*.cc" -exec grep -H "$(notdir $@)" \{\} \; ;
+	@echo "";
+	@echo "You might need to rebuild the dependancy files ('make cleanDeps') to get rid of this error.";
+	@exit 1
+
+#don't try to make random files via this implicit chain
+%:: %.o ;
+
+%.o: $(if $(TEKKOTSU_PCH),$(TK_BD)/$(TEKKOTSU_PCH).gch)
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(TK_BD)/%,%,$@)); \
+	echo "Compiling $$src..."; \
+	$(CXX) $(CXXFLAGS) $(INCLUDE_PCH) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0;
+
+clean:
+	@printf "Cleaning all ~ files corresponding to .cc files..."
+	@rm -f $(addsuffix ~,$(SRCS)) $(SRCS:$(SRCSUFFIX)=.h~)
+	@printf "done.\n"
+	rm -rf $(TEKKOTSU_BUILDDIR)
+	(cd $(TEKKOTSU_ROOT)/tools && $(MAKE) clean);
+	for dir in `ls aperios` ; do \
+		if [ "$$dir" = "CVS" ] ; then continue; fi; \
+		if [ -f "aperios/$$dir" ] ; then continue; fi; \
+		rm -f "aperios/$$dir/$${dir}Stub."{h,cc} "aperios/$$dir/def.h" "aperios/$$dir/entry.h" ; \
+	done
+
+cleanDeps:
+	@printf "Cleaning all .d files from build directory..."
+	@find "$(TK_BD)/../.." -name "*.d" -exec rm \{\} \;
+	@printf "done.\n"
+
+cleanDoc:
+	docs/builddocs --clean
+
+
+
diff -urdN ../Tekkotsu_2.3/Motion/CVS/Entries ./Motion/CVS/Entries
--- ../Tekkotsu_2.3/Motion/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Motion/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,44 @@
+/DynamicMotionSequence.h/1.8/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/EmergencyStopMC.cc/1.26/Mon Jun  6 18:30:19 2005//Ttekkotsu-2_4
+/EmergencyStopMC.h/1.12/Fri Jan  7 19:36:38 2005//Ttekkotsu-2_4
+/Geometry.h/1.3/Thu Sep 25 15:27:22 2003//Ttekkotsu-2_4
+/HeadPointerMC.cc/1.19/Tue Jan 25 20:06:42 2005//Ttekkotsu-2_4
+/HeadPointerMC.h/1.20/Fri Jan  7 21:13:31 2005//Ttekkotsu-2_4
+/Kinematics.cc/1.24/Wed Jun  1 05:47:47 2005//Ttekkotsu-2_4
+/Kinematics.h/1.31/Fri Jan 14 21:20:05 2005//Ttekkotsu-2_4
+/LedEngine.cc/1.15/Sun Sep 12 04:22:37 2004//Ttekkotsu-2_4
+/LedEngine.h/1.20/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/LedMC.h/1.8/Fri Dec 17 05:52:36 2004//Ttekkotsu-2_4
+/MMAccessor.h/1.11/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/MotionCommand.cc/1.4/Wed Jun 29 22:04:51 2005//Ttekkotsu-2_4
+/MotionCommand.h/1.19/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/MotionManager.cc/1.43/Wed Jun 29 22:04:51 2005//Ttekkotsu-2_4
+/MotionManager.h/1.27/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/MotionManagerMsg.h/1.4/Tue Sep  2 20:58:49 2003//Ttekkotsu-2_4
+/MotionSequenceEngine.cc/1.9/Thu Jul 14 17:09:03 2005//Ttekkotsu-2_4
+/MotionSequenceEngine.h/1.13/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/MotionSequenceMC.h/1.28/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/OldHeadPointerMC.cc/1.1/Thu Oct 14 20:23:50 2004//Ttekkotsu-2_4
+/OldHeadPointerMC.h/1.2/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/OldKinematics.cc/1.1/Thu Aug  5 20:29:04 2004//Ttekkotsu-2_4
+/OldKinematics.h/1.1/Thu Aug  5 20:29:04 2004//Ttekkotsu-2_4
+/OutputCmd.cc/1.2/Tue Jan  4 19:51:41 2005//Ttekkotsu-2_4
+/OutputCmd.h/1.3/Sun Sep  7 22:14:01 2003//Ttekkotsu-2_4
+/OutputPID.h/1.5/Sat Dec 13 05:01:40 2003//Ttekkotsu-2_4
+/PIDMC.h/1.12/Tue Dec 21 00:42:21 2004//Ttekkotsu-2_4
+/Path.h/1.5/Thu Sep 25 15:27:23 2003//Ttekkotsu-2_4
+/PostureEngine.cc/1.24/Fri Jan  7 19:36:38 2005//Ttekkotsu-2_4
+/PostureEngine.h/1.16/Fri Jan  7 19:36:38 2005//Ttekkotsu-2_4
+/PostureMC.cc/1.2/Fri Jan  7 21:12:35 2005//Ttekkotsu-2_4
+/PostureMC.h/1.13/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/RemoteControllerMC.h/1.5/Tue Dec 21 00:42:21 2004//Ttekkotsu-2_4
+/Spline.h/1.5/Thu Sep 25 15:27:23 2003//Ttekkotsu-2_4
+/TailWagMC.h/1.8/Wed Apr  6 20:36:00 2005//Ttekkotsu-2_4
+/UPennWalkMC.cc/1.1/Tue Apr 12 21:33:31 2005//Ttekkotsu-2_4
+/UPennWalkMC.h/1.3/Tue Apr 12 22:18:34 2005//Ttekkotsu-2_4
+/WalkMC.cc/1.34/Wed Jun 29 22:01:55 2005//Ttekkotsu-2_4
+/WalkMC.h/1.31/Tue Apr 12 19:07:07 2005//Ttekkotsu-2_4
+/WaypointEngine.h/1.9/Tue Aug  9 23:00:50 2005//Ttekkotsu-2_4
+/WaypointWalkMC.h/1.4/Wed Jun  1 05:47:48 2005//Ttekkotsu-2_4
+/gvector.h/1.5/Thu Sep 25 15:27:23 2003//Ttekkotsu-2_4
+D/roboop////
diff -urdN ../Tekkotsu_2.3/Motion/CVS/Repository ./Motion/CVS/Repository
--- ../Tekkotsu_2.3/Motion/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Motion/CVS/Repository	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+Tekkotsu/Motion
diff -urdN ../Tekkotsu_2.3/Motion/CVS/Root ./Motion/CVS/Root
--- ../Tekkotsu_2.3/Motion/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Motion/CVS/Root	Wed Aug 10 11:03:18 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Motion/CVS/Tag ./Motion/CVS/Tag
--- ../Tekkotsu_2.3/Motion/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Motion/CVS/Tag	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Motion/DynamicMotionSequence.h ./Motion/DynamicMotionSequence.h
--- ../Tekkotsu_2.3/Motion/DynamicMotionSequence.h	Tue Dec 21 17:39:01 2004
+++ ./Motion/DynamicMotionSequence.h	Sun Aug  7 00:11:03 2005
@@ -4,7 +4,9 @@
 
 #include "MotionSequenceEngine.h"
 #include "MotionCommand.h"
+#include "MotionManager.h"
 #include <vector>
+#include "MotionManager.h"
 
 //! Uses STL's vector for dynamic memory allocation - don't use this as a motion command, pointers in shared memory regions can be invalid in other processes
 /*! See MotionSequenceEngine for documentation on its members */
@@ -13,7 +15,7 @@
 	//!constructor
 	DynamicMotionSequence() : MotionCommand(), MotionSequenceEngine(), moves(), erased() {clear();}
 	//!constructor, loads from a file and then resets the playtime to beginning and begins to play
-	explicit DynamicMotionSequence(const char* filename) : MotionCommand(), MotionSequenceEngine(), moves(), erased() {clear();LoadFile(filename);setPlayTime(1);}
+	explicit DynamicMotionSequence(const char* filename) : MotionCommand(), MotionSequenceEngine(), moves(), erased() {clear();LoadFile(filename);setTime(1);}
 	//!destructor
 	virtual ~DynamicMotionSequence() {}
 
@@ -70,7 +72,7 @@
 			prevs[i]=starts[i]=moves.size()-1;
 			nexts[i]=invalid_move;
 		}
-		setPlayTime(1);
+		setTime(1);
 	}
 	virtual unsigned int getMaxFrames() const { return -1U; }
 	virtual unsigned int getUsedFrames() const { return moves.size()-erased.size(); }
@@ -83,8 +85,8 @@
 	list_t moves;                     //!< stores all of the movement keyframes
 	std::vector<Move_idx_t> erased;   //!< recycles erased keyframes, can't just shift elements in #moves, it would throw of index numbers in Move structures
 
-	virtual Move& getKeyFrame(Move_idx_t x) { return moves[x]; }
-	virtual const Move& getKeyFrame(Move_idx_t x) const { return moves[x]; }
+	virtual Move& getKeyFrame(Move_idx_t x) { return moves[x]; } //!< returns #moves[@a x]
+	virtual const Move& getKeyFrame(Move_idx_t x) const { return moves[x]; } //!< returns #moves[@a x]
 	virtual Move_idx_t newKeyFrame() {
 		if(erased.empty()) {
 			moves.push_back(Move());
@@ -95,7 +97,9 @@
 			return x;
 		}
 	}
+	//! marks keyframe @a x unused
 	virtual void eraseKeyFrame(Move_idx_t x) { erased.push_back(x); }
+	//! advances (or rewinds) @a prev and @a next so that @a t falls between them
 	void setRange(unsigned int t,Move_idx_t& prev, Move_idx_t& next) const {
 		if(next!=invalid_move && moves[next].starttime<=t) {
 			do {
@@ -116,10 +120,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/12/21 22:39:01 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/EmergencyStopMC.cc ./Motion/EmergencyStopMC.cc
--- ../Tekkotsu_2.3/Motion/EmergencyStopMC.cc	Fri Jan  7 18:16:58 2005
+++ ./Motion/EmergencyStopMC.cc	Mon Jun  6 14:30:19 2005
@@ -2,7 +2,7 @@
 #include "Shared/WorldState.h"
 #include "Shared/get_time.h"
 #include "Motion/MotionManager.h"
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 #include "Shared/Config.h"
 #include "Events/EventRouter.h"
 #include "Shared/ERS210Info.h"
@@ -63,6 +63,8 @@
 			piddutyavgs[i]=piddutyavgs[i]*.9f+state->pidduties[i]*.1f;
 			//reset if there's something significantly out of place (perhaps we're being overridden)
 			if(fabsf(state->outputs[PIDJointOffset+i]-cmds[PIDJointOffset+i].value)>.15f) {
+				//if(PIDJointOffset+i==LFrLegOffset+RotatorOffset)
+				//cout << "resetting from " << cmds[PIDJointOffset+i].value << " to " << state->outputs[PIDJointOffset+i] << endl;
 				curPositions[PIDJointOffset+i]=cmds[PIDJointOffset+i].value=state->outputs[PIDJointOffset+i];
 				dirty=true;
 				targetReached=false;
@@ -209,9 +211,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.24 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.26 $
  * $State: Exp $
- * $Date: 2005/01/07 23:16:58 $
+ * $Date: 2005/06/06 18:30:19 $
  */
 
diff -urdN ../Tekkotsu_2.3/Motion/EmergencyStopMC.h ./Motion/EmergencyStopMC.h
--- ../Tekkotsu_2.3/Motion/EmergencyStopMC.h	Fri Jan  7 14:36:38 2005
+++ ./Motion/EmergencyStopMC.h	Fri Jan  7 14:36:38 2005
@@ -59,7 +59,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.12 $
  * $State: Exp $
  * $Date: 2005/01/07 19:36:38 $
diff -urdN ../Tekkotsu_2.3/Motion/Geometry.h ./Motion/Geometry.h
--- ../Tekkotsu_2.3/Motion/Geometry.h	Thu Sep 25 11:27:22 2003
+++ ./Motion/Geometry.h	Thu Sep 25 11:27:22 2003
@@ -51,7 +51,7 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Rel $
  * $Date: 2003/09/25 15:27:22 $
diff -urdN ../Tekkotsu_2.3/Motion/HeadPointerMC.cc ./Motion/HeadPointerMC.cc
--- ../Tekkotsu_2.3/Motion/HeadPointerMC.cc	Tue Jan 25 15:06:42 2005
+++ ./Motion/HeadPointerMC.cc	Tue Jan 25 15:06:42 2005
@@ -168,7 +168,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.19 $
  * $State: Exp $
  * $Date: 2005/01/25 20:06:42 $
diff -urdN ../Tekkotsu_2.3/Motion/HeadPointerMC.h ./Motion/HeadPointerMC.h
--- ../Tekkotsu_2.3/Motion/HeadPointerMC.h	Fri Jan  7 16:13:31 2005
+++ ./Motion/HeadPointerMC.h	Fri Jan  7 16:13:31 2005
@@ -163,7 +163,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.20 $
  * $State: Exp $
  * $Date: 2005/01/07 21:13:31 $
diff -urdN ../Tekkotsu_2.3/Motion/Kinematics.cc ./Motion/Kinematics.cc
--- ../Tekkotsu_2.3/Motion/Kinematics.cc	Tue Dec 21 18:51:18 2004
+++ ./Motion/Kinematics.cc	Wed Jun  1 01:47:47 2005
@@ -4,6 +4,7 @@
 #include "roboop/config.h"
 #include "Shared/WorldState.h"
 #include <sstream>
+#include "local/sim/Process.h"
 
 using namespace std;
 
@@ -413,9 +414,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.23 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.24 $
  * $State: Exp $
- * $Date: 2004/12/21 23:51:18 $
+ * $Date: 2005/06/01 05:47:47 $
  */
 
diff -urdN ../Tekkotsu_2.3/Motion/Kinematics.h ./Motion/Kinematics.h
--- ../Tekkotsu_2.3/Motion/Kinematics.h	Fri Jan 14 16:20:05 2005
+++ ./Motion/Kinematics.h	Fri Jan 14 16:20:05 2005
@@ -350,7 +350,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.31 $
  * $State: Exp $
  * $Date: 2005/01/14 21:20:05 $
diff -urdN ../Tekkotsu_2.3/Motion/LedEngine.cc ./Motion/LedEngine.cc
--- ../Tekkotsu_2.3/Motion/LedEngine.cc	Sun Sep 12 00:22:37 2004
+++ ./Motion/LedEngine.cc	Sun Sep 12 00:22:37 2004
@@ -392,7 +392,7 @@
  * @author ejt (Creator)
  *
  * $Author: dst $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.15 $
  * $State: Exp $
  * $Date: 2004/09/12 04:22:37 $
diff -urdN ../Tekkotsu_2.3/Motion/LedEngine.h ./Motion/LedEngine.h
--- ../Tekkotsu_2.3/Motion/LedEngine.h	Thu Jan 20 18:18:25 2005
+++ ./Motion/LedEngine.h	Sun Aug  7 00:11:03 2005
@@ -93,7 +93,7 @@
 	static const LEDBitMask_t ERS7numMasks[11]; //!< writes a number on the display
 	//!Use these to specify a style for displaying numbers using displayNumber()
 	enum numStyle_t {
-		onedigit, //!< can display a number -9 thru 9, using #numMask.  For negative numbers, blinks the top bar - fast if it's supposed to be on, slow if it would otherwise be off
+		onedigit, //!< can display a number -9 thru 9, using the current robot model's numMask.  For negative numbers, blinks the top bar - fast if it's supposed to be on, slow if it would otherwise be off
 		twodigit  //!< can display a number -99 thru 99, using setOneOfTwo().  For negative numbers, sets the top bar to 1 (off otherwise).
 	};
 	//!Use these to specify a style for displaying a percentage value [0-1] using displayPercent()
@@ -149,7 +149,7 @@
 		else
 			return infos[i].value;
 	}
-	//!used by displayNumber() to determine settings of LEDs when using #numStyle_t::twodigit
+	//!used by displayNumber() to determine settings of LEDs when using numStyle_t::twodigit
 	void setOneOfTwo(unsigned int x, unsigned int low, unsigned int mid, unsigned int high);
 	//!used by displayPercent() to determine settings of LEDs
 	void setColumn(float x, unsigned int low, unsigned int mid, unsigned int high, unsigned int top);
@@ -177,10 +177,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.19 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.20 $
  * $State: Exp $
- * $Date: 2005/01/20 23:18:25 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/LedMC.h ./Motion/LedMC.h
--- ../Tekkotsu_2.3/Motion/LedMC.h	Fri Dec 17 00:52:36 2004
+++ ./Motion/LedMC.h	Fri Dec 17 00:52:36 2004
@@ -62,7 +62,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Exp $
  * $Date: 2004/12/17 05:52:36 $
diff -urdN ../Tekkotsu_2.3/Motion/MCList.make ./Motion/MCList.make
--- ../Tekkotsu_2.3/Motion/MCList.make	Mon Sep 30 14:19:49 2002
+++ ./Motion/MCList.make	Wed Dec 31 19:00:00 1969
@@ -1,14 +0,0 @@
-MC_SOURCES = 	\
-	../Motion/JointCmd.cc \
-	../Motion/MotionManager.cc \
-	../Motion/MCRegistrar.cc \
-	../Motion/Registerable.cc \
-	../Motion/MotionCommands/EmergencyStopMC.cc \
-	../Motion/MotionCommands/WalkMC.cc \
-	../Motion/Kinematics.cc \
-	../Motion/LedEngine.cc \
-	../Motion/PostureEngine.cc \
-	../Motion/MotionCommands/HeadPointerMC.cc \
-
-
-
diff -urdN ../Tekkotsu_2.3/Motion/MMAccessor.h ./Motion/MMAccessor.h
--- ../Tekkotsu_2.3/Motion/MMAccessor.h	Wed Feb 18 16:13:02 2004
+++ ./Motion/MMAccessor.h	Sun Aug  7 00:11:03 2005
@@ -60,7 +60,7 @@
 	}
 
 	//! constructor, allows objects to provide uniform access to MotionCommands, regardless of whether they are currently in the MotionManager
-	MMAccessor(MotionCommand * ptr) : mc_id(invalid_MC_ID), checkOutCnt(0), mcptr(ptr) {}
+	MMAccessor(MotionCommand * ptr) : mc_id(MotionManager::invalid_MC_ID), checkOutCnt(0), mcptr(ptr) {}
 
 	//! copy constructor - will reference the same mc_id - checkin/checkouts are independent between this and @a a; however, if @a a is checkout out, @c this will check itself out as well
 	MMAccessor(const MMAccessor& a) : mc_id(a.mc_id), checkOutCnt(0), mcptr(a.mcptr) {
@@ -129,7 +129,7 @@
 	 *  MMAccessor<myMC> mine(myMC_id);
 	 *  if(mine.checkin(mine.mc()->foo()))
 	 *    //do something with motman here
-	 *  @endcode*/
+	 *  @endcode */
 	template<class Ret_t> Ret_t checkin(Ret_t ret) {
 		checkin();
 		return ret;
@@ -153,10 +153,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/02/18 21:13:02 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/MotionCommand.cc ./Motion/MotionCommand.cc
--- ../Tekkotsu_2.3/Motion/MotionCommand.cc	Thu Sep 25 11:27:23 2003
+++ ./Motion/MotionCommand.cc	Wed Jun 29 18:04:51 2005
@@ -1,15 +1,28 @@
 #include "MotionCommand.h"
+#include "Events/EventTranslator.h"
+#include "Events/EventRouter.h"
+#include <iostream>
+
+using namespace std;
+
+void MotionCommand::postEvent(const EventBase& event) {
+	if(queue==NULL) {
+		erouter->postEvent(event.clone());
+	} else {
+		queue->encodeEvent(event);
+	}
+}
+
 
-EventTranslator::Queue_t * MotionCommand::queue=NULL;
 
 /*! @file
- * @brief Declares the static MotionCommand::queue variable, that's all
+ * @brief Empty
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/09/25 15:27:23 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:04:51 $
  */
 
diff -urdN ../Tekkotsu_2.3/Motion/MotionCommand.h ./Motion/MotionCommand.h
--- ../Tekkotsu_2.3/Motion/MotionCommand.h	Mon Feb  9 17:45:28 2004
+++ ./Motion/MotionCommand.h	Sun Aug  7 00:11:03 2005
@@ -4,8 +4,11 @@
 
 #include "Shared/RobotInfo.h"
 #include "MotionManagerMsg.h"
-#include "Events/EventTranslator.h"
 #include "OutputCmd.h"
+#include <stddef.h>
+
+class EventTranslator;
+class EventBase;
 
 //! The abstract base class for motions, provides common interface.  All motions should inherit from this
 /*! For instructions on how to create:
@@ -49,10 +52,10 @@
  * inherit it.
  *
  * MotionCommands which generate events should use the inherited
- * postEvent() instead of trying to access a global #erouter - the
+ * postEvent() instead of trying to access a global ::erouter - the
  * inherited version will properly handle sending the events
  * regardless of the current context, but trying to access a
- * non-shared global like #erouter could cause problems.
+ * non-shared global like ::erouter could cause problems.
  *
  * @warning <b>Be careful what you call in MotionManager</b> \n
  * Some functions are marked MotionCommand-safe - this is another
@@ -113,7 +116,7 @@
 	//        ******************
 
 	//! Constructor: Defaults to kStdPriority and autoprune==true
-	MotionCommand() : MotionManagerMsg(), autoprune(true), started(false) {}
+	MotionCommand() : MotionManagerMsg(), queue(NULL), autoprune(true), started(false) {}
 	//! Destructor
 	virtual ~MotionCommand() {}
 	
@@ -137,8 +140,8 @@
 	virtual bool shouldPrune() { return (autoprune && !isAlive()); }
 	
 	//! only called from MMCombo during process setup, allows MotionCommands to send events
-	static void setQueue(EventTranslator::Queue_t * q) { queue=q; }
-	
+	void setTranslator(EventTranslator * q) { queue=q; }
+
 protected:
 	//! this utility function will probably be of use to a lot of MotionCommand's
 	/*! Does a weighted average of a and b, favoring b by x percent (so x==0 results in a, x==1 results in b)
@@ -171,14 +174,17 @@
 	}
 	//@}
 
-	//! calls EventTranslator::enqueue directly (avoids needing erouter, which is a non-shared global, causes problems with context, grr, silly OS)
-	static void postEvent(const EventBase& event) { EventTranslator::enqueue(event,queue); }
+	//! calls EventTranslator::trapEvent() directly (avoids needing erouter, which is a non-shared global, causes problems with context, grr, silly OS)
+	void postEvent(const EventBase& event);
 
-	static EventTranslator::Queue_t * queue; //!< queue to store outgoing events in - call the MotionCommand::postEvent
+	EventTranslator * queue; //!< send events using this, instead of posting to the erouter
 
 	int autoprune; //!< default true, autoprune setting, if this is true and isAlive() returns false, MotionManager will attempt to remove the MC automatically
 	bool started; //!< true if the MotionCommand is currently running (although it may be overridden by a higher priority MotionCommand)
 
+private:
+	MotionCommand(const MotionCommand&); //!< don't call
+	MotionCommand& operator=(const MotionCommand&); //!< don't call
 };
 
 /*! @file
@@ -186,10 +192,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.17 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.19 $
  * $State: Exp $
- * $Date: 2004/02/09 22:45:28 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/MotionManager.cc ./Motion/MotionManager.cc
--- ../Tekkotsu_2.3/Motion/MotionManager.cc	Fri Jan  7 14:23:45 2005
+++ ./Motion/MotionManager.cc	Wed Jun 29 18:04:51 2005
@@ -11,6 +11,7 @@
 
 MotionManager * motman=NULL;
 int MotionManager::_MMaccID=-1U;
+EventTranslator* MotionManager::etrans=NULL;
 
 const float MotionManager::kIgnoredPriority    =-1;
 const float MotionManager::kBackgroundPriority = 0;
@@ -25,10 +26,7 @@
 typedef unsigned int uint;
 
 MotionManager::MotionManager()
-	: pidchanges(),cmdlist(),cur_cmd(invalid_MC_ID),MMlock()
-#ifdef PLATFORM_APERIOS
-	,numAcc(0)
-#endif
+: pidchanges(),cmdlist(),cur_cmd(invalid_MC_ID),MMlock(),numAcc(0)
 {
 	for(uint x=0; x<NumOutputs; x++)
 		cmdSums[x]=0;
@@ -51,10 +49,70 @@
 	subjs[_MMaccID]=subj;
 	if(cmdlist.size()>0) //Shouldn't happen - busy wait in addMotion
 		cout << "*** WARNING *** MOTIONS ADDED BEFORE ALL INITACCESSED" << endl;
-	MMlock.release();
+	MMlock.unlock();
 }
 
-#endif //PLATFORM_APERIOS
+#else //now PLATFORM_LOCAL
+
+void
+MotionManager::InitAccess(MessageQueueBase& mcbufq) {
+	if(numAcc==MAX_ACCESS) {
+		printf("*** ERROR *** attempted to register more accessors with MotionManager than allowed by MAX_ACCESS\n");
+		return;
+	}
+	_MMaccID=numAcc++;
+ 	//	cout << "ID is now " << _MMaccID << " of " << numAcc << endl;
+	//	cout << "_MMaccID is " << &_MMaccID << endl;
+	//	cout << "numAcc is " << &numAcc << " from " << this << endl;
+	MMlock.lock(_MMaccID);
+	subjs[_MMaccID]=&mcbufq;
+	if(cmdlist.size()>0) //Shouldn't happen - busy wait in doAddMotion
+		cout << "*** WARNING *** MOTIONS ADDED BEFORE ALL INITACCESSED" << endl;
+	MMlock.unlock();
+}
+
+void
+MotionManager::RemoveAccess() {
+	func_begin();
+	for(MC_ID mc_id=cmdlist.begin(); mc_id!=cmdlist.end(); mc_id=cmdlist.next(mc_id)) {
+		if(cmdlist[mc_id].rcr[_MMaccID]!=NULL) {
+			checkoutMotion(mc_id,true);
+			cmdlist[mc_id].rcr[_MMaccID]->RemoveReference();
+			cmdlist[mc_id].rcr[_MMaccID]=NULL;
+			bool found=false;
+			for(unsigned int i=0; i<numAcc; i++)
+				if(cmdlist[mc_id].rcr[i]!=NULL) {
+					found=true;
+					break;
+				}
+			if(!found) {
+				cout << "Warning: dropping motion command " << mc_id << ", was active at shutdown (leaked?)" << endl;
+				push_free(mc_id);
+				//should we check in?  The lock isn't technically valid anymore...
+				//checkinMotion(mc_id);
+			} else
+				checkinMotion(mc_id);
+		}
+	}
+	func_end();
+}
+
+#endif //PLATFORM-specific initialization
+
+MotionManager::~MotionManager() {
+	if(!cmdlist.empty()) {
+		func_begin();
+		cout << "WARNING: MotionManager destruction with MotionCommands still attached." << endl;
+		while(!cmdlist.empty()) {
+			MC_ID mc_id=cmdlist.begin();
+			for(unsigned int i=0; i<numAcc; i++)
+				if(cmdlist[mc_id].rcr[i]!=NULL)
+					cout << "MC " << mc_id << " was still referenced by InitAccess caller #" << _MMaccID << endl;
+			push_free(mc_id);
+		}
+		func_end();
+	}
+}
 
 void
 MotionManager::setOutput(const MotionCommand* caller, unsigned int output, const OutputCmd& cmd) {
@@ -252,6 +310,7 @@
 	std::list<MC_ID> unlocked;
 	for(MC_ID it=begin(); it!=end(); it=next(it)) // check out all the MotionCommands (only one at a time tho)
 		unlocked.push_back(it);
+	unsigned int lastProcessed=get_time();
 	while(unlocked.size()>0) { // keep cycling through all the locks we didn't get
 		for(std::list<MC_ID>::iterator it=unlocked.begin(); it!=unlocked.end(); ) {
 			MotionCommand* mc=checkoutMotion(*it,false);
@@ -265,13 +324,24 @@
 					removeMotion(*it);
 				} else
 					mc->updateOutputs(); // the MotionCommand should make calls to setOutput from within here
+				cur_cmd=invalid_MC_ID;
 				checkinMotion(*it); // release lock, done with motion
 				// remove id from list of unprocessed motioncommands
 				std::list<MC_ID>::iterator rem=it++;
 				unlocked.erase(rem);
+				lastProcessed=get_time();
 			}
 		}
-		cur_cmd=invalid_MC_ID;
+		if(get_time()-lastProcessed>FrameTime*NumFrames/2)
+			break;
+	}
+	if(unlocked.size()>0) {
+		cerr << "Warning: MotionManager was unable to obtain a lock on MCs: ";
+		for(std::list<MC_ID>::iterator it=unlocked.begin(); it!=unlocked.end(); it++)
+			cerr << *it << ' ';
+		cerr << endl;
+		cerr << (unlocked.size()>1?"They":"It") << " may have been left locked by a Behavior while it was busy." << endl;
+		cerr << "Try reducing the scope of your MMAccessor or call checkinMotion sooner." << endl;
 	}
 
 	// sort the list of requested outputs based on priority
@@ -394,6 +464,7 @@
 
 void
 MotionManager::updateWorldState() {
+	//cout << "updateWorldState" << endl;
 	for(uint output=LEDOffset; output<LEDOffset+NumLEDs; output++)
 		state->outputs[output]=cmdSums[output];
 	for(uint output=BinJointOffset; output<BinJointOffset+NumBinJoints; output++)
@@ -420,7 +491,6 @@
 
 #ifdef PLATFORM_APERIOS
 
-
 /*! This function handles the conversion from the Tekkotsu format (one
  *  regular IEEE float per parameter, to the OPEN-R format (which
  *  takes a specialized, reduced precision floating point number) This
@@ -449,6 +519,7 @@
  */
 bool
 MotionManager::updatePIDs(OPrimitiveID primIDs[NumOutputs]) {
+	//cout << "updatePIDs " << endl;
 	bool dirty=!pidchanges.empty();
 	while(!pidchanges.empty()) {
 		float gain[3];
@@ -493,30 +564,84 @@
 	return dirty;
 }
 
-/*! @deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises */
-MotionManager::MC_ID
-MotionManager::addMotion(const SharedObjectBase& sm) {
-	return doAddMotion(sm,true,kStdPriority);
-}
-/*! @deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises */
-MotionManager::MC_ID 
-MotionManager::addMotion(const SharedObjectBase& sm, bool autoprune) {
-	return doAddMotion(sm,autoprune,kStdPriority);
-}
-/*! @deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises */
-MotionManager::MC_ID
-MotionManager::addMotion(const SharedObjectBase& sm, float priority) {
-	return doAddMotion(sm,true,priority);
+void
+MotionManager::receivedMsg(const ONotifyEvent& event) {
+	//	cout << "receivedMsg..." << flush;
+	func_begin();
+	//	cout << id << "..." << flush;
+	//cout << "Received at " << get_time() << endl;
+	for(int x=0; x<event.NumOfData(); x++)
+		processMsg(event.RCData(x));
+	//	cout << "receivedMsg-done" << endl;
+	func_end();
 }
-/*! @deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises */
-MotionManager::MC_ID 
-MotionManager::addMotion(const SharedObjectBase& sm, float priority, bool autoprune) {
-	return doAddMotion(sm,autoprune,priority);
+
+#endif //PLATFORM_APERIOS or PLATFORM_LOCAL
+
+void
+MotionManager::processMsg(RCRegion * rcr) {
+	//cout << "processMsg..." << flush;
+	if(rcr==NULL) {
+		cout << "WARNING: MotionManager::processMsg was given a NULL region" << endl;
+		return;
+	}
+	func_begin();
+	//	cout << id << "..." << flush;
+	MotionManagerMsg * mminfo = reinterpret_cast<MotionManagerMsg*>(rcr->Base());
+	MC_ID mc_id=mminfo->mc_id;
+	switch(mminfo->type) {
+		case MotionManagerMsg::addMotion: {
+			//cout << "receiveMotion(): rcr->NumberOfReference()==" << rcr->NumberOfReference() << endl;
+			rcr->AddReference();
+			//cout << "receiveMotion()NOW: rcr->NumberOfReference()==" << rcr->NumberOfReference() << endl;
+			cmdlist[mc_id].rcr[_MMaccID]=rcr;
+			//should be able to do a nice dynamic cast instead of a static one
+			// but it gives NULL for some reason - i blame having to do the fork trick
+			//cout << "Adding mc_id=="<< mc_id << " (and dynamic_cast is still " << dynamic_cast<MotionCommand*>(mminfo) << ")" << endl;
+			cmdlist[mc_id].baseaddrs[_MMaccID]=static_cast<MotionCommand*>(mminfo);
+			cmdlist[mc_id].baseaddrs[_MMaccID]->DoStart();
+			erouter->postEvent(new EventBase(EventBase::motmanEGID,mc_id,EventBase::activateETID,0));
+		} break;
+		case MotionManagerMsg::deleteMotion: {
+			//cout << "deleteMotion(): cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference()==" << cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference() << endl;
+			//cout << "deleting mc_id=="<<mc_id << endl;
+			if(cmdlist[mc_id].rcr[_MMaccID]==NULL)
+				cout << "WARNING: MotionManager attempted to delete a NULL motion! mc_id="<<mc_id<<" _MMaccID=" << _MMaccID << endl;
+			else {
+				checkoutMotion(mc_id,true);
+				cmdlist[mc_id].baseaddrs[_MMaccID]->DoStop();
+				erouter->postEvent(new EventBase(EventBase::motmanEGID,mc_id,EventBase::deactivateETID,0));
+				cmdlist[mc_id].rcr[_MMaccID]->RemoveReference();
+				cmdlist[mc_id].rcr[_MMaccID]=NULL;
+				bool found=false;
+				for(unsigned int i=0; i<numAcc; i++)
+					if(cmdlist[mc_id].rcr[i]!=NULL) {
+						found=true;
+						break;
+					}
+				if(!found) {
+					push_free(mc_id);
+					//should we check in?  The lock isn't technically valid anymore...
+					//checkinMotion(mc_id);
+				} else {
+					cout << "Warning: motion command " << mc_id << " still has attachments after delete message received" << endl;
+					checkinMotion(mc_id);
+				}
+			}
+			//cout << "deleteMotion()NOW: cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference()==" << cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference() << endl;
+		} break;
+		default:
+			printf("*** WARNING *** unknown MotionManager msg type received\n");
+	}
+	//	cout << "processMsg-done" << endl;
+	func_end();
 }
+
+
 /*! We have made this function protected because it's more readable if you
- *  call addPrunableMotion() or addPersistentMotion() instead... we decided
- *  requiring people to pass a true/false arguement wouldn't make it clear
- *  what that true/false was controlling. */
+*  call addPrunableMotion() or addPersistentMotion() instead... we decided
+*  requiring people to pass a true/false arguement wouldn't make it clear
+*  what that true/false was controlling. */
 MotionManager::MC_ID 
 MotionManager::doAddMotion(const SharedObjectBase& sm, bool autoprune, float priority) {
 	MotionCommand * mc = dynamic_cast<MotionCommand*>(reinterpret_cast<MotionManagerMsg*>(sm.data()));
@@ -530,6 +655,12 @@
 	func_begin();
 	//cout << cmdlist.size() << " exist..." << endl;
 	//	cout << id << "..." << flush;
+	for(MC_ID it=cmdlist.begin(); it!=cmdlist.end(); it=cmdlist.next(it)) {
+		if(cmdlist[it].baseaddrs[_MMaccID]==mc) {
+			cerr << "Warning: re-added motion command " << it << endl;
+			return it;
+		}
+	}
 	MC_ID mc_id = pop_free();
 	if(mc_id==cmdlist.end()) {
 		cout << "MotionManager::addMotion() - Out of room, could not add" << endl;
@@ -544,6 +675,7 @@
 	cmdlist[mc_id].priority=priority;
 	//cout << "setAdd(" << mc_id << ")" << endl;
 	mc->setAdd(mc_id);
+#ifdef PLATFORM_APERIOS
 	OStatus err;
 	/*{
 		unsigned int i=0;
@@ -558,60 +690,14 @@
 	//cout << "addMotion()afterSetData: sm.getRegion()->NumberOfReference()==" << sm.getRegion()->NumberOfReference() << endl;
 	err=subjs[_MMaccID]->NotifyObservers();
 	ASSERT(err==oSUCCESS,"*** ERROR MotionManager: NotifyObservers returned " << err);
+#else //PLATFORM_LOCAL
+	subjs[_MMaccID]->sendMessage(sm.getRegion());
+#endif //PLATFORM check for IPC stuff
 	//	cout << "addMotion-done" << endl;
 	//cout << " - " << get_time() << endl;
 	return func_end(mc_id);
 }
 
-void
-MotionManager::receivedMsg(const ONotifyEvent& event) {
-	//	cout << "receivedMsg..." << flush;
-	func_begin();
-	//	cout << id << "..." << flush;
-	//cout << "Received at " << get_time() << endl;
-	for(int x=0; x<event.NumOfData(); x++) {
-		RCRegion * rcr = event.RCData(x);
-		MotionManagerMsg * mminfo = reinterpret_cast<MotionManagerMsg*>(rcr->Base());
-		MC_ID mc_id=mminfo->mc_id;
-		switch(mminfo->type) {
-		case MotionManagerMsg::addMotion: {
-			//cout << "receiveMotion(): rcr->NumberOfReference()==" << rcr->NumberOfReference() << endl;
-			rcr->AddReference();
-			//cout << "receiveMotion()NOW: rcr->NumberOfReference()==" << rcr->NumberOfReference() << endl;
-			cmdlist[mc_id].rcr[_MMaccID]=rcr;
-			//should be able to do a nice dynamic cast instead of a static one
-			// but it gives NULL for some reason - i blame having to do the fork trick
-			//cout << "Adding mc_id=="<< mc_id << " (and dynamic_cast is still " << dynamic_cast<MotionCommand*>(mminfo) << ")" << endl;
-			cmdlist[mc_id].baseaddrs[_MMaccID]=static_cast<MotionCommand*>(mminfo);
-			cmdlist[mc_id].baseaddrs[_MMaccID]->DoStart();
-			erouter->postEvent(new EventBase(EventBase::motmanEGID,mc_id,EventBase::activateETID,0));
-		} break;
-		case MotionManagerMsg::deleteMotion: {
-			//cout << "deleteMotion(): cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference()==" << cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference() << endl;
-			//cout << "deleting mc_id=="<<mc_id << endl;
-			if(cmdlist[mc_id].rcr[_MMaccID]==NULL)
-				cout << "WARNING: MotionManager attempted to delete a NULL motion! mc_id="<<mc_id<<" _MMaccID=" << _MMaccID << endl;
-			else {
-				checkoutMotion(mc_id,true);
-				cmdlist[mc_id].baseaddrs[_MMaccID]->DoStop();
-				erouter->postEvent(new EventBase(EventBase::motmanEGID,mc_id,EventBase::deactivateETID,0));
-				cmdlist[mc_id].rcr[_MMaccID]->RemoveReference();
-				cmdlist[mc_id].rcr[_MMaccID]=NULL;
-				push_free(mc_id);
-				checkinMotion(mc_id);
-			}
-			//cout << "deleteMotion()NOW: cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference()==" << cmdlist[mc_id].rcr[_MMaccID]->NumberOfReference() << endl;
-		} break;
-		default:
-			printf("*** WARNING *** unknown MotionManager msg type received\n");
-		}
-	}
-	//	cout << "receivedMsg-done" << endl;
-	func_end();
-}
-
-#endif //PLATFORM_APERIOS
-
 MotionCommand *
 MotionManager::checkoutMotion(MC_ID mcid,bool block) {
 	//cout << "checkout..." << flush;
@@ -626,7 +712,7 @@
 			return NULL;
 	if(cmdlist[mcid].lastAccessor==(accID_t)-1) {
 		cout << "*** WARNING *** " << _MMaccID << " tried to access dead mcid " << mcid << endl;
-		cmdlist[mcid].lock.release();
+		cmdlist[mcid].lock.unlock();
 		return NULL;
 	}
 	//cout << "locked..." << endl;
@@ -639,14 +725,16 @@
 		//cout << "to=" << MCRegistrar::getRaw(base) << ", " << accRegs[cmdlist[mcid].lastAccessor].getReg(base) << endl;
 		cmdlist[mcid].lastAccessor=_MMaccID;
 	}
+	base->setTranslator(etrans);
 	//cout << "checkout-done..." << flush;
 	return base;
 }
 
 void
 MotionManager::checkinMotion(MC_ID mcid) {
+	cmdlist[mcid].baseaddrs[_MMaccID]->setTranslator(NULL);
 	if(mcid!=invalid_MC_ID)
-		cmdlist[mcid].lock.release();
+		cmdlist[mcid].lock.unlock();
 }
 
 void
@@ -660,11 +748,19 @@
 	//cout << "Remove at " << get_time() << flush;
 	subjs[_MMaccID]->SetData(&dmsg,sizeof(dmsg));
 	subjs[_MMaccID]->NotifyObservers();
-	//cout << " - " << get_time() << endl;
-	//cout << "removeMotion(): cmdlist[mcid].rcr[_MMaccID]->NumberOfReference()==" << cmdlist[mcid].rcr[_MMaccID]->NumberOfReference() << endl;
-	cmdlist[mcid].rcr[_MMaccID]->RemoveReference();
+#else //PLATFORM_LOCAL
+	SharedObject<MotionManagerMsg> dmsg;
+	dmsg->setDelete(mcid);
+	//cout << "Remove at " << get_time() << flush;
+	subjs[_MMaccID]->sendMessage(dmsg.getRegion());
+#endif //PLATFORM check for IPC stuff
+	 //cout << " - " << get_time() << endl;
+	 //cout << "removeMotion(): cmdlist[mcid].rcr[_MMaccID]->NumberOfReference()==" << cmdlist[mcid].rcr[_MMaccID]->NumberOfReference() << endl;
+	if(cmdlist[mcid].rcr[_MMaccID]!=NULL) {
+		cmdlist[mcid].rcr[_MMaccID]->RemoveReference();
+		cmdlist[mcid].rcr[_MMaccID]=NULL;
+	}
 	//cout << "removeMotion()NOW: cmdlist[mcid].rcr[_MMaccID]->NumberOfReference()==" << cmdlist[mcid].rcr[_MMaccID]->NumberOfReference() << endl;
-#endif //PLATFORM_APERIOS
 	func_end();
 }
 
@@ -702,6 +798,9 @@
 		if(pids[i]!=state->pids[joint][i]) {
 			PIDUpdate update(joint,pids); //it is different, insert a new update
 			pidchanges.push_back(update);
+			// or for debugging:
+			//ListMemBuf<PIDUpdate,NumPIDJoints>::index_t it=pidchanges.push_back(update);
+			//ASSERT(it!=pidchanges.end(),"MotionManager ran out of pidchanges entries!");
 			break;
 		}
 	func_end();
@@ -712,13 +811,9 @@
 MotionManager::skip_ahead(MC_ID mcid) const {
 	// this is in case a new motion has been added, but the current
 	// process hasn't received its own copy yet, so should skip over them
-#ifdef PLATFORM_APERIOS
 	while(mcid!=cmdlist.end() && cmdlist[mcid].rcr[_MMaccID]==NULL)
 		mcid=cmdlist.next(mcid);
 	return mcid;
-#else
-	return cmdlist.next(mcid);
-#endif
 }
 
 MotionManager::OutputState::OutputState()
@@ -763,10 +858,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.40 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.43 $
  * $State: Exp $
- * $Date: 2005/01/07 19:23:45 $
+ * $Date: 2005/06/29 22:04:51 $
  */
 
 
diff -urdN ../Tekkotsu_2.3/Motion/MotionManager.h ./Motion/MotionManager.h
--- ../Tekkotsu_2.3/Motion/MotionManager.h	Mon Oct 18 19:10:26 2004
+++ ./Motion/MotionManager.h	Sun Aug  7 00:11:03 2005
@@ -6,22 +6,23 @@
 #include "OutputCmd.h"
 #include "OutputPID.h"
 #include "Shared/RobotInfo.h"
-#include "Shared/ListMemBuf.h"
-#include "Shared/MutexLock.h"
-
-#ifdef PLATFORM_APERIOS
-#include "Shared/SharedObject.h"
+#include "IPC/ListMemBuf.h"
+#include "IPC/MutexLock.h"
+#include "IPC/SharedObject.h"
 #include "MotionManagerMsg.h"
-#endif
 
 #ifdef PLATFORM_APERIOS
-#include <OPENR/OPENR.h>
-#include <OPENR/OPENRAPI.h>
-#include <OPENR/OSubject.h>
-#include <OPENR/ObjcommEvent.h>
-#include <OPENR/OObject.h>
+#  include <OPENR/OPENR.h>
+#  include <OPENR/OPENRAPI.h>
+#  include <OPENR/OSubject.h>
+#  include <OPENR/ObjcommEvent.h>
+#  include <OPENR/OObject.h>
+#else //PLATFORM_LOCAL
+#  include "IPC/MessageQueue.h"
 #endif
 
+class EventTranslator;
+
 //! The purpose of this class is to provide mutually exclusive access to the MotionCommands and simplify their sharing between memory spaces
 /*! Since MotionObject and MainObject run as separate processes, they
  *  could potentially try to access the same motion command at the
@@ -87,11 +88,16 @@
 	//@}
 
 	MotionManager();                            //!< Constructor, sets all the outputs to 0
-
 #ifdef PLATFORM_APERIOS
 	void InitAccess(OSubject* subj);            //!< @b LOCKS @b MotionManager Everyone who is planning to use the MotionManager needs to call this before they access it or suffer a horrible fate
 	void receivedMsg(const ONotifyEvent& event); //!< @b LOCKS @b MotionManager This gets called by an OObject when it receives a message from one of the other OObject's MotionManagerComm Subject
+#else
+	void InitAccess(MessageQueueBase& mcbufq); //!< @b LOCKS @b MotionManager Everyone who is planning to use the MotionManager needs to call this before they access it or suffer a horrible fate
+	void RemoveAccess(); //!< needed in order to dereference shared memory regions before shutting down
 #endif
+	static void setTranslator(EventTranslator* et) {etrans=et;} //!< sets #etrans, should be called before any events can be sent
+	void processMsg(RCRegion* region); //!< @b LOCKS @b MotionManager This gets called by receivedMsg when under Aperios, or directly if you already have an RCRegion
+	~MotionManager(); //!<destructor
 
 	//!@name MotionCommand Safe
 	void setOutput(const MotionCommand* caller, unsigned int output, const OutputCmd& cmd); //!< @b LOCKS @b MotionManager Requests a value be set for the specified output, copies cmd across frames
@@ -123,28 +129,17 @@
 
 	//!@name MotionCommand Unsafe
 	//@{
-#ifdef PLATFORM_APERIOS
 	//! @b LOCKS @b MotionManager adds a new motion (wrapped in a SharedObject) and marks that it should be automatically deleted when the MotionCommand::isAlive() returns false.
 	MC_ID addPrunableMotion(const SharedObjectBase& sm, float priority=kStdPriority) { return doAddMotion(sm,true,priority); }
 	//! @b LOCKS @b MotionManager adds a new motion (wrapped in a SharedObject) and marks that it should @e not be deleted, until removeMotion(MC_ID mcid) is called.
 	MC_ID addPersistentMotion(const SharedObjectBase& sm, float priority=kStdPriority) { return doAddMotion(sm,false,priority); }
-#endif //PLATFORM_APERIOS
 	void removeMotion(MC_ID mcid); //!< @b LOCKS @b MotionManager removes the specified MotionCommand
 	//@}
 
-	//!@name Deprecated
-#ifdef PLATFORM_APERIOS
-	MC_ID addMotion(const SharedObjectBase& sm) __attribute__((deprecated)); //!< deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises
-	MC_ID addMotion(const SharedObjectBase& sm, bool autoprune) __attribute__((deprecated)); //!< deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises
-	MC_ID addMotion(const SharedObjectBase& sm, float priority) __attribute__((deprecated)); //!< deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises
-	MC_ID addMotion(const SharedObjectBase& sm, float priority, bool autoprune) __attribute__((deprecated)); //!< deprecated, we're recommending users call either addPrunableMotion() or addPersistentMotion() so there are no surprises
-#endif //PLATFORM_APERIOS
-	//@}
-
 	//@{
 	void lock()    { MMlock.lock(_MMaccID); } //!< gets an exclusive lock on MotionManager - functions marked @b LOCKS @b MotionManager will cause (and require) this to happen automatically
 	bool trylock() { return MMlock.try_lock(_MMaccID); } //!< tries to get a lock without blocking
-	void release() { MMlock.release(); } //!< releases a lock on the motion manager
+	void unlock() { MMlock.unlock(); } //!< releases a lock on the motion manager
 	//@}
 
 	//@{
@@ -175,10 +170,8 @@
 	};
 
 protected:
-#ifdef PLATFORM_APERIOS
 	//!does the actual work of adding a motion
 	MC_ID doAddMotion(const SharedObjectBase& sm, bool autoprune, float priority);
-#endif
 	
 	//! used to request pids for a given joint
 	struct PIDUpdate {
@@ -198,7 +191,7 @@
 	typedef unsigned short accID_t; //!< type to use to refer to accessors of MotionManager (or its locks)
 
 	void func_begin() { MMlock.lock(_MMaccID); } //!< called at the begining of many functions to lock MotionManager
-	void func_end() { MMlock.release(); } //!< called at the end of a function which called func_begin() to release it
+	void func_end() { MMlock.unlock(); } //!< called at the end of a function which called func_begin() to release it
 	template<class T> T func_end(T val) { func_end(); return val; } //!< same as func_end(), except passes return value through
 
 	MC_ID skip_ahead(MC_ID mcid) const; //!< during iteration, skips over motioncommands which are still in transit from on OObject to another
@@ -209,15 +202,11 @@
 		CommandEntry() : lastAccessor((unsigned short)-1),lock(),priority(MotionManager::kStdPriority) {
 			for(unsigned int i=0; i<MAX_ACCESS; i++) {
 				baseaddrs[i]=NULL;
-#ifdef PLATFORM_APERIOS
 				rcr[i]=NULL;
-#endif
 			}
 		}
 		MotionCommand * baseaddrs[MAX_ACCESS]; //!< for each accessor, the base address of the motion command
-#ifdef PLATFORM_APERIOS
 		RCRegion * rcr[MAX_ACCESS];            //!< for each accessor the shared memory region that holds the motion command
-#endif
 		accID_t lastAccessor;                  //!< the ID of the last accessor to touch the command (which implies if it wants to touch this again, we don't have to convert again)
 		MutexLock<MAX_ACCESS> lock;            //!< a lock to maintain mutual exclusion
 		float priority;                        //!< MotionCommand's priority level
@@ -239,19 +228,23 @@
 	float cmdSums[NumOutputs];             //!<Holds the final values for the outputs of the last frame generated
 	OutputCmd cmds[NumOutputs];            //!<Holds the weighted values and total weight for the outputs of the last frame
 
-#ifdef PLATFORM_APERIOS
 	accID_t numAcc;                        //!<The number of accessors who have registered with InitAccess()
+#ifdef PLATFORM_APERIOS
 	OSubject* subjs[MAX_ACCESS];           //!<The OSubject for each process (accessor) on which it should be broadcast when a command is added
+#else //PLATFORM_LOCAL
+	//!Storage of each process's attachment of the message queue, used to internally transmit sound buffers to SoundPlay
+	MessageQueueBase * subjs[MAX_ACCESS];
 #endif
 
 	static int _MMaccID;          //!<Stores the accessor for the current process
+	static EventTranslator* etrans; //!< EventTranslator for sending events to Main -- each process will set the correct value for calls within that process.
 
 private:
 	MotionManager(const MotionManager&); //!< this shouldn't be called...
 	MotionManager& operator=(const MotionManager&); //!< this shouldn't be called...
 };
 
-//!anyone who #includes MotionManager.h will be wanting to use the global motman... don't want multiple of these! created by MotoObj
+//!anyone who includes MotionManager.h will be wanting to use the global motman... don't want multiple of these! created by MotoObj
 extern MotionManager * motman;
 
 /*! @file
@@ -259,10 +252,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.23 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.27 $
  * $State: Exp $
- * $Date: 2004/10/18 23:10:26 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/MotionManagerMsg.h ./Motion/MotionManagerMsg.h
--- ../Tekkotsu_2.3/Motion/MotionManagerMsg.h	Tue Sep  2 16:58:49 2003
+++ ./Motion/MotionManagerMsg.h	Tue Sep  2 16:58:49 2003
@@ -52,7 +52,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Rel $
  * $Date: 2003/09/02 20:58:49 $
diff -urdN ../Tekkotsu_2.3/Motion/MotionSequenceEngine.cc ./Motion/MotionSequenceEngine.cc
--- ../Tekkotsu_2.3/Motion/MotionSequenceEngine.cc	Tue Jan 11 13:39:36 2005
+++ ./Motion/MotionSequenceEngine.cc	Thu Jul 14 13:09:03 2005
@@ -9,16 +9,26 @@
 
 MotionSequenceEngine::Move_idx_t MotionSequenceEngine::invalid_move=-1U;
 
+MotionSequenceEngine::MotionSequenceEngine()
+: LoadSave(), playtime(1), lasttime(0), endtime(0), playspeed(1.0),
+playing(true), hold(true), loadSaveMode(M_PI/180)
+{
+	for(unsigned int i=0; i<NumOutputs; i++)
+		curstamps[i]=-1U;
+}
+
+
 int MotionSequenceEngine::updateOutputs() {
 	if(isPlaying()) {
 		if(lasttime==0)
 			play();
-		float diff=(get_time()-lasttime)*playspeed;
+		unsigned int curtime=get_time();
+		float diff=(curtime-lasttime)*playspeed;
 		if(playtime<-diff)
 			setTime(0);
 		else
 			setTime(static_cast<unsigned int>(diff+playtime));
-		lasttime=get_time();
+		lasttime=curtime;
 		return 1;
 	} else {
 		lasttime=get_time();
@@ -160,23 +170,15 @@
 			}
 		} else if(strcasecmp(command,"load")==0) {
 			PostureEngine pose;
-			std::string f;
-			if(arg1[0]!='/')
-				f="/ms/data/motion/";
-			f+=arg1;
-			if(pose.LoadFile(f.c_str())!=0) {
+			if(pose.LoadFile(arg1)!=0) {
 				setPose(pose);
 			} else
 				cout << "*** WARNING could not read file " << arg1 << " for load - line " << linenum << endl;
 		} else if(strcasecmp(command,"overlay")==0) {
 			PostureEngine pose;
-			std::string f;
-			if(arg1[0]!='/')
-				f="/ms/data/motion/";
-			f+=arg1;
-			if(pose.LoadFile(f.c_str())!=0)
+			if(pose.LoadFile(arg1)!=0)
 				overlayPose(pose);
-			else if(LoadFile(f.c_str())==0)
+			else
 				cout << "*** WARNING could not read file " << arg1 << " for overlay - line " << linenum << endl;
 		} else if(strcasecmp(command,"degrees")==0) {
 			setSaveDegrees();
@@ -466,34 +468,14 @@
 	}
 }
 
-/*! @deprecated, call setTime(unsigned int x) instead */
-void MotionSequenceEngine::setPlayTime(unsigned int x) {
-	setTime(x);
-}
-
-/*! @deprecated, use getTime() */
-unsigned int MotionSequenceEngine::getPlayTime() const {
-	return getTime();
-}
-
-/*! @deprecated, use setSpeed(float x) */
-void MotionSequenceEngine::setPlaySpeed(float x) {
-	setSpeed(x);
-}
-
-/*! @deprecated, use getSpeed() */
-float MotionSequenceEngine::getPlaySpeed() const {
-	return getSpeed();
-}
-
 /*! @file
  * @brief Implements MotionSequenceEngine, abstract code for smoothly transitioning between a sequence of postures
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2005/01/11 18:39:36 $
+ * $Date: 2005/07/14 17:09:03 $
  */
 
diff -urdN ../Tekkotsu_2.3/Motion/MotionSequenceEngine.h ./Motion/MotionSequenceEngine.h
--- ../Tekkotsu_2.3/Motion/MotionSequenceEngine.h	Tue Jan 11 13:39:36 2005
+++ ./Motion/MotionSequenceEngine.h	Sun Aug  7 00:11:03 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_MotionSequenceEngine_h_
 
 #include "Shared/LoadSave.h"
-#include "Shared/ListMemBuf.h"
+#include "IPC/ListMemBuf.h"
 #include "PostureEngine.h"
 
 //! A handy little (or not so little) class for switching between a sequence of postures
@@ -40,7 +40,7 @@
  *  @see MotionSequenceEngine::SizeSmall, MotionSequenceEngine::SizeMedium, MotionSequenceEngine::SizeLarge, MotionSequenceEngine::SizeXLarge, 
  *  
  *  The file format used is as follows: ('<' and '>' are not meant literally)
- *  - First line: '<tt>#MSq</tt>'
+ *  - First line: '<tt>\#MSq</tt>'
  *  - Followed by any series of:\n
  *    - '<tt>advanceTime </tt><i>time-delta</i>' - moves playhead forward, in milliseconds (synonym for <tt>delay</tt>)
  *    - '<tt>delay </tt><i>time-delta</i>' - moves playhead forward, in milliseconds (synonym for <tt>advanceTime</tt>)
@@ -51,7 +51,7 @@
  *    - '<tt>degrees</tt>' - following <i>value</i>s will be interpreted as degrees [default]
  *    - '<tt>radians</tt>' - following <i>value</i>s will be interpreted as radians
  *    - '<tt>#</tt><i>comment</i>' - a comment line
- *  - Last line: '<tt>#END</tt>'
+ *  - Last line: '<tt>\#END</tt>'
  *  
  *  Lines beginning with '#' are ignored as comments.  Be aware if you
  *  load the file and then save it again, these comments will be lost.
@@ -81,7 +81,7 @@
  *  standSit->setOutputCmd(HeadOffset+TiltOffset,0.1); //look up .1 radians
  *
  *  //Add to MotionManager:
- *  motman->addPersistentMotion(standSit);
+ *  motman->addPrunableMotion(standSit);
  *  //Playback will now begin automatically, and region deallocated when done
  *  \endcode
  *  
@@ -102,20 +102,10 @@
 class MotionSequenceEngine : public LoadSave {
 public:
 	//!constructor, will start playing immediately
-	MotionSequenceEngine() : LoadSave(), playtime(1), lasttime(0), endtime(0), playspeed(1.0), playing(true), hold(true), loadSaveMode(M_PI/180) {}
+	MotionSequenceEngine();
 	//!destructor
 	virtual ~MotionSequenceEngine() {}
 
-	//!To avoid code bloat if there are a large number of different sized MotionSequences, use these sizes where possible.
-	/*!@deprecated use MotionSequenceMC typedefs (e.g. TinyMotionSequenceMC) in conjunction with MotionSequenceMC::CAPACITY() */
-	//!@name Template Sizes (deprecated)
-	static const unsigned int SizeTiny __attribute__((deprecated))   =NumOutputs*2; //!< deprecated, use TinyMotionSequenceMC for type specification, or TinyMotionSequenceMC::CAPACITY if you need the actual value
-	static const unsigned int SizeSmall __attribute__((deprecated))  =NumOutputs*3; //!< deprecated, use SmallMotionSequenceMC for type specification, or SmallMotionSequenceMC::CAPACITY if you need the actual value
-	static const unsigned int SizeMedium __attribute__((deprecated)) =NumOutputs*6; //!< deprecated, use MediumMotionSequenceMC for type specification, or MediumMotionSequenceMC::CAPACITY if you need the actual value
-	static const unsigned int SizeLarge __attribute__((deprecated))  =NumOutputs*11; //!< deprecated, use LargeMotionSequenceMC for type specification, or LargeMotionSequenceMC::CAPACITY if you need the actual value
-	static const unsigned int SizeXLarge __attribute__((deprecated)) =NumOutputs*26; //!< deprecated, use XLargeMotionSequenceMC for type specification, or XLargeMotionSequenceMC::CAPACITY if you need the actual value
-	//@}
-
 	//! similar to the MotionCommand::updateOutputs, although this isn't a motion command, and doesn't make any calls on MotionManager - merely updates #lasttime, expects subclasses to do the work of sending new commands to the system
 	virtual int updateOutputs();
 	
@@ -162,15 +152,9 @@
 	
 	//@}
 
-	//!@name Deprecated
-	void setPlayTime(unsigned int x) __attribute__((deprecated)); //!< deprecated, use setTime(unsigned int x)
-	unsigned int getPlayTime() const __attribute__((deprecated)); //!< deprecated, use getTime()
-	void setPlaySpeed(float x) __attribute__((deprecated)); //!< deprecated, use setSpeed(float x)
-	float getPlaySpeed() const __attribute__((deprecated)); //!< deprecated, use getSpeed()
-	//@}
 protected:
 	// TYPES:
-	typedef unsigned short Move_idx_t; //!< type for indexes to move structures in #moves
+	typedef unsigned short Move_idx_t; //!< type for indexes to move structures in subclass's storage
 	static Move_idx_t invalid_move; //!< used to mark the ends of the Move linked lists
 
 	//! This struct holds all the information needed about a frame for a particular output
@@ -191,7 +175,7 @@
 	unsigned int curstamps[NumOutputs]; //!< timestamp of corresponding value in #curs
 	unsigned int playtime;              //!< the current time of playback, 0 is start of sequence
 	unsigned int lasttime;              //!< the time of the last update
-	unsigned int endtime;               //!< max of #moves's Move::starttime's
+	unsigned int endtime;               //!< max of moves's Move::starttime's
 	float playspeed;                    //!< multiplies the difference between current time and starttime, negative will cause play backwards
 	bool playing;                       //!< true if playing, false if paused
 	bool hold;                          //!< if set to true, the posture will be kept active; otherwise joints will be marked unused after each posture is achieved (as if the posture was pruned); set through setHold()
@@ -222,19 +206,15 @@
 	static unsigned int getOutputIndex(const char name[], unsigned int i);
 };
 
-//! deprecated, use MotionSequenceEngine directly instead
-/*! @deprecated, use MotionSequenceEngine directly instead */
-typedef MotionSequenceEngine MotionSequence __attribute__ ((deprecated)); 
-
 /*! @file
  * @brief Describes MotionSequenceEngine, abstract code for smoothly transitioning between a sequence of postures
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.13 $
  * $State: Exp $
- * $Date: 2005/01/11 18:39:36 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/MotionSequenceMC.h ./Motion/MotionSequenceMC.h
--- ../Tekkotsu_2.3/Motion/MotionSequenceMC.h	Tue Jan 11 13:38:52 2005
+++ ./Motion/MotionSequenceMC.h	Sun Aug  7 00:11:03 2005
@@ -90,15 +90,17 @@
 	// MEMBERS:
 	list_t moves; //!< stores all of the movement keyframes
 
-	virtual Move& getKeyFrame(Move_idx_t x) { return moves[x]; }
-	virtual const Move& getKeyFrame(Move_idx_t x) const { return moves[x]; }
+	virtual Move& getKeyFrame(Move_idx_t x) { return moves[x]; } //!< returns #moves[@a x]
+	virtual const Move& getKeyFrame(Move_idx_t x) const { return moves[x]; } //!< returns #moves[@a x]
 	virtual Move_idx_t newKeyFrame() {
 		Move_idx_t i=moves.new_front();
 		if(i==invalid_move)
 			serr->printf("ERROR: MotionSequenceMC %d has run out of memory\n",getID());
 		return i;
 	}
+	//! marks keyframe @a x unused
 	virtual void eraseKeyFrame(Move_idx_t x) { moves.erase(x); }
+	//! advances (or rewinds) @a prev and @a next so that @a t falls between them
 	void setRange(unsigned int t,Move_idx_t& prev, Move_idx_t& next) const {
 		if(next!=invalid_move && moves[next].starttime<=t) {
 			do {
@@ -125,10 +127,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.27 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.28 $
  * $State: Exp $
- * $Date: 2005/01/11 18:38:52 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/OldHeadPointerMC.cc ./Motion/OldHeadPointerMC.cc
--- ../Tekkotsu_2.3/Motion/OldHeadPointerMC.cc	Thu Oct 14 16:23:50 2004
+++ ./Motion/OldHeadPointerMC.cc	Thu Oct 14 16:23:50 2004
@@ -176,7 +176,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.1 $
  * $State: Exp $
  * $Date: 2004/10/14 20:23:50 $
diff -urdN ../Tekkotsu_2.3/Motion/OldHeadPointerMC.h ./Motion/OldHeadPointerMC.h
--- ../Tekkotsu_2.3/Motion/OldHeadPointerMC.h	Thu Oct 14 16:23:50 2004
+++ ./Motion/OldHeadPointerMC.h	Sun Aug  7 00:11:03 2005
@@ -77,7 +77,7 @@
 
   //!@name Inherited:
   virtual int updateOutputs(); //!< Updates where the head is looking
-  virtual const OutputCmd& getOutputCmd(unsigned int i);  //!< returns one of the #headJoints entries or ::unusedJoint if not a head joint
+  virtual const OutputCmd& getOutputCmd(unsigned int i);  //!< returns one of the #headCmds entries or ::unusedJoint if not a head joint
   virtual int isDirty() { return ((dirty || !targetReached) && active)?1:0; } //!< true if a change has been made since the last updateJointCmds() and we're active
   virtual int isAlive() { return true; }
   virtual void DoStart() { MotionCommand::DoStart(); dirty=true; targetReached=false; }
@@ -116,10 +116,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.1 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
  * $State: Exp $
- * $Date: 2004/10/14 20:23:50 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/OldKinematics.cc ./Motion/OldKinematics.cc
--- ../Tekkotsu_2.3/Motion/OldKinematics.cc	Thu Aug  5 16:29:04 2004
+++ ./Motion/OldKinematics.cc	Thu Aug  5 16:29:04 2004
@@ -603,7 +603,7 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.1 $
  * $State: Exp $
  * $Date: 2004/08/05 20:29:04 $
diff -urdN ../Tekkotsu_2.3/Motion/OldKinematics.h ./Motion/OldKinematics.h
--- ../Tekkotsu_2.3/Motion/OldKinematics.h	Thu Aug  5 16:29:04 2004
+++ ./Motion/OldKinematics.h	Thu Aug  5 16:29:04 2004
@@ -118,7 +118,7 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.1 $
  * $State: Exp $
  * $Date: 2004/08/05 20:29:04 $
diff -urdN ../Tekkotsu_2.3/Motion/OutputCmd.cc ./Motion/OutputCmd.cc
--- ../Tekkotsu_2.3/Motion/OutputCmd.cc	Tue Jan  4 14:51:41 2005
+++ ./Motion/OutputCmd.cc	Tue Jan  4 14:51:41 2005
@@ -7,7 +7,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Exp $
  * $Date: 2005/01/04 19:51:41 $
diff -urdN ../Tekkotsu_2.3/Motion/OutputCmd.h ./Motion/OutputCmd.h
--- ../Tekkotsu_2.3/Motion/OutputCmd.h	Sun Sep  7 18:14:01 2003
+++ ./Motion/OutputCmd.h	Sun Sep  7 18:14:01 2003
@@ -27,7 +27,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Rel $
  * $Date: 2003/09/07 22:14:01 $
diff -urdN ../Tekkotsu_2.3/Motion/OutputPID.h ./Motion/OutputPID.h
--- ../Tekkotsu_2.3/Motion/OutputPID.h	Sat Dec 13 00:01:40 2003
+++ ./Motion/OutputPID.h	Sat Dec 13 00:01:40 2003
@@ -44,7 +44,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2003/12/13 05:01:40 $
diff -urdN ../Tekkotsu_2.3/Motion/PIDMC.h ./Motion/PIDMC.h
--- ../Tekkotsu_2.3/Motion/PIDMC.h	Mon Dec 20 19:42:21 2004
+++ ./Motion/PIDMC.h	Mon Dec 20 19:42:21 2004
@@ -139,7 +139,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.12 $
  * $State: Exp $
  * $Date: 2004/12/21 00:42:21 $
diff -urdN ../Tekkotsu_2.3/Motion/Path.h ./Motion/Path.h
--- ../Tekkotsu_2.3/Motion/Path.h	Thu Sep 25 11:27:23 2003
+++ ./Motion/Path.h	Thu Sep 25 11:27:23 2003
@@ -107,7 +107,7 @@
  * @endverbatim
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Rel $
  * $Date: 2003/09/25 15:27:23 $
diff -urdN ../Tekkotsu_2.3/Motion/PostureEngine.cc ./Motion/PostureEngine.cc
--- ../Tekkotsu_2.3/Motion/PostureEngine.cc	Fri Jan  7 14:36:38 2005
+++ ./Motion/PostureEngine.cc	Fri Jan  7 14:36:38 2005
@@ -339,7 +339,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.24 $
  * $State: Exp $
  * $Date: 2005/01/07 19:36:38 $
diff -urdN ../Tekkotsu_2.3/Motion/PostureEngine.h ./Motion/PostureEngine.h
--- ../Tekkotsu_2.3/Motion/PostureEngine.h	Fri Jan  7 14:36:38 2005
+++ ./Motion/PostureEngine.h	Fri Jan  7 14:36:38 2005
@@ -148,7 +148,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.16 $
  * $State: Exp $
  * $Date: 2005/01/07 19:36:38 $
diff -urdN ../Tekkotsu_2.3/Motion/PostureMC.cc ./Motion/PostureMC.cc
--- ../Tekkotsu_2.3/Motion/PostureMC.cc	Fri Jan  7 16:12:35 2005
+++ ./Motion/PostureMC.cc	Fri Jan  7 16:12:35 2005
@@ -80,7 +80,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Exp $
  * $Date: 2005/01/07 21:12:35 $
diff -urdN ../Tekkotsu_2.3/Motion/PostureMC.h ./Motion/PostureMC.h
--- ../Tekkotsu_2.3/Motion/PostureMC.h	Fri Jan  7 16:13:10 2005
+++ ./Motion/PostureMC.h	Sun Aug  7 00:11:03 2005
@@ -26,7 +26,7 @@
  */
 class PostureMC : public MotionCommand, public PostureEngine {
 public:
-	//!#timeout will be set to a default value of 2 seconds, #tolerance is .035 radians (~2 degrees), #hold is true
+	//!timeout will be set to a default value of 2 seconds, tolerance is .035 radians (~2 degrees), hold is true
 	//!@name Constructors
 
 	//!constructor
@@ -82,21 +82,21 @@
 	virtual PostureMC& setTimeout(unsigned int delay) { timeout=delay; return *this; } //!< sets #timeout, returns @c *this
 	virtual unsigned int getTimeout() { return timeout; } //!< returns #timeout
 
-	//! Sets #maxSpeed to 0 (no maximum)
+	//! Sets #maxSpeeds to 0 (no maximum)
 	void noMaxSpeed() { for(unsigned int i=0; i<NumOutputs; i++) maxSpeeds[i]=0; }
 	
-	//! Restores #maxSpeed to default ::MaxOutputSpeed values from the robot info file (e.g. ERS7Info.h)
+	//! Restores #maxSpeeds to default ::MaxOutputSpeed values from the robot info file (e.g. ERS7Info.h)
 	/*! Neck joints are instead set from the applicable
 	 *  Config::motion_config values.
 	 *  @param x ratio of the max speed to use; so 0.5 would limit motion to half the recommended upper limit */
 	void defaultMaxSpeed(float x=1);
 	
-	//! Sets #maxSpeed in rad/sec
+	//! Sets #maxSpeeds[i] entry, in rad/sec
 	/*! @param i joint offset, see your model's info file (e.g. ERS7Info.h)
 	 *  @param x maximum radians per second to move */
 	void setMaxSpeed(unsigned int i, float x) { maxSpeeds[i]=x*FrameTime/1000; }
 	
-	//! Returns #maxSpeed in rad/sec
+	//! Returns #maxSpeeds[i] entry, in rad/sec
 	/*! @param i joint offset, see your model's info file (e.g. ERS7Info.h)
 	 *  @return the maximum speed of joint @a i in radians per second */
 	float getMaxSpeed(unsigned int i) { return maxSpeeds[i]*1000/FrameTime; }
@@ -154,10 +154,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.12 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.13 $
  * $State: Exp $
- * $Date: 2005/01/07 21:13:10 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/RemoteControllerMC.h ./Motion/RemoteControllerMC.h
--- ../Tekkotsu_2.3/Motion/RemoteControllerMC.h	Mon Dec 20 19:42:21 2004
+++ ./Motion/RemoteControllerMC.h	Mon Dec 20 19:42:21 2004
@@ -45,7 +45,7 @@
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/12/21 00:42:21 $
diff -urdN ../Tekkotsu_2.3/Motion/Spline.h ./Motion/Spline.h
--- ../Tekkotsu_2.3/Motion/Spline.h	Thu Sep 25 11:27:23 2003
+++ ./Motion/Spline.h	Thu Sep 25 11:27:23 2003
@@ -375,7 +375,7 @@
  * @endverbatim
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Rel $
  * $Date: 2003/09/25 15:27:23 $
diff -urdN ../Tekkotsu_2.3/Motion/TailWagMC.h ./Motion/TailWagMC.h
--- ../Tekkotsu_2.3/Motion/TailWagMC.h	Wed Dec 22 20:47:07 2004
+++ ./Motion/TailWagMC.h	Wed Apr  6 16:36:00 2005
@@ -6,7 +6,9 @@
 #include "Motion/MotionManager.h"
 #include "Shared/get_time.h"
 #include "math.h"
+#include "Shared/ERS7Info.h"
 #include "Shared/ERS210Info.h"
+#include "Shared/WorldState.h"
 
 //! A simple motion command for wagging the tail - you can specify period, magnitude, and tilt
 class TailWagMC : public MotionCommand {
@@ -61,10 +63,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/04/06 20:36:00 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/UPennWalkMC.cc ./Motion/UPennWalkMC.cc
--- ../Tekkotsu_2.3/Motion/UPennWalkMC.cc	Wed Dec 31 19:00:00 1969
+++ ./Motion/UPennWalkMC.cc	Tue Apr 12 17:33:31 2005
@@ -0,0 +1,634 @@
+#include "UPennWalkMC.h"
+
+//This class is ported from University of Pennsylvania's 2004 Robosoccer entry, and falls under their license:
+/*=========================================================================
+    This software is distributed under the GNU General Public License,
+    version 2.  If you do not have a copy of this licence, visit
+    www.gnu.org, or write: Free Software Foundation, 59 Temple Place,
+    Suite 330 Boston, MA 02111-1307 USA.  This program is distributed
+    in the hope that it will be useful, but WITHOUT ANY WARRANTY,
+    including MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  ========================================================================= */
+
+//better to put this here instead of the header
+using namespace std; 
+
+#include <math.h>
+
+#ifndef PI
+#define PI M_PI
+#endif
+
+const size_t MAX_WIDTH = 208;
+const size_t MAX_HEIGHT = 160;
+const size_t LAYERM_WIDTH = 104;
+const size_t LAYERM_HEIGHT = 80;
+
+const double FIELD_VIEW_H = 56.9*(PI/180);
+const double FIELD_VIEW_V = 45.2*(PI/180);
+const double FOCAL_LENGTH = 192.0; // in pixel units (.5*WIDTH/tan(.5*FIELD_VIEW_H))
+const unsigned int IMAGE_WIDTH = 208;
+const unsigned int IMAGE_HEIGHT = 160;
+
+const double BODY_TILT = -13*PI/180; // Negative is head closer to ground
+
+const double BODY_WIDTH = 134.4;
+const double BODY_LENGTH = 130.0;
+
+const size_t NUM_LEG = 4;
+const size_t NUM_LEG_JOINT = 3*NUM_LEG;
+
+// Should optimize by also storing LENGTH and ANGLE of each segment:
+const double LEG_FORE_UPPER_Z = 69.5;
+const double LEG_FORE_UPPER_Y = 9.0;
+const double LEG_FORE_LOWER_Z = 76.4;  // From (71.5, 28.3) @ 30 deg.
+const double LEG_FORE_LOWER_Y = -9.0;
+
+const double LEG_HIND_UPPER_Z = 69.5;
+const double LEG_HIND_UPPER_Y = 9.0;
+const double LEG_HIND_LOWER_Z = 78.9; // From (76.5, 21.3) @ 30 deg.
+const double LEG_HIND_LOWER_Y = -9.0;
+//const double LEG_HIND_LOWER_Z = 80.0; // From (76.5, 21.3) @ 30 deg.
+//const double LEG_HIND_LOWER_Y = 0.0;
+
+const double NECK_TILT2_TO_CAMERA_Y = 81.0;
+const double NECK_TILT2_TO_CAMERA_Z = -14.6;
+const double NECK_TILT_TO_TILT2 = 80.0;
+const double SHOULDER_TO_NECK_TILT_Y = 2.5;
+const double SHOULDER_TO_NECK_TILT_Z = 19.5;
+
+const double MIN_SHOULDER_HEIGHT = 50.0;
+
+const double TURN_OFFSET = 75.0;
+
+
+
+// Maximum parameters for walk:
+
+
+// Imitating Paul's walk:
+
+const double STANCE_BODY_TILT = 0*PI/180;
+const double STANCE_SHOULDER_HEIGHT = 105.;
+
+const double STANCE_FORE_X0 = 7.;
+//const double STANCE_FORE_Y0 = 50.;
+const double STANCE_FORE_Y0 = 60.;
+const double STANCE_HIND_X0 = 2.;
+const double STANCE_HIND_Y0 = -45.;
+
+const int WALK_QUARTER_PERIOD = 3;
+const double WALK_MAX_DISTANCE = 13.; // 390 (mm/sec) /30 frames = 13
+
+const double WALK_FORE_LIFT_INITIAL = 25;
+const double WALK_FORE_LIFT_FINAL = 45;
+
+const double WALK_HIND_LIFT_INITIAL = 25;
+const double WALK_HIND_LIFT_FINAL = 25;
+
+const double WALK_FORE_XMIN = -10;
+const double WALK_FORE_XMAX = 30;
+const double WALK_FORE_YMIN = 25;
+//const double WALK_FORE_YMAX = 85;
+const double WALK_FORE_YMAX = 90;
+
+const double WALK_HIND_XMIN = -15;
+const double WALK_HIND_XMAX = 35;
+const double WALK_HIND_YMIN = -70;
+const double WALK_HIND_YMAX = -15;
+
+
+/*
+// Imitating 2004 US Open walk:
+const double STANCE_BODY_TILT = -15*PI/180;
+const double STANCE_SHOULDER_HEIGHT = 95.;
+
+const double STANCE_FORE_X0 = 5.;
+const double STANCE_FORE_Y0 = 70.;
+const double STANCE_HIND_X0 = 10.;
+const double STANCE_HIND_Y0 = -40.;
+
+const int WALK_QUARTER_PERIOD = 4;
+const double WALK_MAX_DISTANCE = 8.; // 390 (mm/sec) /30 frames = 13
+
+const double WALK_FORE_LIFT_INITIAL = 20;
+const double WALK_FORE_LIFT_FINAL = 30;
+const double WALK_HIND_LIFT_INITIAL = 30;
+const double WALK_HIND_LIFT_FINAL = 20;
+
+const double WALK_FORE_XMIN = -20;
+const double WALK_FORE_XMAX = 40;
+const double WALK_FORE_YMIN = 0;
+const double WALK_FORE_YMAX = 100;
+
+const double WALK_HIND_XMIN = -20;
+const double WALK_HIND_XMAX = 50;
+const double WALK_HIND_YMIN = -150;
+const double WALK_HIND_YMAX = 20;
+*/
+
+
+enum LegIdentifier {
+  LEG_LEFT_FORE = 0,
+  LEG_LEFT_HIND = 1,
+  LEG_RIGHT_FORE = 2,
+  LEG_RIGHT_HIND = 3
+};
+
+UPennWalkMC::UPennWalkMC()
+	: MotionCommand(), xVel(0), yVel(0), aVel(0),
+		// Default stance parameters:
+		body_tilt(STANCE_BODY_TILT), shoulder_height(STANCE_SHOULDER_HEIGHT),
+		fore_x0(STANCE_FORE_X0), fore_y0(STANCE_FORE_Y0),
+		hind_x0(STANCE_HIND_X0), hind_y0(STANCE_HIND_Y0),
+		// Default walk parameters:
+		walk_phase(0),walk_phase_direction(1),
+		walk_quarter_period(WALK_QUARTER_PERIOD), walk_max_distance(WALK_MAX_DISTANCE),
+		walk_fore_lift_initial(WALK_FORE_LIFT_INITIAL), walk_fore_lift_final(WALK_FORE_LIFT_FINAL),
+		walk_hind_lift_initial(WALK_HIND_LIFT_INITIAL), walk_hind_lift_final(WALK_HIND_LIFT_FINAL),
+		walk_fore_xmin(WALK_FORE_XMIN), walk_fore_xmax(WALK_FORE_XMAX),
+		walk_fore_ymin(WALK_FORE_YMIN), walk_fore_ymax(WALK_FORE_YMAX),
+		walk_hind_xmin(WALK_HIND_XMIN), walk_hind_xmax(WALK_HIND_XMAX),
+		walk_hind_ymin(WALK_HIND_YMIN), walk_hind_ymax(WALK_HIND_YMAX)
+{
+  for (int i = 0; i < 4; i++) {
+    walk_current_x[i] = 0.0;
+    walk_current_y[i] = 0.0;
+  }
+}
+
+void
+UPennWalkMC::SetLegJoints(double * x) {
+	motman->setOutput(this,LFrLegOffset+RotatorOffset,x[LEG_LEFT_FORE*JointsPerLeg+0]);
+	motman->setOutput(this,LFrLegOffset+ElevatorOffset,x[LEG_LEFT_FORE*JointsPerLeg+1]);
+	motman->setOutput(this,LFrLegOffset+KneeOffset,x[LEG_LEFT_FORE*JointsPerLeg+2]);
+	
+	motman->setOutput(this,RFrLegOffset+RotatorOffset,x[LEG_RIGHT_FORE*JointsPerLeg+0]);
+	motman->setOutput(this,RFrLegOffset+ElevatorOffset,x[LEG_RIGHT_FORE*JointsPerLeg+1]);
+	motman->setOutput(this,RFrLegOffset+KneeOffset,x[LEG_RIGHT_FORE*JointsPerLeg+2]);
+	
+	motman->setOutput(this,LBkLegOffset+RotatorOffset,x[LEG_LEFT_HIND*JointsPerLeg+0]);
+	motman->setOutput(this,LBkLegOffset+ElevatorOffset,x[LEG_LEFT_HIND*JointsPerLeg+1]);
+	motman->setOutput(this,LBkLegOffset+KneeOffset,x[LEG_LEFT_HIND*JointsPerLeg+2]);
+	
+	motman->setOutput(this,RBkLegOffset+RotatorOffset,x[LEG_RIGHT_HIND*JointsPerLeg+0]);
+	motman->setOutput(this,RBkLegOffset+ElevatorOffset,x[LEG_RIGHT_HIND*JointsPerLeg+1]);
+	motman->setOutput(this,RBkLegOffset+KneeOffset,x[LEG_RIGHT_HIND*JointsPerLeg+2]);
+}
+
+void
+UPennWalkMC::SetStanceParameters(double bodyTilt, double shoulderHeight,
+			    double foreX0, double foreY0,
+			    double hindX0, double hindY0) {
+  body_tilt = bodyTilt;
+  shoulder_height = shoulderHeight;
+  fore_x0 = foreX0;
+  fore_y0 = foreY0;
+  hind_x0 = hindX0;
+  hind_y0 = hindY0;
+}
+
+void
+UPennWalkMC::SetWalkSpeeds(int quarterPeriod, double maxDistance,
+			  double foreLiftInitial, double foreLiftFinal,
+			  double hindLiftInitial, double hindLiftFinal) {
+  walk_quarter_period = quarterPeriod;
+  walk_max_distance = maxDistance;
+  walk_fore_lift_initial = foreLiftInitial;
+  walk_fore_lift_final = foreLiftFinal;
+  walk_hind_lift_initial = hindLiftInitial;
+  walk_hind_lift_final = hindLiftFinal;
+}
+
+void
+UPennWalkMC::SetWalkWorkspace(double foreXMin, double foreXMax,
+			 double foreYMin, double foreYMax,
+			 double hindXMin, double hindXMax,
+			 double hindYMin, double hindYMax) {
+  walk_fore_xmin = foreXMin;
+  walk_fore_xmax = foreXMax;
+  walk_fore_ymin = foreYMin;
+  walk_fore_ymax = foreYMax;
+
+  walk_hind_xmin = hindXMin;
+  walk_hind_xmax = hindXMax;
+  walk_hind_ymin = hindYMin;
+  walk_hind_ymax = hindYMax;
+}
+
+// Calculate 12 leg joint angles from leg positions
+// Note positions are relative to stance parameters
+// so all zero inputs -> stance angles
+void
+UPennWalkMC::LegPositionsToAngles(double *a)
+{
+  double cosTilt = cos(body_tilt);
+  double sinTilt = sin(body_tilt);
+
+  double foreHeight = shoulder_height;
+  double hindHeight = shoulder_height - BODY_LENGTH*sinTilt;
+
+  for (int iLeg = 0; iLeg < 4; iLeg++) {
+    double posX=0, posY=0, posZ=0;
+    double dUpperZ = 0.0, dUpperY = 0.0, dLowerZ = 0.0, dLowerY = 0.0;
+
+    switch (iLeg) {
+    case LEG_LEFT_FORE:
+      // Left Fore: Reverse x
+      a[0] -= fore_x0;
+      a[1] += fore_y0;
+      a[2] -= foreHeight;
+
+      posX = -(a[0]);
+      posY = (cosTilt*a[1]+sinTilt*a[2]);
+      posZ = (-sinTilt*a[1]+cosTilt*a[2]);
+      dUpperZ = LEG_FORE_UPPER_Z;
+      dUpperY = LEG_FORE_UPPER_Y;
+      dLowerZ = LEG_FORE_LOWER_Z;
+      dLowerY = LEG_FORE_LOWER_Y;
+      break;
+    case LEG_LEFT_HIND:
+      // Left Hind: Reverse x,y
+      a[0] -= hind_x0;
+      a[1] += hind_y0;
+      a[2] -= hindHeight;
+
+      posX = -(a[0]);
+      posY = -(cosTilt*a[1]+sinTilt*a[2]);
+      posZ = (-sinTilt*a[1]+cosTilt*a[2]);
+
+      dUpperZ = LEG_HIND_UPPER_Z;
+      dUpperY = LEG_HIND_UPPER_Y;
+      dLowerZ = LEG_HIND_LOWER_Z;
+      dLowerY = LEG_HIND_LOWER_Y;
+      break;
+    case LEG_RIGHT_FORE:
+      // Right Fore:
+      a[0] += fore_x0;
+      a[1] += fore_y0;
+      a[2] -= foreHeight;
+
+      posX = (a[0]);
+      posY = (cosTilt*a[1]+sinTilt*a[2]);
+      posZ = (-sinTilt*a[1]+cosTilt*a[2]);
+
+      dUpperZ = LEG_FORE_UPPER_Z;
+      dUpperY = LEG_FORE_UPPER_Y;
+      dLowerZ = LEG_FORE_LOWER_Z;
+      dLowerY = LEG_FORE_LOWER_Y;
+      break;
+    case LEG_RIGHT_HIND:
+      // Right Hind: Reverse y
+      a[0] += hind_x0;
+      a[1] += hind_y0;
+      a[2] -= hindHeight;
+
+      posX = (a[0]);
+      posY = -(cosTilt*a[1]+sinTilt*a[2]);
+      posZ = (-sinTilt*a[1]+cosTilt*a[2]);
+
+      dUpperZ = LEG_HIND_UPPER_Z;
+      dUpperY = LEG_HIND_UPPER_Y;
+      dLowerZ = LEG_HIND_LOWER_Z;
+      dLowerY = LEG_HIND_LOWER_Y;
+      break;
+    default:
+      cerr << "UPennWalkMC::LegPositionsToAngles(): Unknown leg.\n" << endl;
+    }
+
+    double dUpper = sqrt(dUpperY*dUpperY+dUpperZ*dUpperZ);
+    double angleUpper = tan(dUpperY/dUpperZ);  // Positive
+
+    double dLower = sqrt(dLowerY*dLowerY+dLowerZ*dLowerZ);
+    double angleLower = tan(dLowerY/dLowerZ);  // Negative
+
+    double posSumSq = posX*posX+posY*posY+posZ*posZ;
+    
+    double cosJ3 = .5*(posSumSq-dUpper*dUpper-dLower*dLower)/(dUpper*dLower);
+    cosJ3 = clip(cosJ3, -1.0, 1.0);
+    // Correct for angle offsets of leg segments
+    a[2] = acos(cosJ3)+angleUpper-angleLower;
+
+    double aZ = -dUpperZ-dLower*cos(a[2]+angleLower);
+    double aY = dUpperY+dLower*sin(a[2]+angleLower);
+
+    double sinJ2 = -posX/aZ;
+    sinJ2 = clip(sinJ2, -1.0, 1.0);
+    a[1] = asin(sinJ2);
+
+    double J1a = atan2(aZ*cos(a[1]), aY);
+    double J1b = atan2(posZ, posY);
+    double J1 = J1b-J1a;
+    while (J1 > PI) J1 -= 2*PI;
+    while (J1 < -PI) J1 += 2*PI;
+    a[0] = J1;
+
+    a += 3;
+  }
+}
+
+void
+UPennWalkMC::StandLegs(double x/*=0*/, double y/*=0*/, double z/*=0*/)
+{
+  static double leg_joints[NUM_LEG_JOINT];
+  double *a = leg_joints;
+
+  for (int iLeg = 0; iLeg < 4; iLeg++) {
+    double center_x = 0, center_y = 0;
+    switch (iLeg) {
+    case LEG_LEFT_FORE:
+      center_x = -fore_x0;
+      center_y = fore_y0;
+      break;
+    case LEG_LEFT_HIND:
+      center_x = -hind_x0;
+      center_y = hind_y0;
+      break;
+    case LEG_RIGHT_FORE:
+      center_x = fore_x0;
+      center_y = fore_y0;
+      break;
+    case LEG_RIGHT_HIND:
+      center_x = hind_x0;
+      center_y = hind_y0;
+      break;
+    default:
+      cerr << "UPennWalkMC::StandLegs(): Unknown leg.\n" << endl;
+    }
+
+    a[0] = -x;
+    a[1] = -y;
+    a[2] = -z;
+
+    walk_current_x[iLeg] = center_x - x;
+    walk_current_y[iLeg] = center_y - y;
+
+    // Advance pointer to next leg angles:
+    a += 3;
+  }
+
+  LegPositionsToAngles(leg_joints);
+  SetLegJoints(leg_joints);
+
+}
+
+int
+UPennWalkMC::GetWalkPhase() {
+  return walk_phase;
+}
+
+void
+UPennWalkMC::SetWalkPhase(int phase) {
+  walk_phase = phase;
+}
+
+
+void
+UPennWalkMC::WalkLegs(double xWalk/*=0.0*/, double yWalk/*=0.0*/, double aWalk/*=0.0*/)
+{
+  // Check to see if legs should stand rather than walk
+  if ((walk_phase == 0) &&
+      (xWalk == 0.0) && (yWalk == 0.0) && (aWalk == 0.0)) {
+    StandLegs(0, 0, 0);
+    return;
+  }
+  
+  static double leg_joints[NUM_LEG_JOINT];
+  double *a = leg_joints;
+  bool switch_phase_direction = false;
+
+  //  double afactor = .7*BODY_LENGTH*aWalk; // 1/2*sqrt(2)
+  double afactor = .85*BODY_LENGTH*aWalk; // 1/2*sqrt(2)
+  double rnorm = sqrt(afactor*afactor + xWalk*xWalk + yWalk*yWalk);
+  if (rnorm > walk_max_distance) {
+    double scale = walk_max_distance/rnorm;
+    aWalk *= scale;
+    xWalk *= scale;
+    yWalk *= scale;
+  }
+
+  //  printf("WalkLegs: phase = %d, phase_direction = %d\n", walk_phase, walk_phase_direction);
+  int phase_diff_from_switch = walk_quarter_period+walk_phase_direction*walk_phase;
+  int phase_diff_to_switch = walk_quarter_period-walk_phase_direction*walk_phase;
+
+  double half_width = .5*BODY_WIDTH;
+  double half_length = .5*BODY_LENGTH*cos(body_tilt);
+
+  for (int iLeg = 0; iLeg < 4; iLeg++) {
+    double center_x = 0, center_y = 0; // Stance position center
+    double leg_offset_x = 0, leg_offset_y = 0; // Relative to center of body
+    double leg_lift_initial = 0, leg_lift_final = 0; // Lift heights
+    double xmin = 0.0, xmax = 0.0, ymin = 0.0, ymax = 0.0; // Workspace limits relative to shoulder
+    int leg_sign = 1;
+
+    double current_x = walk_current_x[iLeg];
+    double current_y = walk_current_y[iLeg];
+    
+    switch (iLeg) {
+    case LEG_LEFT_FORE:
+      leg_sign = 1;
+      center_x = -fore_x0;
+      center_y = fore_y0;
+
+      leg_offset_x = -half_width+center_x;
+      leg_offset_y = half_length+center_y;
+
+      leg_lift_initial = walk_fore_lift_initial;
+      leg_lift_final = walk_fore_lift_final;
+
+      xmin = -walk_fore_xmax; xmax = -walk_fore_xmin;
+      ymin = walk_fore_ymin; ymax = walk_fore_ymax;
+      break;
+    case LEG_LEFT_HIND:
+      leg_sign = -1;
+      center_x = -hind_x0;
+      center_y = hind_y0;
+
+      leg_offset_x = -half_width+center_x;
+      leg_offset_y = -half_length+center_y;
+
+      leg_lift_initial = walk_hind_lift_initial;
+      leg_lift_final = walk_hind_lift_final;
+
+      xmin = -walk_hind_xmax; xmax = -walk_hind_xmin;
+      ymin = walk_hind_ymin; ymax = walk_hind_ymax;
+      break;
+    case LEG_RIGHT_FORE:
+      leg_sign = -1;
+      center_x = fore_x0;
+      center_y = fore_y0;
+
+      leg_offset_x = half_width+center_x;
+      leg_offset_y = half_length+center_y;
+
+      leg_lift_initial = walk_fore_lift_initial;
+      leg_lift_final = walk_fore_lift_final;
+
+      xmin = walk_fore_xmin; xmax = walk_fore_xmax;
+      ymin = walk_fore_ymin; ymax = walk_fore_ymax;
+      break;
+    case LEG_RIGHT_HIND:
+      leg_sign = 1;
+      center_x = hind_x0;
+      center_y = hind_y0;
+
+      leg_offset_x = half_width+center_x;
+      leg_offset_y = -half_length+center_y;
+
+      leg_lift_initial = walk_hind_lift_initial;
+      leg_lift_final = walk_hind_lift_final;
+
+      xmin = walk_hind_xmin; xmax = walk_hind_xmax;
+      ymin = walk_hind_ymin; ymax = walk_hind_ymax;
+      break;
+    default:
+      cerr << "UPennWalkMC::WalkLegs(): Unknown leg.\n" << endl;
+    }
+
+    // Make relative to stance center:
+    current_x -= center_x;
+    current_y -= center_y;
+    xmin -= center_x;
+    xmax -= center_x;
+    ymin -= center_y;
+    ymax -= center_y;
+
+    double dx, dy;
+
+    // leg is up if leg_sign == walk_phase_direction
+    if (leg_sign == walk_phase_direction) {
+      // Leg is up
+      if (phase_diff_from_switch > 0) {
+
+	dx = xWalk + (cos(aWalk)-1)*leg_offset_x-sin(aWalk)*leg_offset_y;
+	dy = yWalk + sin(aWalk)*leg_offset_x+(cos(aWalk)-1)*leg_offset_y;
+
+	double destination_x = walk_quarter_period*dx;
+	double destination_y = walk_quarter_period*dy;
+
+      //      printf("Leg %d destination: %g, %g\n", iLeg, destination_x, destination_y);
+	dx = (destination_x-current_x)/(phase_diff_to_switch+1);
+	dy = (destination_y-current_y)/(phase_diff_to_switch+1);
+
+	current_x += dx;
+	current_y += dy;
+      }
+
+      current_x = clip(current_x, xmin, xmax);
+      current_y = clip(current_y, ymin, ymax);
+
+      a[0] = current_x;
+      a[1] = current_y;
+      a[2] = (phase_diff_from_switch*leg_lift_final+
+	      phase_diff_to_switch*leg_lift_initial)/(2*walk_quarter_period);
+
+    }
+    else {
+      // Leg is down
+
+      leg_offset_x += current_x;
+      leg_offset_y += current_y;
+      dx = xWalk + (cos(aWalk)-1)*leg_offset_x-sin(aWalk)*leg_offset_y;
+      dy = yWalk + sin(aWalk)*leg_offset_x+(cos(aWalk)-1)*leg_offset_y;
+
+      current_x -= dx; // Travels opposite direction as dx
+      current_y -= dy; // Travels opposite direction as dy
+
+      a[0] = current_x;
+      a[1] = current_y;
+      a[2] = 0;
+
+      // Check if leg is going outside workspace:
+      // This check is after writing leg positions to give extra reach
+      current_x = clip(current_x, xmin, xmax);
+      current_y = clip(current_y, ymin, ymax);
+
+      /*
+      Old code to advance phase to speed up cycle
+      if (walk_current_x[iLeg] < xmin) {
+	walk_current_x[iLeg] = xmin;
+	// Only switch direction after quarter_period has elapsed:
+	if (walk_phase_direction*walk_phase > 0)
+	  switch_phase_direction = true;
+      }
+      else if (walk_current_x[iLeg] > xmax) {
+	walk_current_x[iLeg] = xmax;
+	if (walk_phase_direction*walk_phase > 0)
+	  switch_phase_direction = true;
+      }
+      if (walk_current_y[iLeg] < ymin) {
+	walk_current_y[iLeg] = ymin;
+	if (walk_phase_direction*walk_phase > 0)
+	  switch_phase_direction = true;
+      }
+      else if (walk_current_y[iLeg] > ymax) {
+	walk_current_y[iLeg] = ymax;
+	if (walk_phase_direction*walk_phase > 0)
+	  switch_phase_direction = true;
+      }
+      */
+
+    }
+
+    //    printf("iLeg = %d: %g %g %g\n", iLeg, a[0],a[1],a[2]);
+
+    // Store current leg positions in coordinates relative to shoulder:
+    walk_current_x[iLeg] = current_x+center_x;
+    walk_current_y[iLeg] = current_y+center_y;
+
+    // Shift pointer to next leg:
+    a += 3;
+  }
+
+  /*
+  if (switch_phase_direction)
+  printf("WalkLegs: workspace switch: phase = %d, phase_direction = %d\n", walk_phase, walk_phase_direction);
+  */
+
+  // walk_phase goes oscillates between
+  // -walk_quarter_period to +walk_quarter_period:
+  walk_phase += walk_phase_direction;
+  if ((walk_phase > walk_quarter_period) ||
+      (walk_phase < -walk_quarter_period)) {
+    switch_phase_direction = true;
+  }
+
+  if (switch_phase_direction) {
+    // Switch legs:
+    walk_phase = walk_phase_direction*walk_quarter_period;
+    walk_phase_direction = -walk_phase_direction;
+  }
+  
+  LegPositionsToAngles(leg_joints);
+  SetLegJoints(leg_joints);
+
+  // Update odometry:
+  // Commenting out to put odometry control in Perl:
+  //  Self.world->AddMotionUpdate(xWalk, yWalk, aWalk);
+  
+}
+
+
+
+
+/*! @file
+ * @brief Defines UPennWalkMC, which uses the UPennalizers' 2004 RoboCup code to compute walking gaits
+ * @author UPennalizers 2004 (Creator)
+ * @author ejt (Ported)
+ *
+ * The UPennalizers code was released under the GPL:\n
+ *  ------------------------------------------------------------------------- \n
+ *    This software is distributed under the GNU General Public License,      \n
+ *    version 2.  If you do not have a copy of this licence, visit            \n
+ *    www.gnu.org, or write: Free Software Foundation, 59 Temple Place,       \n
+ *    Suite 330 Boston, MA 02111-1307 USA.  This program is distributed       \n
+ *    in the hope that it will be useful, but WITHOUT ANY WARRANTY,           \n
+ *    including MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          \n
+ *  ------------------------------------------------------------------------- \n
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.1 $
+ * $State: Exp $
+ * $Date: 2005/04/12 21:33:31 $
+ */
diff -urdN ../Tekkotsu_2.3/Motion/UPennWalkMC.h ./Motion/UPennWalkMC.h
--- ../Tekkotsu_2.3/Motion/UPennWalkMC.h	Wed Dec 31 19:00:00 1969
+++ ./Motion/UPennWalkMC.h	Tue Apr 12 18:18:34 2005
@@ -0,0 +1,115 @@
+//-*-c++-*-
+#ifndef INCLUDED_UPennWalkMC_h_
+#define INCLUDED_UPennWalkMC_h_
+
+#include "Motion/MotionCommand.h"
+#include "Motion/MotionManager.h"
+
+//! Uses the UPennalizers' 2004 RoboCup code to compute walking gaits
+
+/*! This class is ported from University of Pennsylvania's 2004 Robosoccer entry, and falls under their license:
+    =========================================================================
+    This software is distributed under the GNU General Public License,
+	  version 2.  If you do not have a copy of this licence, visit
+    www.gnu.org, or write: Free Software Foundation, 59 Temple Place,
+    Suite 330 Boston, MA 02111-1307 USA.  This program is distributed
+    in the hope that it will be useful, but WITHOUT ANY WARRANTY,
+	  including MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+    ========================================================================= */
+
+class UPennWalkMC : public MotionCommand {
+public:
+	//! constructor
+	UPennWalkMC();
+
+	virtual int updateOutputs() {
+		/*if(sqrt(xVel*xVel+yVel*yVel+aVel*aVel)<.01)
+			StandLegs(xVel,yVel,aVel);
+			else */
+		WalkLegs(xVel,yVel,aVel);
+		return NumLegJoints;
+	}
+
+	virtual int isDirty() { return true; }
+	virtual int isAlive() { return true; }
+
+	void setTargetVelocity(float x, float y, float a) { xVel=-y; yVel=x; aVel=a; }
+
+protected:
+	void SetLegJoints(double * x);
+
+	inline static double clip(double x, double min=-1.0, double max=1.0)
+	{
+		if (x < min) return min;
+		if (x > max) return max;
+		return x;
+	}
+
+	void SetStanceParameters(double bodyTilt, double shoulderHeight,
+	                         double foreX0, double foreY0,
+	                         double hindX0, double hindY0);
+	
+	void SetWalkSpeeds(int quarterPeriod, double maxDistance,
+	                   double foreLiftInitial, double foreLiftFinal,
+	                   double hindLiftInitial, double hindLiftFinal);
+	
+	void SetWalkWorkspace(double foreXMin, double foreXMax,
+	                      double foreYMin, double foreYMax,
+	                      double hindXMin, double hindXMax,
+	                      double hindYMin, double hindYMax);
+	
+	//! Calculate 12 leg joint angles from leg positions
+	/*! Note positions are relative to stance parameters
+	 *  so all zero inputs -> stance angles */
+	void UPennWalkMC::LegPositionsToAngles(double *a);
+
+	void StandLegs(double x=0, double y=0, double z=0);
+
+	int  GetWalkPhase();
+
+	void SetWalkPhase(int phase);
+
+	void WalkLegs(double xWalk=0.0, double yWalk=0.0, double aWalk=0.0);
+
+	float xVel;
+	float yVel;
+	float aVel;
+
+	double body_tilt, shoulder_height;
+	double fore_x0, fore_y0;
+	double hind_x0, hind_y0;
+
+	int walk_phase, walk_phase_direction, walk_quarter_period;
+	double walk_max_distance;
+	double walk_fore_lift_initial, walk_fore_lift_final;
+	double walk_hind_lift_initial, walk_hind_lift_final;
+	double walk_current_x[NumLegs], walk_current_y[NumLegs];
+	double walk_fore_xmin, walk_fore_xmax, walk_fore_ymin, walk_fore_ymax;
+	double walk_hind_xmin, walk_hind_xmax, walk_hind_ymin, walk_hind_ymax;
+
+};
+
+/*! @file
+ * @brief Defines UPennWalkMC, which uses the UPennalizers' 2004 RoboCup code to compute walking gaits
+ * @author UPennalizers 2004 (Creator)
+ * @author ejt (Ported)
+ *
+ * The UPennalizers code was released under the GPL:\n
+ *  ------------------------------------------------------------------------- \n
+ *    This software is distributed under the GNU General Public License,      \n
+ *    version 2.  If you do not have a copy of this licence, visit            \n
+ *    www.gnu.org, or write: Free Software Foundation, 59 Temple Place,       \n
+ *    Suite 330 Boston, MA 02111-1307 USA.  This program is distributed       \n
+ *    in the hope that it will be useful, but WITHOUT ANY WARRANTY,           \n
+ *    including MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          \n
+ *  ------------------------------------------------------------------------- \n
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/04/12 22:18:34 $
+ */
+
+#endif
+
diff -urdN ../Tekkotsu_2.3/Motion/WalkMC.cc ./Motion/WalkMC.cc
--- ../Tekkotsu_2.3/Motion/WalkMC.cc	Mon Dec 20 16:26:24 2004
+++ ./Motion/WalkMC.cc	Wed Jun 29 18:01:55 2005
@@ -59,11 +59,12 @@
 unsigned int checksum(const char *data,int num); //!< computes a file checksum
 
 WalkMC::WalkMC(const char* pfile/*=NULL*/)
-	: MotionCommand(), isPaused(false), wp(), cp(), body_loc(), body_angle(), acc_style(DEFAULT_ACCEL), step_count(-1), last_cycle(0),
-				pos_delta(0,0,0), angle_delta(0), travelTime(get_time()),
-				time(get_time()), TimeStep(FrameTime), slowmo(1.0f),
-				CycleOffset(0), TimeOffset(0), NewCycleOffset(false),
-				vel_xya(0,0,0), target_vel_xya(0,0,0), last_target_vel_xya(0,0,0)
+	: MotionCommand(), isPaused(false), wp(), cp(), body_loc(), body_angle(),
+		acc_style(DEFAULT_ACCEL), step_count(-1), step_threshold(0), last_cycle(0),
+		pos_delta(0,0,0), angle_delta(0), travelTime(get_time()),
+		time(get_time()), TimeStep(FrameTime), slowmo(1.0f),
+		CycleOffset(0), TimeOffset(0), NewCycleOffset(false),
+		vel_xya(0,0,0), target_vel_xya(0,0,0), last_target_vel_xya(0,0,0)
 {
 	init(pfile);
 }
@@ -93,7 +94,8 @@
 void WalkMC::DoStop() {
 	unsigned int t=get_time();
 	LocomotionEvent e(EventBase::locomotionEGID,getID(),EventBase::deactivateETID,t-travelTime);
-	e.setXYA(target_vel_xya.x,target_vel_xya.y,target_vel_xya.z);
+	//leave values at 0!
+	//e.setXYA(target_vel_xya.x,target_vel_xya.y,target_vel_xya.z);
 	postEvent(e);
 	travelTime=t;
 	MotionCommand::DoStop();
@@ -272,9 +274,23 @@
 	if(n==0) {
 		setTargetVelocity(0,0,0,0);
 	} else {
-		double vx=dx/(n*wp.period/1000.0);
-		double vy=dy/(n*wp.period/1000.0);
-		double va=da/(n*wp.period/1000.0);
+		//compute the point in cycle of the mid-step
+		float midsteps[NumLegs];
+		for(unsigned int i=0; i<NumLegs; i++)
+			midsteps[i] = (wp.leg[i].down_time+wp.leg[i].lift_time)/2;
+		//find the number of unique steps per cycle
+		unsigned int steps_per_cycle=4;
+		for(unsigned int i=0; i<NumLegs-1; i++)
+			for(unsigned int j=i+1; j<NumLegs; j++)
+				if(midsteps[i]==midsteps[j]) {
+					steps_per_cycle--;
+					break;
+				}
+		//compute velocity needed to move requested distance in the time it takes to do n steps
+		double scale=steps_per_cycle/(n*wp.period/1000.0);
+		double vx=dx*scale;
+		double vy=dy*scale;
+		double va=da*scale;
 		setTargetVelocity(vx,vy,va,n); //apply new value
 	}
 }
@@ -294,6 +310,7 @@
 		last_target_vel_xya=target_vel_xya;
 		LocomotionEvent e(EventBase::locomotionEGID,getID(),EventBase::statusETID,getTravelTime());
 		e.setXYA(target_vel_xya.x,target_vel_xya.y,target_vel_xya.z);
+		//cout << e.getDescription(true) << endl;
 		postEvent(e);
 		travelTime=curT;
 	}
@@ -361,13 +378,19 @@
 		double cycle = (double)(AdjustedTime % wp.period) / wp.period;
 
 		if(step_count>0) {
-			float ncyc=cycle;
-			if(cycle<last_cycle)
-				ncyc+=1;
 			for(unsigned int i=0; i<NumLegs; i++){
-				float midstep = (wp.leg[i].down_time+wp.leg[i].lift_time)/2;
+				float midstep;
+				if(step_threshold<=.5f)
+					midstep=wp.leg[i].lift_time+(wp.leg[i].down_time-wp.leg[i].lift_time)*step_threshold*2;
+				else
+					midstep=wp.leg[i].down_time+(1-wp.leg[i].down_time+wp.leg[i].lift_time)*(step_threshold-.5)*2;
+				midstep-=floorf(midstep);
 				//cout << "leg "<<i<<": " <<AdjustedTime << ' ' << cycle << ' ' << last_cycle << ' ' << midstep << ' ' <<step_count ;
-				if(last_cycle<midstep && midstep<=ncyc) { //we just completed a step
+				bool above_last= (last_cycle<midstep);
+				bool below_cur = (midstep<=cycle);
+				bool wrap      = (cycle<last_cycle);
+				//need any 2 of the conditions: above_last && below_cur || wrap && (above_last || below_cur)
+				if(above_last+below_cur+wrap>1) { //we just completed a step
 					step_count--;
 					//cout << " -> " << step_count << endl;
 					if(step_count==0) { //we're done, copy out any completed frames
@@ -377,6 +400,12 @@
 						CycleOffset = AdjustedTime % wp.period;
 						NewCycleOffset = true;
 						last_cycle=cycle;
+						target_vel_xya.set(0,0,0);
+						last_target_vel_xya=target_vel_xya;
+						LocomotionEvent e(EventBase::locomotionEGID,getID(),EventBase::statusETID,getTravelTime());
+						e.setXYA(target_vel_xya.x,target_vel_xya.y,target_vel_xya.z);
+						//cout << e.getDescription(true) << endl;
+						postEvent(e);
 						//		cout << "WalkMC-done" << endl;
 						return frame==0?0:NumLegs*JointsPerLeg;
 					}
@@ -593,9 +622,9 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.30 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.34 $
  * $State: Exp $
- * $Date: 2004/12/20 21:26:24 $
+ * $Date: 2005/06/29 22:01:55 $
  */
 
diff -urdN ../Tekkotsu_2.3/Motion/WalkMC.h ./Motion/WalkMC.h
--- ../Tekkotsu_2.3/Motion/WalkMC.h	Wed Dec 22 20:47:07 2004
+++ ./Motion/WalkMC.h	Tue Apr 12 15:07:07 2005
@@ -146,11 +146,12 @@
 	virtual unsigned int SaveFile(const char* filename) const;
 
 	//! set the direction to walk
-	/*! @param dx forward velocity
-	 *  @param dy left velocity
-	 *  @param da counterclockwise velocity
+	/*! @param dx forward velocity (millimeters per second)
+	 *  @param dy left velocity (millimeters per second)
+	 *  @param da counterclockwise velocity (radians per second)
 	 *  @param n steps to take (if unspecified or negative, walk forever)
-	 *  Using a non-negative step count disables software acceleration of velocities */
+	 *  Using a non-negative step count disables software acceleration of velocities
+	 *  @see setTargetDisplacement() */
 	void setTargetVelocity(double dx,double dy,double da,int n=-1);
 	//! returns current velocity we're trying to go
 	const vector3d& getTargetVelocity() { return target_vel_xya; }
@@ -169,11 +170,16 @@
 	 *  #step_count will be set to @a n, so if the required velocity is
 	 *  beyond the abilities of the robot, it will stop on the @a n'th
 	 *  step, regardless of distance remaining.
+	 *  @see setTargetVelocity()
 	 */
 	void setTargetDisplacement(double dx, double dy, double da, unsigned int n);
 
 	//! returns remaining steps (#step_count) (negative means infinite)
-	int getRemainingSteps() { return step_count; }
+	int getRemainingSteps() const { return step_count; }
+
+	
+	float getStepThreshold() const { return step_threshold; } //!< returns the step threshold -- see #step_threshold
+	void setStepThreshold(float st) { step_threshold=st; } //!< sets the step threshold -- see #step_threshold
 	
 	void setPaused(bool p) { isPaused=p; } //!< if set to true, will stop moving
 	bool getPaused() const { return isPaused; } //!< if is true, we aren't moving
@@ -239,6 +245,7 @@
 	AccelerationStyle_t acc_style; //!< lets you switch between finite or infinite acceleration models
 
 	int step_count; //!< number of steps to take before stopping; if negative, walk forever.
+	float step_threshold; //!< point in a leg's cycle where the step counter should be decremented; 0 - leg lift, .25 - mid-air, .5 - leg down, .75 - mid-ground
 
 	double last_cycle; //!< where the walk is in it its cycle, updated at the end of each call to updateOutputs()
 
@@ -303,10 +310,10 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.29 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.31 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/04/12 19:07:07 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/WaypointEngine.h ./Motion/WaypointEngine.h
--- ../Tekkotsu_2.3/Motion/WaypointEngine.h	Tue Jul 27 10:33:59 2004
+++ ./Motion/WaypointEngine.h	Tue Aug  9 19:00:50 2005
@@ -2,7 +2,7 @@
 #ifndef INCLUDED_WaypointEngine_h_
 #define INCLUDED_WaypointEngine_h_
 
-#include "Shared/ListMemBuf.h"
+#include "IPC/ListMemBuf.h"
 #include "Shared/LoadSave.h"
 
 //! Provides computation and management of a desired path through a series of waypoints
@@ -20,37 +20,96 @@
  *  can use either circular arcs or straight lines.
  *
  *  The Waypoint class holds the actual data about each waypoint.  You
- *  can specify waypoints in 3 ways, egocentric, offset, and absolute.
- *  - Egocentric: the x and y parameters are relative to the body
+ *  can specify waypoints in 3 ways: egocentric, offset, and absolute.
+ *
+ *  <table cellspacing=0 cellpadding=0 width="750" class="figures" align="center" border="0"><tr>
+ *  <td class="figure"><img src="Waypoint_Ego.png"><div style="padding:10px;">
+ *    @b Egocentric: the x and y parameters are relative to the body
  *    itself; x is always forward and y is always left.  Handy for
- *    turtle/logo style specification of a series of instructions which
- *    specify the waypoints.
- *  - Offset: the x and y parameters are relative to the current body
+ *    turtle/logo style specification of instructions
+ *  </div></td><td class="figure"><img src="Waypoint_Off.png"><div style="padding:10px;">
+ *    @b Offset: the x and y parameters are relative to the current body
  *    position, but not its heading.
- *  - Absolute: the x and y parameters are direct coordinates
+ *  </div></td><td class="figure"><img src="Waypoint_Abs.png"><div style="padding:10px;">
+ *    @b Absolute: the x and y parameters are direct coordinates
+ *  </div></td></tr></table>
  *
- *  In addition, you can specify how to handle the heading of the body
- *  while the path is executing.  You can specify a relative offset to
- *  the direction of travel (for instance, to walk sideways instead of
- *  forward), or an absolute value (to always face a certain direction
- *  while traveling)
+ *  These specify the @e position of the next waypoint, but we also need
+ *  to be able to specify the @e orientation (heading) of the robot.  This
+ *  is done by specifying an angle and a mode which controls how that
+ *  angle is interpreted: Waypoint::angleIsRelative, which can be @c true or @c false.
+ *
+ *  <table cellspacing=0 cellpadding=0 width="500" class="figures" align="center" border="0"><tr>
+ *  <td class="figure"><img src="Waypoint_AngleRel.png"><div style="padding:10px;">
+ *  <code>angleIsRelative==</code>@b true: The angle is relative to the path, so that @c 0 will keep
+ *  the robot pointed in the direction of travel, even when arcing.  Similarly, @f$\pi/2\ (90^\circ)@f$
+ *  would cause the robot to walk sideways.
+ *  </div></td><td class="figure"><img src="Waypoint_AngleAbs.png"><div style="padding:10px;">
+ *  <code>angleIsRelative==</code>@b false: The angle is relative to the world coordinate system, so a 
+ *  constant heading is maintained throughout execution of the path.
+ *  </div></td></tr></table>
+ *
+ *  The final orientation of the robot is simply the heading it was
+ *  facing when it reaches the end point.  To turn in place, you can
+ *  use a (0,0) egocentric or offset waypoint with an angle parameter.
+ *
+ *  In order to execute curves, you can supply an arc value:
+ *
+ *  <table cellspacing=0 cellpadding=0 width="417" class="figures" align="center" border="0"><tr>
+ *  <td class="figure"><img src="Waypoint_Arc.png"><div style="padding:10px;">
+ *  Here you see the results of 3 different arc values @f$(60^\circ,120^\circ,180^\circ)@f$.  Note how
+ *  the arc parameter corresponds to the angle of the circle which is swept.<br>
+ *  </div></td></tr></table>
+ *
+ *  There are two ways to specify arcs.  The @c add*Waypoint functions
+ *  use the position arguments to specify the <em>end point</em> of
+ *  the arc, and the arc parameter serves to "bow" the path.  The @c
+ *  add*Arc functions specify the <em>center of the circle</em> as the
+ *  position, and the end point is inferred from the amount of the arc
+ *  to sweep.
+ *
+ *  Beware that arcs greater than @f$180^\circ@f$ are entirely
+ *  possible, but will create larger and larger circles which may
+ *  cause the robot to initially start moving @e away from the
+ *  destination.  This isn't necessarily a bad thing, but may be
+ *  unanticipated.  Values approaching @f$2\pi\ (360^\circ)@f$ may
+ *  cause numerical instability yielding infinitely large circles.
+ *  Values larger than @f$2\pi\ (360^\circ)@f$ will be normalized to
+ *  the range @f$[0,2\pi)@f$.
  *
  *  Dead reckoning is very prone to accruing error.  It is highly
  *  recommended that you calibrate the locomotion mechanism carefully
- *  and implement some form of localization to handle the inevitable
- *  drift.
+ *  (see WalkCalibration, available under the "Walk Edit" menu with a
+ *  run-time help menu) and implement some form of localization to
+ *  handle the inevitable drift.
+ *
+ *  If you have a localization module in place, you can use the
+ *  setCurPos() function to update the position of the robot within
+ *  the world.  WaypointEngine provides two ways to handle this
+ *  ensuing discrepency from the path the robot had been tracing:
+ *
+ *  <table cellspacing=0 cellpadding=0 width="325" class="figures" align="center" border="0"><tr>
+ *  <td class="figure"><img src="Waypoint_Error.png"><div style="padding:10px;">
+ *  The effect of the Waypoint::trackPath flag.  When @c true, the robot will attempt to catch up
+ *  to its "ideal" location after a perterbation.  When @c false, the robot will ignore the "ideal"
+ *  path, and just go straight to the destination from wherever perterbations may push it.
+ *  </div></td></tr></table>
+ *
+ *  trackPath is a per-waypoint setting, setTracking() sets the
+ *  default value for any new waypoints which are thereafter created
+ *  (the default default is false ;)
  *
  *  Waypoint list files are a fairly straightforward plain text format.
  *  The extension .wyp is suggested.
  *
- *  The format is:
- *  - '<tt>#WyP</tt>' - header to verify file type
+ *  The waypoint file format is:
+ *  - '<tt>\#WyP</tt>' - header to verify file type
  *  - A series of entries:
  *    - '<tt>max_turn_speed </tt><i>num</i>' - sets the maximum error-correction turning speed used for all following waypoints
  *    - '<tt>track_path </tt><i>bool</i>' - sets trackpath mode on or off for all following waypoints (see Waypoint::trackPath)
  *    - '<tt>add_point </tt>{<tt>ego</tt>|<tt>off</tt>|<tt>abs</tt>}<tt> </tt><i>x_val</i><tt> </tt><i>y_val</i><tt> </tt>{<tt>hold</tt>|<tt>follow</tt>}<tt> </tt><i>angle_val</i><tt> </tt><i>speed_val</i><tt> </tt><i>arc_val</i>' - adds the waypoint with the parameters given, see Waypoint, similar to add*Waypoint functions
  *    - '<tt>add_arc </tt>{<tt>ego</tt>|<tt>off</tt>|<tt>abs</tt>}<tt> </tt><i>x_val</i><tt> </tt><i>y_val</i><tt> </tt>{<tt>hold</tt>|<tt>follow</tt>}<tt> </tt><i>angle_val</i><tt> </tt><i>speed_val</i><tt> </tt><i>arc_val</i>' - adds the waypoint with the parameters given, see Waypoint, similar to add*Arc functions
- *  - '<tt>#END</tt>' - footer to verify ending of file
+ *  - '<tt>\#END</tt>' - footer to verify ending of file
  */
 template<unsigned int MAX_WAY>
 class WaypointEngine : public LoadSave {
@@ -104,6 +163,8 @@
 	virtual unsigned int getBinSize() const;
 	virtual unsigned int LoadBuffer(const char buf[], unsigned int len);
 	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
+	virtual unsigned int LoadFile(const char * filename) { return LoadSave::LoadFile(config->motion.makePath(filename).c_str()); }
+	virtual unsigned int SaveFile(const char * filename) const { return LoadSave::SaveFile(config->motion.makePath(filename).c_str()); }
 
 	virtual void go();      //!< starts walking towards the first waypoint
 	virtual void pause();   //!< halts execution of waypoint list
@@ -125,6 +186,9 @@
 		curPos[0]=x; curPos[1]=y; curPos[2]=a;
 	}
 
+	virtual void setTracking(bool b) { isTracking=b; } //!< sets the #isTracking flag, only affects future waypoints which are added, not currently listed waypoints (use getWaypointList() to modify existing waypoints)
+	virtual bool getTracking() const { return isTracking; } //!< returns #isTracking
+
 	//! call this on each opportunity to check current location and correct velocities
 	/*! @return #isRunning for convenience of checking if anything is happening */
 	virtual bool cycle(); 
@@ -133,7 +197,8 @@
 	//!@name Adding Waypoints
 
 	//! adds a waypoint to the end of the list, allows you to specify turtle-style instructions
-	/*! @param forward distance forward to move (negative to move backward of course)
+	/*! <img src="Waypoint_Ego.png">
+	 *  @param forward distance forward to move (negative to move backward of course)
 	 *  @param left distance to the left to move (negative to move right of course)
 	 *  @param angle angle of attack to use on the path
 	 *  @param angleIsRelative controls interpretation of @a angle; true means angle specifies an offset from the bearing of the target waypoint, false means maintain an absolute heading
@@ -142,7 +207,8 @@
 		waypoints.push_back(Waypoint(forward,left,Waypoint::POSTYPE_EGOCENTRIC,angle,angleIsRelative,speed,isTracking,turnSpeed));
 	}
 	//! adds a waypoint to the end of the list, allows you to set locations relative to the location of the previous waypoint (or starting position)
-	/*! @param x distance delta along x axis of the waypoint
+	/*! <img src="Waypoint_Off.png">
+	 *  @param x distance delta along x axis of the waypoint
 	 *  @param y distance delta along y axis of the waypoint
 	 *  @param angle angle of attack to use on the path
 	 *  @param angleIsRelative controls interpretation of @a angle; true means angle specifies an offset from the bearing of the target waypoint, false means maintain an absolute heading
@@ -150,8 +216,9 @@
 	virtual void addOffsetWaypoint(float x, float y, float angle, bool angleIsRelative, float speed) {
 		waypoints.push_back(Waypoint(x,y,Waypoint::POSTYPE_OFFSET,angle,angleIsRelative,speed,isTracking,turnSpeed));
 	}
-	//! adds a waypoint to the end of the list, allows you to set locations relative to the location of the previous waypoint (or starting position)
-	/*! @param x position along x axis of the waypoint
+	//! adds a waypoint to the end of the list, allows you to set locations relative to the world coordinate frame
+	/*! <img src="Waypoint_Abs.png">
+	 *  @param x position along x axis of the waypoint
 	 *  @param y position along y axis of the waypoint
 	 *  @param angle angle of attack to use on the path
 	 *  @param angleIsRelative controls interpretation of @a angle; true means angle specifies an offset from the bearing of the target waypoint, false means maintain an absolute heading
@@ -161,37 +228,40 @@
 	}
 
 	//! adds a waypoint to the end of the list, using an arcing path to get there, allows you to specify turtle-style instructions to specify the focus of the arc
-	/*! If you would rather specify the ending point and then "bow" the path, try addEgocentricWaypoint() followed by setting the Waypoint::arc field directly
+	/*! <img src="Waypoint_Ego.png">
+	 *  If you would rather specify the ending point and then "bow" the path, try addEgocentricWaypoint() followed by setting the Waypoint::arc field directly
 	 *  @param forward distance in front of the center of the circle of the arc
 	 *  @param left distance to the left of the center of the circle of the arc
 	 *  @param angle angle of attack to use on the path
 	 *  @param angleIsRelative controls interpretation of @a angle; true means angle specifies an offset from the bearing of the target waypoint, false means maintain an absolute heading
 	 *  @param speed is the speed to move at; meters per second
-	 *  @param arc is the number of radians the arc fills; arcs near 0 (or multiples of 360) may cause numeric instability*/
+	 *  @param arc is the number of radians the arc fills; arcs near 0 (or multiples of 360) may cause numeric instability */
 	virtual void addEgocentricArc(float forward, float left, float angle, bool angleIsRelative, float speed, float arc) {
 		addEgocentricWaypoint(forward,left,angle,angleIsRelative,speed);
 		fixArc(arc);
 	}
 	//! adds a waypoint to the end of the list, using an arcing path to get there, allows you to specify locations relative to previous waypoint to specify the focus of the arc
-	/*! If you would rather specify the ending point and then "bow" the path, try addOffsetWaypoint() followed by setting the Waypoint::arc field directly
+	/*! <img src="Waypoint_Off.png">
+	 *  If you would rather specify the ending point and then "bow" the path, try addOffsetWaypoint() followed by setting the Waypoint::arc field directly
 	 *  @param x distance delta along x of the center of the circle of the arc
 	 *  @param y distance delta along y of the center of the circle of the arc
 	 *  @param angle angle of attack to use on the path
 	 *  @param angleIsRelative controls interpretation of @a angle; true means angle specifies an offset from the bearing of the target waypoint, false means maintain an absolute heading
 	 *  @param speed is the speed to move at; meters per second
-	 *  @param arc is the number of radians the arc fills; arcs near 0 (or multiples of 360) may cause numeric instability*/
+	 *  @param arc is the number of radians the arc fills; arcs near 0 (or multiples of 360) may cause numeric instability */
 	virtual void addOffsetArc(float x, float y, float angle, bool angleIsRelative, float speed, float arc) {
 		addOffsetWaypoint(x,y,angle,angleIsRelative,speed);
 		fixArc(arc);
 	}
 	//! adds a waypoint to the end of the list, using an arcing path to get there, allows you to specify absolute locations to specify the focus of the arc
-	/*! If you would rather specify the ending point and then "bow" the path, try addAbsoluteWaypoint() followed by setting the Waypoint::arc field directly
+	/*! <img src="Waypoint_Abs.png">
+	 *  If you would rather specify the ending point and then "bow" the path, try addAbsoluteWaypoint() followed by setting the Waypoint::arc field directly
 	 *  @param x position along x of the center of the circle of the arc
 	 *  @param y position along y of the center of the circle of the arc
 	 *  @param angle angle of attack to use on the path
 	 *  @param angleIsRelative controls interpretation of @a angle; true means angle specifies an offset from the bearing of the target waypoint, false means maintain an absolute heading
 	 *  @param speed is the speed to move at; meters per second
-	 *  @param arc is the number of radians the arc fills; arcs near 0 (or multiples of 360) may cause numeric instability*/
+	 *  @param arc is the number of radians the arc fills; arcs near 0 (or multiples of 360) may cause numeric instability */
 	virtual void addAbsoluteArc(float x, float y, float angle, bool angleIsRelative, float speed, float arc) {
 		addAbsoluteWaypoint(x,y,angle,angleIsRelative,speed);
 		fixArc(arc);
@@ -409,7 +479,7 @@
 unsigned int WaypointEngine<MAX_WAY>::LoadBuffer(const char buf[], unsigned int len) {
 	unsigned int origlen=len;
 	waypoints.clear();
-	if(strncmp("#WyP\n",buf,5)!=0) {
+	if(strncmp("#WyP\n",buf,5)!=0 && strncmp("#WyP\r",buf,5)!=0) {
 		return 0;
 	}
 
@@ -424,19 +494,39 @@
 	float angle_val=0;
 	float speed_val=0;
 	float arc_val=0;
-	unsigned int linenum=2;
+	unsigned int linenum=1;
 	while(len<=origlen && len>0) {
 		//		printf("%d %.9s\n",linenum+1,buf);
-		if(buf[0]=='#' || buf[0]=='\n') {
-			if(strncmp("#END\n",buf,5)==0)
-				return origlen-len;
-			else {
-				while(*buf++!='\n') {}
+		if(buf[0]=='\r') {
+			buf++; len--;
+			if(buf[0]=='\n') {
+				buf++; len--;
+			}
+			linenum++;
+			continue;
+		}
+		if(buf[0]=='\n') {
+			buf++; len--;
+			linenum++;
+			continue;
+		}
+		if(buf[0]=='#') {
+			if(strncmp("#END\n",buf,5)==0 || strncmp("#END\r",buf,5)==0) {
+				return origlen-len+5;
+			} else if(strncmp("#END\r\n",buf,6)==0) {
+				return origlen-len+6;
+			} else {
+				while(len>0 && *buf!='\n' && *buf!='\r') {len--;buf++;}
+				if(*buf=='\n') { //in case of \r\n
+					buf++;
+					len--;
+				}
+				linenum++;
 				continue;
 			}
 		}
 		int used=-1U;
-		sscanf(buf,"%40s%n",&cmd,&used);
+		sscanf(buf,"%40s%n",cmd,&used);
 		if(!ChkAdvance(used,&buf,&len,"*** ERROR Waypoint list load corrupted - ran out of room line %d\n",linenum)) return 0;
 		if(strncasecmp(cmd,"add_point",9)==0 || strncasecmp(cmd,"add_arc",7)==0) {
 			sscanf(buf,"%40s %g %g %40s %g %g %g%n",posType,&x_val,&y_val,angType,&angle_val,&speed_val,&arc_val,&used);
@@ -476,7 +566,9 @@
 			waypoints.back().trackPath=track;
 			waypoints.back().turnSpeed=turn;
 		} else if(strncasecmp(cmd,"track_path",10)==0) {
-			sscanf(buf,"%d%n",&track,&used);
+			int track_tmp;
+			sscanf(buf,"%d%n",&track_tmp,&used);
+			track=track_tmp;
 			if(!ChkAdvance(used,&buf,&len,"*** ERROR Waypoint load corrupted - bad read on track_path line %d\n",linenum)) return 0;
 		} else if(strncasecmp(cmd,"max_turn_speed",14)==0) {
 			sscanf(buf,"%g%n",&turn,&used);
@@ -750,10 +842,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2004/07/27 14:33:59 $
+ * $Date: 2005/08/09 23:00:50 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/WaypointWalkMC.h ./Motion/WaypointWalkMC.h
--- ../Tekkotsu_2.3/Motion/WaypointWalkMC.h	Tue Jul 27 10:33:59 2004
+++ ./Motion/WaypointWalkMC.h	Wed Jun  1 01:47:48 2005
@@ -2,7 +2,7 @@
 #ifndef INCLUDED_WaypointWalk_h_
 #define INCLUDED_WaypointWalk_h_
 
-#include "Shared/ListMemBuf.h"
+#include "IPC/ListMemBuf.h"
 #include "WalkMC.h"
 #include "WaypointEngine.h"
 
@@ -29,8 +29,8 @@
 	
 	//! so we can get our hooks in to modify the target velocity
 	virtual int updateOutputs() {
-		cycle();
-		WalkMC::setTargetVelocity(curVel[0]*1000,curVel[1]*1000,curVel[2]);
+		WaypointEngine<MAX_WAY>::cycle();
+		WalkMC::setTargetVelocity(WaypointEngine<MAX_WAY>::curVel[0]*1000,WaypointEngine<MAX_WAY>::curVel[1]*1000,WaypointEngine<MAX_WAY>::curVel[2]);
 		//cout << get_time()-waypointTime << " Cur: ("<<curPos[0]<<','<<curPos[1]<<','<<curPos[2]<<")  Ideal: ("<<idealPos[0]<<','<<idealPos[1]<<','<<idealPos[2]<<','<<idealPos[3]<<")  Vel: ("<<curVel[0]<<','<<curVel[1]<<','<<curVel[2]<<")" << endl;
 		return WalkMC::updateOutputs();
 	}
@@ -50,10 +50,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2004/07/27 14:33:59 $
+ * $Date: 2005/06/01 05:47:48 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Motion/gvector.h ./Motion/gvector.h
--- ../Tekkotsu_2.3/Motion/gvector.h	Thu Sep 25 11:27:23 2003
+++ ./Motion/gvector.h	Thu Sep 25 11:27:23 2003
@@ -677,7 +677,7 @@
  * @endverbatim
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Rel $
  * $Date: 2003/09/25 15:27:23 $
diff -urdN ../Tekkotsu_2.3/Motion/roboop/CVS/Entries ./Motion/roboop/CVS/Entries
--- ../Tekkotsu_2.3/Motion/roboop/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,33 @@
+/Makefile/1.14/Wed Aug 10 02:20:09 2005//Ttekkotsu-2_4
+/clik.cpp/1.6/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/clik.h/1.5/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/comp_dq.cpp/1.5/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/comp_dqp.cpp/1.5/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/config.cpp/1.11/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/config.h/1.14/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/control_select.cpp/1.4/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/control_select.h/1.4/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/controller.cpp/1.4/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/controller.h/1.4/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/delta_t.cpp/1.6/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/dynamics.cpp/1.7/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/dynamics_sim.cpp/1.3/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/dynamics_sim.h/1.4/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/gnugraph.cpp/1.3/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/gnugraph.h/1.2/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/homogen.cpp/1.5/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/invkine.cpp/1.25/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/kinemat.cpp/1.17/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/quaternion.cpp/1.5/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/quaternion.h/1.5/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/readme.txt/1.2/Wed Jul 14 02:29:35 2004//Ttekkotsu-2_4
+/revisions.txt/1.2/Wed Jul 14 02:29:35 2004//Ttekkotsu-2_4
+/robdocs.tar.gz/1.2/Wed Jul 14 02:29:35 2004/-kb/Ttekkotsu-2_4
+/robot.cpp/1.21/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/robot.h/1.19/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/sensitiv.cpp/1.5/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/trajectory.cpp/1.5/Tue Jul 26 03:22:08 2005//Ttekkotsu-2_4
+/trajectory.h/1.5/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/utils.cpp/1.6/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+/utils.h/1.5/Tue Jul 26 03:22:09 2005//Ttekkotsu-2_4
+D/extra////
diff -urdN ../Tekkotsu_2.3/Motion/roboop/CVS/Repository ./Motion/roboop/CVS/Repository
--- ../Tekkotsu_2.3/Motion/roboop/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/CVS/Repository	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Tekkotsu/Motion/roboop
diff -urdN ../Tekkotsu_2.3/Motion/roboop/CVS/Root ./Motion/roboop/CVS/Root
--- ../Tekkotsu_2.3/Motion/roboop/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/CVS/Root	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Motion/roboop/CVS/Tag ./Motion/roboop/CVS/Tag
--- ../Tekkotsu_2.3/Motion/roboop/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/CVS/Tag	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Motion/roboop/Makefile ./Motion/roboop/Makefile
--- ../Tekkotsu_2.3/Motion/roboop/Makefile	Tue Nov  9 16:26:13 2004
+++ ./Motion/roboop/Makefile	Tue Aug  9 22:20:09 2005
@@ -7,9 +7,7 @@
 $(error An error has occured, TEKKOTSU_ENVIRONMENT_CONFIGURATION was not defined)
 endif
 include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
-FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(FILTERSYSWARN))
-COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(COLORFILT))
-BUILDDIR=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(TK_BD)/Motion/roboop)
+BUILDDIR=$(TK_LIB_BD)/Motion/roboop
 SRCSUFFIX=.cpp
 
 # You may need to adjust these cc options:
@@ -18,6 +16,11 @@
           -Woverloaded-virtual -Wdeprecated -Wnon-virtual-dtor \
           -O3 -frename-registers -fomit-frame-pointer -fno-common \
 
+ifeq ($(strip $(shell $(CXX) --version | head -n 1)),powerpc-apple-darwin8-g++-4.0.0 (GCC) 4.0.0 20041026 (Apple Computer, Inc. build 4061))
+$(shell echo "Disabling ROBOOP optimization due to darwin gcc 4.0.0 compiler bug triggered by robot.cpp" > /dev/tty)
+CXXFLAGS:=$(filter-out -O3,$(CXXFLAGS))
+endif
+
 #          -Wshadow -Weffc++
 
 # Link-time cc options:
@@ -34,8 +37,15 @@
 # file rename command
 MV= mv
 
+# if precompiled headers are enabled by the Environment.conf, then
+# this file will be created with the names of all current .h files
+# and then precompiled
+PCH=all.h
+
 # End of configurable options.
 
+INCLUDE_PCH:=$(if $(TEKKOTSU_PCH),-include $(BUILDDIR)/$(PCH))
+
 # source files:
 LIBSOURCES:= $(wildcard *$(SRCSUFFIX))
 ifeq ($(TEKKOTSU_TARGET_PLATFORM), PLATFORM_APERIOS)
@@ -44,6 +54,11 @@
 
 SOURCES= $(LIBSOURCES)
 
+INCLUDES:=$(filter-out $(PCH),$(wildcard *.h))
+ifeq ($(TEKKOTSU_TARGET_PLATFORM), PLATFORM_APERIOS)
+INCLUDES:=$(filter-out gnugraph.h,$(INCLUDES))
+endif
+
 LIBOBJECTS= $(addprefix $(BUILDDIR)/,$(LIBSOURCES:.cpp=.o))
 
 all: $(BUILDDIR)/libroboop.a
@@ -57,16 +72,34 @@
 	@$(AR2) $@
 
 clean:
-	$(RM) *.o *.a *.log core
+	$(RM) *.o *.a *.log core $(PCH)
+	$(RM) -r $(BUILDDIR)
 
-%.o:
+%:: %.o;
+
+%.o: $(if $(TEKKOTSU_PCH),$(BUILDDIR)/$(PCH).gch)
 	@mkdir -p $(dir $@)
 	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(BUILDDIR)/%,%,$@)); \
 	echo "Compiling ROBOOP::$$src... (Reduced warnings)"; \
-	$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+	$(CXX) $(CXXFLAGS) $(INCLUDE_PCH) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0;
+
+$(BUILDDIR)/$(PCH).gch: $(PCH)
+	@mkdir -p $(dir $@)
+	@src=$(PCH); \
+	echo "Pre-compiling ROBOOP::$$src... (Reduced warnings)"; \
+	$(CXX) $(CXXFLAGS) -x c++-header -o $@ -c $$src > $*.log 2>&1; \
 	retval=$$?; \
 	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
 	test $$retval -eq 0;
+
+$(PCH): $(INCLUDES)
+	@rm -f $@;
+	@for x in $^ ; do \
+		echo "#include \"$$x\"" >> $@; \
+	done
 
 $(BUILDDIR)/controller.o: controller.cpp controller.h
 
diff -urdN ../Tekkotsu_2.3/Motion/roboop/clik.cpp ./Motion/roboop/clik.cpp
--- ../Tekkotsu_2.3/Motion/roboop/clik.cpp	Sun Sep 26 15:55:35 2004
+++ ./Motion/roboop/clik.cpp	Mon Jul 25 23:22:09 2005
@@ -29,9 +29,6 @@
     -Added support for newmat's use_namespace #define, using ROBOOP namespace.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: clik.cpp,v 1.5 2004/09/26 19:55:35 ejt Exp $";
-
 /*!
   @file clik.cpp
   @brief Clik member functions.
@@ -44,6 +41,9 @@
   using namespace NEWMAT;
 #endif
 
+  //! @brief RCS/CVS version.
+  static const char rcsid[] __UNUSED__ = "$Id: clik.cpp,v 1.6 2005/07/26 03:22:09 ejt Exp $";
+	
 /*!
   @fn Clik::Clik(const Robot & robot_, const DiagonalMatrix & Kp_, const DiagonalMatrix & Ko_,
                  const Real eps_, const Real lambda_max_, const Real dt);
diff -urdN ../Tekkotsu_2.3/Motion/roboop/clik.h ./Motion/roboop/clik.h
--- ../Tekkotsu_2.3/Motion/roboop/clik.h	Tue Jul 13 22:32:11 2004
+++ ./Motion/roboop/clik.h	Mon Jul 25 23:22:09 2005
@@ -61,9 +61,6 @@
   @brief Header file for Clik class definitions.
 */
 
-//! @brief RCS/CVS version.
-static const char header_clik_rcsid[] = "$Id: clik.h,v 1.4 2004/07/14 02:32:11 ejt Exp $";
-
 #include "robot.h"
 #include "quaternion.h"
 
@@ -71,7 +68,8 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
-
+  //! @brief RCS/CVS version.
+  static const char header_clik_rcsid[] __UNUSED__ = "$Id: clik.h,v 1.5 2005/07/26 03:22:09 ejt Exp $";
 
 //! @brief Using Clik under DH notation.
 #define CLICK_DH           1
diff -urdN ../Tekkotsu_2.3/Motion/roboop/comp_dq.cpp ./Motion/roboop/comp_dq.cpp
--- ../Tekkotsu_2.3/Motion/roboop/comp_dq.cpp	Tue Jul 13 22:32:11 2004
+++ ./Motion/roboop/comp_dq.cpp	Mon Jul 25 23:22:08 2005
@@ -51,15 +51,15 @@
   @brief Delta torque (linearized dynamics).
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: comp_dq.cpp,v 1.4 2004/07/14 02:32:11 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: comp_dq.cpp,v 1.5 2005/07/26 03:22:08 ejt Exp $";
 
 
 void Robot::dq_torque(const ColumnVector & q, const ColumnVector & qp,
diff -urdN ../Tekkotsu_2.3/Motion/roboop/comp_dqp.cpp ./Motion/roboop/comp_dqp.cpp
--- ../Tekkotsu_2.3/Motion/roboop/comp_dqp.cpp	Tue Jul 13 22:32:11 2004
+++ ./Motion/roboop/comp_dqp.cpp	Mon Jul 25 23:22:09 2005
@@ -50,15 +50,15 @@
   @brief Delta torque (linearized dynamics).
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: comp_dqp.cpp,v 1.4 2004/07/14 02:32:11 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: comp_dqp.cpp,v 1.5 2005/07/26 03:22:09 ejt Exp $";
 
 void Robot::dqp_torque(const ColumnVector & q, const ColumnVector & qp,
                        const ColumnVector & dqp,
diff -urdN ../Tekkotsu_2.3/Motion/roboop/config.cpp ./Motion/roboop/config.cpp
--- ../Tekkotsu_2.3/Motion/roboop/config.cpp	Wed Sep  1 15:51:04 2004
+++ ./Motion/roboop/config.cpp	Mon Jul 25 23:22:08 2005
@@ -39,6 +39,10 @@
 2004/09/01: Ethan Tira-Thompson
     -Added optional parameter to constructor so you can automatically read_conf
     -select_* functions are now const
+
+2005/04/08: Ethan Tira-Thompson
+    -Switched data storage to STL map, replacing the previous O(n^2) config file
+     parsing, now approx O(n lg n) (actually a little better - O((s*p) lg (s+p)))
 -------------------------------------------------------------------------------
 */
 
@@ -47,16 +51,24 @@
   @brief Configuration class functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: config.cpp,v 1.9 2004/09/01 19:51:04 ejt Exp $";
-
 
 #include "config.h"
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+#ifdef __WATCOMC__
+#include <strstrea.h>
+#else
+#include <sstream>
+#endif
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: config.cpp,v 1.11 2005/07/26 03:22:08 ejt Exp $";
 
 Config::Config(const string & filename_, bool doRead/*=false*/)
 //! @brief Constructor.
@@ -99,17 +111,16 @@
 */
 {
    const char *ptr_filename = filename.c_str(); //transform string to *char
-
    std::ifstream inconffile(ptr_filename, std::ios::in);
 
    if(inconffile)
    {
       string temp;
       int tmpPos;
-      Data data;
+	map<string,string>* cursection=NULL;
+	string parameter, value;
 #ifdef __WATCOMC__
       char tempo[256], tempo2[256];
-      string section, parameter, value;
       inconffile.getline(tempo,sizeof(tempo));
       temp = tempo;
 #else
@@ -128,7 +139,8 @@
  	       tmpPos = temp.find("]");
 	       if (tmpPos != (int)string::npos)
 		 {
-		   data.section = temp.substr(1, tmpPos-1); // remove []
+		   cursection = &conf[temp.substr(1, tmpPos-1)]; // remove []
+            
 		   // Read the next line, it's should be a parameter.
 #ifdef __WATCOMC__
 		   inconffile.getline(tempo,sizeof(tempo));
@@ -144,33 +156,43 @@
 			 {
 			   if(temp.find(":") != string::npos)
 			     {
+					 try{
 #ifdef __WATCOMC__
 			       istrstream inputString(tempo);
 			       inputString >> tempo2;
-			       data.parameter = tempo2;
+			       parameter = tempo2;
 			       inputString >> tempo2;
-			       data.value = tempo2;
+			       value = tempo2;
 #else
+//						 while(foo) ;
+//						 std::cout << "Config Da " << temp << std::endl;
 			       istringstream inputString(temp);
-			       inputString >> data.parameter >> data.value;
+//						 std::cout << "Config Db " << temp << std::endl;
+			       inputString >> parameter >> value;
 #endif
+//						 std::cout << "Config Dc" << std::endl;
 			       // Find ":" in parameter.
-			       tmpPos = data.parameter.find(":");
+			       tmpPos = parameter.find(":");
 			       if (tmpPos != (int)string::npos)
 				 // remove ":" a the end of parameter
-				 data.parameter = data.parameter.substr(0, tmpPos);
+				 parameter = parameter.substr(0, tmpPos);
 			       else
 				 {
 #ifdef __WATCOMC__
 				   inputString >> tempo2;
-				   data.value = tempo2;
+				   value = tempo2;
 #else
-				   inputString >> data.value;
+				   inputString >> value;
 #endif
 				 }
+						 } catch(std::exception e) { std::cout << "caught " << e.what() << ' ' << parameter << ' ' << value << endl; }
+					 catch(...) { std::cout << "caught " << parameter << ' ' << value << endl; }
 
 			       // Add data to the config vector
-			       conf.push_back(data);
+            if(cursection==NULL)
+               std::cout << "parameter without section: " << parameter << " == " << value << endl;
+            else
+					 (*cursection)[parameter]=value;
 			     }
 
 			   // Read the next line.
@@ -216,19 +238,12 @@
 void Config::print()
 //! @brief Print the configuration data.
 {
-  string tmpSection;
-  for(Conf_data::iterator iter = conf.begin(); iter != conf.end(); ++iter)
-    {
-      if (tmpSection != iter->section)
-	{
-	  //Beginning of a section
-	  tmpSection = iter->section;
-	  cout << "\n[" << tmpSection << "]" << endl;
+	for(confdata_t::const_iterator it=conf.begin(); it!=conf.end(); ++it) {
+		cout << '[' << it->first << "]\n";
+		for(map<string,string>::const_iterator vit=it->second.begin(); vit!=it->second.end(); ++vit)
+			cout << setw(15-vit->first.size()) << vit->first+":" << " " << vit->second << '\n';
 	}
-      else
-	  cout << setw(15-iter->parameter.size()) << iter->parameter+":" << " " 
-	       << iter->value << endl;
-    }
+	cout << flush;
 }
 
 bool Config::section_exists(const string& section) const
@@ -237,10 +252,7 @@
   @return true if @a section is found
 */
 {
-	for(Conf_data::const_iterator iter = conf.begin(); iter != conf.end(); ++iter)
-		if(iter->section == section)
-			return true;
-	return false;
+	return conf.find(section)!=conf.end();
 }
 
 bool Config::parameter_exists(const string& section, const string& parameter) const
@@ -249,10 +261,10 @@
   @return true if @a parameter is found within @a section
 */
 {
-	for(Conf_data::const_iterator iter = conf.begin(); iter != conf.end(); ++iter)
-		if( (iter->section == section) && (iter->parameter == parameter) )
-			return true;
-	return false;
+	confdata_t::const_iterator it=conf.find(section);
+	if(it==conf.end())
+		return false;
+	return it->second.find(parameter)!=it->second.end();
 }
 
 short Config::select_string(const string section, const string parameter, string & value) const
@@ -261,14 +273,14 @@
   @return 0 or SECTION_OR_PARAMETER_DOES_NOT_EXIST if the data can not be found.
 */
 {
-   for(Conf_data::const_iterator iter = conf.begin(); iter != conf.end(); ++iter)
-   {
-      if( (iter->section == section) && (iter->parameter == parameter) )
-      {
-         value = iter->value;
-         return 0;
-      }
-   }
+	confdata_t::const_iterator it=conf.find(section);
+	if(it!=conf.end()) {
+		map<string,string>::const_iterator vit=it->second.find(parameter);
+		if(vit!=it->second.end()) {
+			value=vit->second;
+			return 0;
+		}
+	}
    value = "";
    cerr << "Config::select_string: section " << section.c_str() << " or parameter "
    << parameter.c_str() << " does not exist." << endl;
@@ -450,18 +462,11 @@
       outconffile << "# ---------------------------------------------------" << endl;
       outconffile << endl;
 
-      string section = "";
-
-      for(Conf_data::iterator iterConf = conf.begin(); iterConf != conf.end(); ++iterConf)
-      {
-         if(section != iterConf->section)
-         {
-            section = iterConf->section;
-            outconffile << "\n[" << section << "]\n" << endl;
-         }
-	 outconffile << setw(space_between_column-iterConf->parameter.size()) 
-		     << iterConf->parameter + ":" << " " << iterConf->value << endl;
-      }
+		for(confdata_t::const_iterator it=conf.begin(); it!=conf.end(); ++it) {
+			outconffile << '[' << it->first << "]\n";
+			for(map<string,string>::const_iterator vit=it->second.begin(); vit!=it->second.end(); ++vit)
+				outconffile << setw(space_between_column-vit->first.size()) << vit->first + ": " << vit->second << '\n';
+		}
       return 0;
    }
    else
@@ -478,32 +483,7 @@
   The functions will added the parameter and the section if it does not already exist.
 */
 {
-   Data dataSet;
-   dataSet.section = section;
-   dataSet.parameter = parameter;
-   dataSet.value = value;
-   for(Conf_data::iterator iterConf = conf.begin(); iterConf != conf.end(); ++iterConf)
-   {
-      if(section == iterConf->section) // section already exist
-      {
-         if(parameter == iterConf->parameter) // parameter already exist
-         {
-            iterConf->value = value;
-            return;
-         }
-         // parameter does not exist
-         for(Conf_data::iterator iterConf2 = iterConf; iterConf2 != conf.end(); ++iterConf2)
-         {
-            if(section != iterConf2->section)
-            {
-               conf.insert(iterConf2, dataSet);
-               return;
-            }
-         }
-      }
-   }
-   // section and parameter does not exist.
-   conf.push_back(dataSet);
+	conf[section][parameter]=value;
 }
 
 void Config::add_bool(const string section, const string parameter,
@@ -622,13 +602,3 @@
 #ifdef use_namespace
 }
 #endif
-
-
-
-
-
-
-
-
-
-
diff -urdN ../Tekkotsu_2.3/Motion/roboop/config.h ./Motion/roboop/config.h
--- ../Tekkotsu_2.3/Motion/roboop/config.h	Wed Dec 22 14:18:48 2004
+++ ./Motion/roboop/config.h	Mon Jul 25 23:22:09 2005
@@ -39,6 +39,10 @@
 2004/09/01: Ethan Tira-Thompson
     -Added optional parameter to constructor so you can automatically read_conf
     -select_* functions are now const
+
+2005/04/08: Ethan Tira-Thompson
+    -Switched data storage to STL map, replacing the previous O(n^2) config file
+     parsing, now approx O(n lg n) (actually a little better - O((s*p) lg (s+p)))
 -------------------------------------------------------------------------------
 */
 
@@ -50,30 +54,21 @@
   @brief Header file for Config class definitions.
 */
 
-//! @brief RCS/CVS version.
-static const char header_config_rcsid[] = "$Id: config.h,v 1.11 2004/12/22 19:18:48 ejt Exp $";
-
-
 #ifdef _MSC_VER                  // Microsoft
 #pragma warning (disable:4786)  // Disable decorated name truncation warnings 
 #pragma warning (disable:4503)  // Disable decorated name truncation warnings 
 #endif
-#include <iostream>
+
 #include <string>
-#include <iomanip>
-#include <fstream>
-#ifdef __WATCOMC__
-#include <strstrea.h>
-#else
-#include <sstream>
-#endif
-#include <vector>
+#include <map>
 
 #include "utils.h"
 #ifdef use_namespace
-namespace ROBOOP {
+namespace ROBOOP {	
   using namespace NEWMAT;
 #endif
+  //! @brief RCS/CVS version.
+  static const char header_config_rcsid[] __UNUSED__ = "$Id: config.h,v 1.14 2005/07/26 03:22:09 ejt Exp $";
 
 //! @brief Return when can not open file.
 #define CAN_NOT_OPEN_FILE                     -1
@@ -89,17 +84,6 @@
 #endif
 
 
-//! @brief Basic data element used in Config class.
-typedef struct Data{
-   Data() : section(), parameter(), value() {}
-   string section;
-   string parameter;
-   string value;
-} Data;
-
-//! @brief Configuration data type.
-typedef vector< Data > Conf_data;
-
 //! @brief Handle configuration files.
 /*! The file syntax used is:
  *  - <tt>[</tt><i>section_name</i><tt>]</tt>
@@ -111,7 +95,7 @@
  *  The minimal entries required to avoid warnings are (can be any order):
  *  - <tt>[</tt><i>chain_name</i><tt>]</tt><br>
  *    - <tt>Name: </tt> - a string identifier
- *    - <tt>DH: </tt> - whether or not the chain specification is standard Denavitt-Hartenberg (non-zero), or modified Denavitt-Hartenberg (0)
+ *    - <tt>DH: </tt> - whether or not the chain specification is standard Denavit-Hartenberg (non-zero), or modified Denavit-Hartenberg (0)
  *    - <tt>Fix: </tt> - ?
  *    - <tt>MinPara: </tt> - ?
  *    - <tt>dof: </tt> - number of links in the chain
@@ -182,7 +166,10 @@
                    const Real value);
 
 private:
-   Conf_data conf;   //!< Data store from/to configuration file.
+	//! holds configuration data - a map from section name to sub-map of parameters to values
+	typedef map<string, map<string, string> > confdata_t;
+	 
+   confdata_t conf;   //!< Data store from/to configuration file.
    string filename;  //!< Configuration file name.
 };
 
diff -urdN ../Tekkotsu_2.3/Motion/roboop/control_select.cpp ./Motion/roboop/control_select.cpp
--- ../Tekkotsu_2.3/Motion/roboop/control_select.cpp	Tue Jul 13 22:46:43 2004
+++ ./Motion/roboop/control_select.cpp	Mon Jul 25 23:22:09 2005
@@ -34,16 +34,14 @@
   @brief Controller selection class.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: control_select.cpp,v 1.3 2004/07/14 02:46:43 ejt Exp $";
-
-
 #include "control_select.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: control_select.cpp,v 1.4 2005/07/26 03:22:09 ejt Exp $";
 
 Control_Select::Control_Select()
 //! @brief Constructor.
diff -urdN ../Tekkotsu_2.3/Motion/roboop/control_select.h ./Motion/roboop/control_select.h
--- ../Tekkotsu_2.3/Motion/roboop/control_select.h	Tue Jul 13 22:46:43 2004
+++ ./Motion/roboop/control_select.h	Mon Jul 25 23:22:08 2005
@@ -37,10 +37,6 @@
   @brief Header file for Control_Select class definitions.
 */
 
-//! @brief RCS/CVS version.
-static const char header_Control_Select_rcsid[] = "$Id: control_select.h,v 1.3 2004/07/14 02:46:43 ejt Exp $";
-
-
 #include <string>
 #include <vector>
 #include "robot.h"
@@ -52,7 +48,10 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char header_Control_Select_rcsid[] __UNUSED__ = "$Id: control_select.h,v 1.4 2005/07/26 03:22:08 ejt Exp $";
 
+	
 #define NONE   0
 #define PD     1
 #define CTM    2
diff -urdN ../Tekkotsu_2.3/Motion/roboop/controller.cpp ./Motion/roboop/controller.cpp
--- ../Tekkotsu_2.3/Motion/roboop/controller.cpp	Tue Jul 13 22:32:11 2004
+++ ./Motion/roboop/controller.cpp	Mon Jul 25 23:22:09 2005
@@ -26,17 +26,14 @@
   @brief Differents controllers class.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: controller.cpp,v 1.2 2004/07/14 02:32:11 ejt Exp $";
-
-
 #include "controller.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
-
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: controller.cpp,v 1.4 2005/07/26 03:22:09 ejt Exp $";
 
 Impedance::Impedance()
 //! @brief Constructor.
@@ -545,7 +542,7 @@
                                       const ColumnVector & pdp, const ColumnVector & pd,
                                       const ColumnVector & wdp, const ColumnVector & wd,
                                       const Quaternion & quatd, const short link_pc,
-                                      const Real dt)
+                                      const Real /*dt*/)
 /*!
   @brief Output torque.
 
diff -urdN ../Tekkotsu_2.3/Motion/roboop/controller.h ./Motion/roboop/controller.h
--- ../Tekkotsu_2.3/Motion/roboop/controller.h	Tue Jul 13 22:46:43 2004
+++ ./Motion/roboop/controller.h	Mon Jul 25 23:22:09 2005
@@ -36,10 +36,6 @@
   @brief Header file for controller class definitions.
 */
 
-//! @brief RCS/CVS version.
-static const char header_controller_rcsid[] = "$Id: controller.h,v 1.3 2004/07/14 02:46:43 ejt Exp $";
-
-
 #include "robot.h"
 #include "quaternion.h"
 
@@ -47,6 +43,8 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char header_controller_rcsid[] __UNUSED__ = "$Id: controller.h,v 1.4 2005/07/26 03:22:09 ejt Exp $";
 
 //! @brief Return value when input vectors or matrix don't have the right size.
 #define WRONG_SIZE -1
diff -urdN ../Tekkotsu_2.3/Motion/roboop/delta_t.cpp ./Motion/roboop/delta_t.cpp
--- ../Tekkotsu_2.3/Motion/roboop/delta_t.cpp	Fri Sep  3 11:56:33 2004
+++ ./Motion/roboop/delta_t.cpp	Mon Jul 25 23:22:09 2005
@@ -51,16 +51,14 @@
   @brief Delta torque (linearized dynamics).
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: delta_t.cpp,v 1.5 2004/09/03 15:56:33 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
-
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: delta_t.cpp,v 1.6 2005/07/26 03:22:09 ejt Exp $";
 
 void Robot::delta_torque(const ColumnVector & q, const ColumnVector & qp,
                          const ColumnVector & qpp, const ColumnVector & dq,
diff -urdN ../Tekkotsu_2.3/Motion/roboop/dynamics.cpp ./Motion/roboop/dynamics.cpp
--- ../Tekkotsu_2.3/Motion/roboop/dynamics.cpp	Tue Jul 13 23:22:32 2004
+++ ./Motion/roboop/dynamics.cpp	Mon Jul 25 23:22:09 2005
@@ -66,15 +66,14 @@
   @brief Manipulator dynamics functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: dynamics.cpp,v 1.6 2004/07/14 03:22:32 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: dynamics.cpp,v 1.7 2005/07/26 03:22:09 ejt Exp $";
 
 ReturnMatrix Robot_basic::inertia(const ColumnVector & q)
 //! @brief Inertia of the manipulator.
diff -urdN ../Tekkotsu_2.3/Motion/roboop/dynamics_sim.cpp ./Motion/roboop/dynamics_sim.cpp
--- ../Tekkotsu_2.3/Motion/roboop/dynamics_sim.cpp	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/dynamics_sim.cpp	Mon Jul 25 23:22:09 2005
@@ -26,16 +26,14 @@
   @brief Basic dynamics simulation class.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: dynamics_sim.cpp,v 1.2 2004/07/14 02:32:12 ejt Exp $";
-
-
 #include "dynamics_sim.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: dynamics_sim.cpp,v 1.3 2005/07/26 03:22:09 ejt Exp $";
 
 Dynamics *Dynamics::instance = 0;
 
diff -urdN ../Tekkotsu_2.3/Motion/roboop/dynamics_sim.h ./Motion/roboop/dynamics_sim.h
--- ../Tekkotsu_2.3/Motion/roboop/dynamics_sim.h	Fri Jul 23 17:33:46 2004
+++ ./Motion/roboop/dynamics_sim.h	Mon Jul 25 23:22:09 2005
@@ -36,9 +36,6 @@
   @brief Header file for Dynamics definitions.
 */
 
-//! @brief RCS/CVS version.
-static const char header_dynamics_sim_rcsid[] = "$Id: dynamics_sim.h,v 1.3 2004/07/23 21:33:46 ejt Exp $";
-
 #include "control_select.h"
 #include "quaternion.h"
 #include "robot.h"
@@ -48,6 +45,8 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char header_dynamics_sim_rcsid[] __UNUSED__ = "$Id: dynamics_sim.h,v 1.4 2005/07/26 03:22:09 ejt Exp $";
 
 
 /*!
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Entries ./Motion/roboop/extra/CVS/Entries
--- ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,13 @@
+/bench.cpp/1.4/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/demo.cpp/1.4/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/demo_2dof_pd.cpp/1.1/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/makefile.gcc/1.2/Fri Jul  2 00:19:33 2004//Ttekkotsu-2_4
+/matlabtest.m/1.1/Wed Jun 16 21:50:00 2004//Ttekkotsu-2_4
+/puma560_motor.m/1.2/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/puma560_no_motor.m/1.2/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/puma560akb_motor.m/1.2/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/puma560akb_no_motor.m/1.2/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/rtest.cpp/1.4/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/stanford_no_motor.m/1.2/Wed Jul 14 02:29:41 2004//Ttekkotsu-2_4
+/test.txt/1.1/Wed Jun 16 21:50:00 2004//Ttekkotsu-2_4
+D/conf////
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Repository ./Motion/roboop/extra/CVS/Repository
--- ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/CVS/Repository	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Tekkotsu/Motion/roboop/extra
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Root ./Motion/roboop/extra/CVS/Root
--- ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/CVS/Root	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Tag ./Motion/roboop/extra/CVS/Tag
--- ../Tekkotsu_2.3/Motion/roboop/extra/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/CVS/Tag	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Entries ./Motion/roboop/extra/conf/CVS/Entries
--- ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/conf/CVS/Entries	Wed Aug 10 11:03:19 2005
@@ -0,0 +1,7 @@
+/pd_2dof.conf/1.1/Wed Jul 14 02:29:48 2004//Ttekkotsu-2_4
+/puma560_dh.conf/1.2/Wed Jul 14 02:29:48 2004//Ttekkotsu-2_4
+/puma560_mdh.conf/1.2/Wed Jul 14 02:29:48 2004//Ttekkotsu-2_4
+/rhino_dh.conf/1.2/Wed Jul 14 02:29:48 2004//Ttekkotsu-2_4
+/rhino_mdh.conf/1.2/Wed Jul 14 02:29:48 2004//Ttekkotsu-2_4
+/rr_dh.conf/1.1/Wed Jul 14 02:29:48 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Repository ./Motion/roboop/extra/conf/CVS/Repository
--- ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/conf/CVS/Repository	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Tekkotsu/Motion/roboop/extra/conf
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Root ./Motion/roboop/extra/conf/CVS/Root
--- ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/conf/CVS/Root	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Tag ./Motion/roboop/extra/conf/CVS/Tag
--- ../Tekkotsu_2.3/Motion/roboop/extra/conf/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Motion/roboop/extra/conf/CVS/Tag	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Motion/roboop/gnugraph.cpp ./Motion/roboop/gnugraph.cpp
--- ../Tekkotsu_2.3/Motion/roboop/gnugraph.cpp	Tue Jul 20 13:55:24 2004
+++ ./Motion/roboop/gnugraph.cpp	Mon Jul 25 23:22:08 2005
@@ -60,15 +60,14 @@
   @brief Graphics functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: gnugraph.cpp,v 1.1 2004/07/20 17:55:24 ejt Exp $";
-
 #include "gnugraph.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: gnugraph.cpp,v 1.3 2005/07/26 03:22:08 ejt Exp $";
 
 char *curvetype[] =
    {"lines",
@@ -139,7 +138,7 @@
    {
       curves = new GNUcurve[NCURVESMAX];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "Plot2d::Plot2d:: new ran out of memory" << endl;
    }
@@ -198,7 +197,7 @@
    {
       filedata = new char[strlen(filename)+3];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "Plot2d::gnuplot:: new ran out of memory" << endl;
    }
@@ -683,7 +682,7 @@
    {
       legend = new char[strlen(label)+1];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "set_plot2d:: new ran out of memory" << endl;
       return OUT_OF_MEMORY;
diff -urdN ../Tekkotsu_2.3/Motion/roboop/gnugraph.h ./Motion/roboop/gnugraph.h
--- ../Tekkotsu_2.3/Motion/roboop/gnugraph.h	Tue Jul 20 13:55:24 2004
+++ ./Motion/roboop/gnugraph.h	Mon Jul 25 23:22:09 2005
@@ -47,9 +47,6 @@
   @brief Header file for graphics definitions.
 */
 
-//! @brief RCS/CVS version.
-static const char header_gnugraph_rcsid[] = "$Id: gnugraph.h,v 1.1 2004/07/20 17:55:24 ejt Exp $";
-
 #if defined(__WIN32__) || defined(_WIN32) || defined(__NT__)  || defined(__CYGWIN__)      /* Windows 95/NT */
 
 #define GNUPLOT "wgnuplot.exe"
@@ -81,6 +78,8 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char header_gnugraph_rcsid[] __UNUSED__ = "$Id: gnugraph.h,v 1.2 2005/07/26 03:22:09 ejt Exp $";
 
 #define OUT_OF_MEMORY       -1
 #define X_Y_DATA_NO_MATCH   -2
diff -urdN ../Tekkotsu_2.3/Motion/roboop/homogen.cpp ./Motion/roboop/homogen.cpp
--- ../Tekkotsu_2.3/Motion/roboop/homogen.cpp	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/homogen.cpp	Mon Jul 25 23:22:09 2005
@@ -45,15 +45,14 @@
   @brief Homogen transformation functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: homogen.cpp,v 1.4 2004/07/14 02:32:12 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: homogen.cpp,v 1.5 2005/07/26 03:22:09 ejt Exp $";
 
 
 ReturnMatrix trans(const ColumnVector & a)
diff -urdN ../Tekkotsu_2.3/Motion/roboop/invkine.cpp ./Motion/roboop/invkine.cpp
--- ../Tekkotsu_2.3/Motion/roboop/invkine.cpp	Mon Oct 18 13:01:38 2004
+++ ./Motion/roboop/invkine.cpp	Mon Jul 25 23:22:09 2005
@@ -61,9 +61,6 @@
   @brief Inverse kinematics solutions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: invkine.cpp,v 1.23 2004/10/18 17:01:38 ejt Exp $";
-
 #include "robot.h"
 #include <sstream>
 
@@ -71,6 +68,8 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+	//! @brief RCS/CVS version.
+	static const char rcsid[] __UNUSED__ = "$Id: invkine.cpp,v 1.25 2005/07/26 03:22:09 ejt Exp $";
 
 #define NITMAX 1000  //!< def maximum number of iterations in inv_kin 
 #ifdef USING_FLOAT //from newmat's include.h
@@ -1058,7 +1057,7 @@
 			Real aor_d=(2*cur_to_plink_len*previous_to_cur_len);
 			//cout << "aor_d==" << aor_d << endl;
 			//have to check if Pobj is within reach
-			if(abs(aor_d)<=ITOL) {
+			if(fabs(aor_d)<=ITOL) {
 				//Plink is along axis of rotation - nothing we do is going to move it, so don't move at all
 				//this should never be seen...
 				cout << "ASSERTION FAILED: " << __FILE__ << ':' << __LINE__ << endl;
diff -urdN ../Tekkotsu_2.3/Motion/roboop/kinemat.cpp ./Motion/roboop/kinemat.cpp
--- ../Tekkotsu_2.3/Motion/roboop/kinemat.cpp	Tue Dec 21 18:51:22 2004
+++ ./Motion/roboop/kinemat.cpp	Mon Jul 25 23:22:09 2005
@@ -86,16 +86,14 @@
   @brief Kinematics functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: kinemat.cpp,v 1.16 2004/12/21 23:51:22 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
-
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: kinemat.cpp,v 1.17 2005/07/26 03:22:09 ejt Exp $";
 
 void Robot_basic::kine(Matrix & Rot, ColumnVector & pos)const
 /*!
diff -urdN ../Tekkotsu_2.3/Motion/roboop/quaternion.cpp ./Motion/roboop/quaternion.cpp
--- ../Tekkotsu_2.3/Motion/roboop/quaternion.cpp	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/quaternion.cpp	Mon Jul 25 23:22:09 2005
@@ -53,15 +53,15 @@
   @brief Quaternion functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: quaternion.cpp,v 1.4 2004/07/14 02:32:12 ejt Exp $";
-
 #include "quaternion.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: quaternion.cpp,v 1.5 2005/07/26 03:22:09 ejt Exp $";
 
 
 Quaternion::Quaternion()
diff -urdN ../Tekkotsu_2.3/Motion/roboop/quaternion.h ./Motion/roboop/quaternion.h
--- ../Tekkotsu_2.3/Motion/roboop/quaternion.h	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/quaternion.h	Mon Jul 25 23:22:09 2005
@@ -61,15 +61,15 @@
   @brief Quaternion class.
 */
 
-//! @brief RCS/CVS version.
-static const char header_quat_rcsid[] = "$Id: quaternion.h,v 1.4 2004/07/14 02:32:12 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char header_quat_rcsid[] __UNUSED__ = "$Id: quaternion.h,v 1.5 2005/07/26 03:22:09 ejt Exp $";
 
 #define BASE_FRAME 0
 #define BODY_FRAME 1
diff -urdN ../Tekkotsu_2.3/Motion/roboop/robot.cpp ./Motion/roboop/robot.cpp
--- ../Tekkotsu_2.3/Motion/roboop/robot.cpp	Fri Dec 10 18:49:35 2004
+++ ./Motion/roboop/robot.cpp	Mon Jul 25 23:22:08 2005
@@ -91,17 +91,23 @@
   @brief Initialisation of differents robot class.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: robot.cpp,v 1.19 2004/12/10 23:49:35 ejt Exp $";
-
 #include "robot.h"
 #include <time.h>
+#ifdef __WATCOMC__
+#include <strstrea.h>
+#else
+#include <sstream>
+#endif
+
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
 
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: robot.cpp,v 1.21 2005/07/26 03:22:08 ejt Exp $";
+
 //! @brief Used to initialize a \f$4\times 4\f$ matrix.
 Real fourbyfourident[] = {1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0};
 
@@ -445,7 +451,7 @@
       dp   = new ColumnVector[dof+1];
       R    = new Matrix[dof+fix+1];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "Robot_basic constructor : new ran out of memory" << endl;
       exit(1);
@@ -607,7 +613,7 @@
       dp   = new ColumnVector[dof+1];
       R    = new Matrix[dof+fix+1];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "Robot_basic constructor : new ran out of memory" << endl;
       exit(1);
@@ -678,8 +684,8 @@
       error("Initialisation robot and motor matrix does not have same numbers of Rows.");
 }
 
-Robot_basic::Robot_basic(const int ndof, const bool dh_parameter, 
-                         const bool min_inertial_para)
+Robot_basic::Robot_basic(const int ndof, const bool /*dh_parameter*/, 
+                         const bool /*min_inertial_para*/)
 /*!
   @brief Constructor.
   @param ndof: Robot degree of freedom.
@@ -726,7 +732,7 @@
       dp   = new ColumnVector[dof+1];
       R    = new Matrix[dof+1];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "Robot_basic constructor : new ran out of memory" << endl;
       exit(1);
@@ -792,7 +798,7 @@
       dp   = new ColumnVector[dof+1];
       R    = new ColumnVector[dof+fix+1];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "Robot_basic constructor : new ran out of memory" << endl;
       exit(1);
@@ -888,7 +894,7 @@
       dp   = new ColumnVector[dof+1];
       R    = new Matrix[dof+fix+1];
    }
-   catch(bad_alloc exception)
+   catch(bad_alloc ex)
    {
       cerr << "Robot_basic constructor : new ran out of memory" << endl;
       exit(1);
@@ -1083,7 +1089,7 @@
          dp    = new ColumnVector[dof+1];
          R     = new Matrix[dof+fix+1];
       }
-      catch(bad_alloc exception)
+      catch(bad_alloc ex)
       {
          cerr << "Robot_basic::operator= : new ran out of memory" << endl;
          exit(1);
diff -urdN ../Tekkotsu_2.3/Motion/roboop/robot.h ./Motion/roboop/robot.h
--- ../Tekkotsu_2.3/Motion/roboop/robot.h	Mon Oct 11 18:01:28 2004
+++ ./Motion/roboop/robot.h	Mon Jul 25 23:22:08 2005
@@ -116,15 +116,14 @@
   @brief Robots class definitions.
 */
 
-//! @brief RCS/CVS version.
-static const char header_rcsid[] = "$Id: robot.h,v 1.18 2004/10/11 22:01:28 ejt Exp $";
-
 #include "utils.h"
 
 #ifdef use_namespace
-namespace ROBOOP {
+namespace ROBOOP {	
   using namespace NEWMAT;
 #endif
+  //! @brief RCS/CVS version.
+  static const char header_rcsid[] __UNUSED__ = "$Id: robot.h,v 1.19 2005/07/26 03:22:08 ejt Exp $";
 
 
 /*!
diff -urdN ../Tekkotsu_2.3/Motion/roboop/sensitiv.cpp ./Motion/roboop/sensitiv.cpp
--- ../Tekkotsu_2.3/Motion/roboop/sensitiv.cpp	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/sensitiv.cpp	Mon Jul 25 23:22:08 2005
@@ -44,15 +44,15 @@
   @brief Delta torque (linearized dynamics).
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: sensitiv.cpp,v 1.4 2004/07/14 02:32:12 ejt Exp $";
-
 #include "robot.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: sensitiv.cpp,v 1.5 2005/07/26 03:22:08 ejt Exp $";
 
 
 ReturnMatrix Robot_basic::dtau_dq(const ColumnVector & q,
diff -urdN ../Tekkotsu_2.3/Motion/roboop/trajectory.cpp ./Motion/roboop/trajectory.cpp
--- ../Tekkotsu_2.3/Motion/roboop/trajectory.cpp	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/trajectory.cpp	Mon Jul 25 23:22:08 2005
@@ -36,15 +36,15 @@
   @brief Trajectory member functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: trajectory.cpp,v 1.4 2004/07/14 02:32:12 ejt Exp $";
-
 #include "trajectory.h"
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: trajectory.cpp,v 1.5 2005/07/26 03:22:08 ejt Exp $";
 
 
 Spl_cubic::Spl_cubic(const Matrix & pts)
diff -urdN ../Tekkotsu_2.3/Motion/roboop/trajectory.h ./Motion/roboop/trajectory.h
--- ../Tekkotsu_2.3/Motion/roboop/trajectory.h	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/trajectory.h	Mon Jul 25 23:22:09 2005
@@ -51,9 +51,6 @@
   @brief Header file for trajectory generation class.
 */
 
-//! @brief RCS/CVS version.
-static const char header_trajectory_rcsid[] = "$Id: trajectory.h,v 1.4 2004/07/14 02:32:12 ejt Exp $";
-
 
 #ifdef _MSC_VER                         // Microsoft
 //#include <string.h>
@@ -77,6 +74,9 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char header_trajectory_rcsid[] __UNUSED__ = "$Id: trajectory.h,v 1.5 2005/07/26 03:22:09 ejt Exp $";
 
 #define K_ZER0          1
 #define BAD_DATA       -1
diff -urdN ../Tekkotsu_2.3/Motion/roboop/utils.cpp ./Motion/roboop/utils.cpp
--- ../Tekkotsu_2.3/Motion/roboop/utils.cpp	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/utils.cpp	Mon Jul 25 23:22:09 2005
@@ -50,15 +50,16 @@
   @brief Utility functions.
 */
 
-//! @brief RCS/CVS version.
-static const char rcsid[] = "$Id: utils.cpp,v 1.4 2004/07/14 02:32:12 ejt Exp $";
-
 #include "robot.h"
+#include <iomanip>
 
 #ifdef use_namespace
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
+
+//! @brief RCS/CVS version.
+static const char rcsid[] __UNUSED__ = "$Id: utils.cpp,v 1.6 2005/07/26 03:22:09 ejt Exp $";
 
 
 ReturnMatrix x_prod_matrix(const ColumnVector & x)
diff -urdN ../Tekkotsu_2.3/Motion/roboop/utils.h ./Motion/roboop/utils.h
--- ../Tekkotsu_2.3/Motion/roboop/utils.h	Tue Jul 13 22:32:12 2004
+++ ./Motion/roboop/utils.h	Mon Jul 25 23:22:09 2005
@@ -50,8 +50,10 @@
   @brief Utility header file.
 */
 
-//! @brief RCS/CVS version.
-static const char header_utils_rcsid[] = "$Id: utils.h,v 1.4 2004/07/14 02:32:12 ejt Exp $";
+#ifndef __UNUSED__
+//!used to mark rcs strings as expected-to-be-unused so the compiler won't issue a warning
+#define __UNUSED__ __attribute__((unused))
+#endif
 
 #ifdef _MSC_VER                         // Microsoft
 #pragma warning (disable:4786)  /* Disable decorated name truncation warnings */
@@ -74,7 +76,9 @@
 namespace ROBOOP {
   using namespace NEWMAT;
 #endif
-
+  //! @brief RCS/CVS version.
+  static const char header_utils_rcsid[] __UNUSED__ = "$Id: utils.h,v 1.5 2005/07/26 03:22:09 ejt Exp $";	
+	
 #ifndef __WATCOMC__
 using namespace std;
 #endif
diff -urdN ../Tekkotsu_2.3/README ./README
--- ../Tekkotsu_2.3/README	Wed Mar 31 19:16:51 2004
+++ ./README	Tue Aug  9 19:10:47 2005
@@ -1,6 +1,6 @@
 Welcome to the Tekkotsu framework.
 Unless otherwise noted, all source code and related files are
-Copyright 2004, Carnegie Mellon University AIBO Lab
+Copyright 2005, Carnegie Mellon University Tekkotsu Lab
 Released under the LGPL.
 
 Documentation and Usage Guides:
@@ -11,12 +11,11 @@
 Contact info:
 ------------
   * Developer BBS: http://groups.yahoo.com/group/tekkotsu_dev/
+  * CVS info: http://cvs.tekkotsu.org/
+  * Bugzilla: http://bugs.tekkotsu.org/
 
   * General: info@tekkotsu.org
   * Bugs: bugs@tekkotsu.org
-  * Questions: questions@tekkotsu.org
-  * Feature requests: requests@tekkotsu.org
-  * Fan mail: fanmail@tekkotsu.org
 
 Directory Descriptions:
 ----------------------
@@ -36,25 +35,20 @@
   * Source Files *
     ------------
 
-     -Main and Motion Processes-
-      -------------------------
+     -Platform Specific Files-
+      -----------------------
+      aperios - provides support for Sony AIBO robots (through OPEN-R SDK)
+                (includes MMCombo, which forks into Main and Motion processes,
+                in addition to Sound and TinyFTPD processes)
+      local - provides simulation support for the host platform (UNIX variants)
+
+     -General Source Code-
+      -------------------
       Behaviors - Base classes and demo code
       Events - Base classes and 'custom' events
-      MMCombo - OPEN-R process, forks into Main and Motion processes
+      IPC - Inter-Process Communication, mutual exclusion and message passing
       Motion - Most motion related classes
       Shared - Utility code
+      Sound - Handles mixing and sending sound buffers to system
       Vision - Vision processing code
       Wireless - Networking code
-
-     -Sound Process-
-      -------------
-      SoundPlay - OPEN-R process, Handles mixing and sending
-                  sound buffers to system
-
-     -FTP process-
-      -----------
-      TinyFTPD - OPEN-R process, runs an FTP server
-
-     -Remote Process-
-      --------------
-      RemoteProcess - A simple RemoteProcessing OPENR sample
diff -urdN ../Tekkotsu_2.3/RemoteProcess/MS/OPEN-R/MW/CONF/CONNECT.CFG ./RemoteProcess/MS/OPEN-R/MW/CONF/CONNECT.CFG
--- ../Tekkotsu_2.3/RemoteProcess/MS/OPEN-R/MW/CONF/CONNECT.CFG	Wed Mar 26 16:35:49 2003
+++ ./RemoteProcess/MS/OPEN-R/MW/CONF/CONNECT.CFG	Wed Dec 31 19:00:00 1969
@@ -1,2 +0,0 @@
-TCPGateway.RPOPENRSendString.char.S RemoteProcess.RPOPENRReceiveString.char.O
-RemoteProcess.RPOPENRSendString.char.S TCPGateway.RPOPENRReceiveString.char.O
diff -urdN ../Tekkotsu_2.3/RemoteProcess/MS/OPEN-R/MW/CONF/HOSTGW.CFG ./RemoteProcess/MS/OPEN-R/MW/CONF/HOSTGW.CFG
--- ../Tekkotsu_2.3/RemoteProcess/MS/OPEN-R/MW/CONF/HOSTGW.CFG	Wed Mar 26 23:25:02 2003
+++ ./RemoteProcess/MS/OPEN-R/MW/CONF/HOSTGW.CFG	Wed Dec 31 19:00:00 1969
@@ -1,11 +0,0 @@
-!ROBOT_PROXY 59001 192.168.0.5
-
-TCPGateway.RPOPENRSendString.char.S 59010 192.168.0.5
-TCPGateway.RPOPENRReceiveString.char.O 59011 192.168.0.5
-
-# Other available data streams
-#TCPGateway.Sensor.OSensorFrameVectorData.O              59002
-#TCPGateway.Effector.OCommandVectorData.S                59003
-#TCPGateway.FbkImageSensor.OFbkImageVectorData.O         59004
-#TCPGateway.Mic.OSoundVectorData.O                       59005
-#TCPGateway.Speaker.OSoundVectorData.S                   59006
diff -urdN ../Tekkotsu_2.3/RemoteProcess/MS/OPEN-R/MW/CONF/OBJECT.CFG ./RemoteProcess/MS/OPEN-R/MW/CONF/OBJECT.CFG
--- ../Tekkotsu_2.3/RemoteProcess/MS/OPEN-R/MW/CONF/OBJECT.CFG	Wed Mar 26 16:35:49 2003
+++ ./RemoteProcess/MS/OPEN-R/MW/CONF/OBJECT.CFG	Wed Dec 31 19:00:00 1969
@@ -1 +0,0 @@
-/MS/OPEN-R/MW/OBJS/RPROCESS.BIN
diff -urdN ../Tekkotsu_2.3/RemoteProcess/RemoteProcess.cc ./RemoteProcess/RemoteProcess.cc
--- ../Tekkotsu_2.3/RemoteProcess/RemoteProcess.cc	Thu Sep 25 11:27:50 2003
+++ ./RemoteProcess/RemoteProcess.cc	Wed Dec 31 19:00:00 1969
@@ -1,97 +0,0 @@
-#include <OPENR/core_macro.h>
-#include "RemoteProcess.h"
-#include <stdio.h>
-
-RemoteProcess::RemoteProcess() : RPOPENR_isready(true)
-{
-  // usercode: constructor here
-}
-
-RemoteProcess::~RemoteProcess()
-{
-  // usercode: destructor here
-}
-
-void
-RemoteProcess::start()
-{
-  // usercode: objects connected
-  // code below is a simple example
-
-  if (RPOPENR_isReady()) {
-    RPOPENR_send("hello aibo",11);
-    printf("local: hello aibo");
-  }
-}
-
-void
-RemoteProcess::data_received(const char *buf)
-{
-  // usercode: message received
-  // code below is a simple example
-
-  printf("remote: %s\n",buf);
-}
-
-OStatus
-RemoteProcess::DoInit(const OSystemEvent& event)
-{
-  NEW_ALL_SUBJECT_AND_OBSERVER;
-  REGISTER_ALL_ENTRY;
-  SET_ALL_READY_AND_NOTIFY_ENTRY;
-  return oSUCCESS;
-}
-
-OStatus
-RemoteProcess::DoStart(const OSystemEvent& event)
-{
-    ENABLE_ALL_SUBJECT;
-    ASSERT_READY_TO_ALL_OBSERVER;
-    start();
-    return oSUCCESS;
-}
-
-OStatus
-RemoteProcess::DoStop(const OSystemEvent& event)
-{
-    DISABLE_ALL_SUBJECT;
-    DEASSERT_READY_TO_ALL_OBSERVER;
-    return oSUCCESS;
-}
-
-OStatus
-RemoteProcess::DoDestroy(const OSystemEvent& event)
-{
-    DELETE_ALL_SUBJECT_AND_OBSERVER;
-    return oSUCCESS;
-}
-
-void
-RemoteProcess::RPOPENR_notify(const ONotifyEvent& event) {
-  const char *buf = (const char *)event.Data(0);
-  data_received(buf);
-  observer[event.ObsIndex()]->AssertReady();
-}
-
-int
-RemoteProcess::RPOPENR_send(char *buf, int bufsize) {
-  if (RPOPENR_isready && bufsize>0) {
-    RPOPENR_isready=false;
-    subject[sbjRPOPENRSendString]->SetData(buf, bufsize);
-    subject[sbjRPOPENRSendString]->NotifyObservers();
-    return bufsize;
-  }
-  return 0;
-}
-
-/*! @file
- * @brief Describes RemoteProcess, sample RemoteProcessingOPENR process
- * @author alokl (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
- * $State: Rel $
- * $Date: 2003/09/25 15:27:50 $
- */
-
diff -urdN ../Tekkotsu_2.3/RemoteProcess/RemoteProcess.h ./RemoteProcess/RemoteProcess.h
--- ../Tekkotsu_2.3/RemoteProcess/RemoteProcess.h	Thu Sep 25 11:27:50 2003
+++ ./RemoteProcess/RemoteProcess.h	Wed Dec 31 19:00:00 1969
@@ -1,63 +0,0 @@
-#ifndef RemoteProcess_h_DEFINED
-#define RemoteProcess_h_DEFINED
-
-#include <OPENR/OObject.h>
-#include <OPENR/OSubject.h>
-#include <OPENR/OObserver.h>
-#include "def.h"
-
-//! Sample RemoteProcessingOPENR process
-/*! RemoteProcess runs on Linux with OPEN_R_SDK installed (and the
- *  RemoteProcessingOPENR patch). RemoteProcess talks to the Aibo using
- *  OPENR messages. RemoteProcessingOPENR can receive all the OPENR system
- *  sensor streams and write to all output streams available on the Aibo.
- *
- *  In short, use this if you're falling short of processing power on the
- *  Aibo, and the data you want processed is small in size. It'll help
- *  greatly if you're comfortable with OPENR processes and message
- *  passing.
- *
- *  Please read the RemoteProcessingOPENR instructions on the main Tekkotsu
- *  page for more information.
- */
-
-class RemoteProcess : public OObject {
-public:
-  //! constructor
-  RemoteProcess();
-  ~RemoteProcess(); //!< destructor
-  void start(); //!< called when objects are connected (by DoStart). Add user code here.
-  void data_received(const char *buf); //!< called when a message is received (by RPOPENR_notify). Add user code here.
-
-  // usercode: add additional definitions here
-
-  // support code below here:
-public:
-  OSubject* subject[numOfSubject]; //!< holds information for each of our subjects (data we provide)
-  OObserver* observer[numOfObserver]; //!< holds information for each of the sources we're observing
-
-  virtual OStatus DoInit   (const OSystemEvent& event); //!< first call (after constructor), set up memory
-  virtual OStatus DoStart  (const OSystemEvent& event); //!< second call, ask for messages
-  virtual OStatus DoStop   (const OSystemEvent& event); //!< next to last call, stop sending and receiving messages
-  virtual OStatus DoDestroy(const OSystemEvent& event); //!< last call (before destructor), clean up memory here
-
-  bool RPOPENR_isready; //!< set to true after RPOPENR_ready() was called
-  bool RPOPENR_isReady() { return RPOPENR_isready; } //!< indicates whether the Aibo is ready to receive more messages
-  int RPOPENR_send(char *buf, int bufsize); //!< send message to Aibo
-
-  void RPOPENR_ready(const OReadyEvent& event) { RPOPENR_isready=true; } //!< OPENR callback for registering when the Aibo is ready for messages
-  void RPOPENR_notify(const ONotifyEvent& event); //!< OPENR callback for when a message is received from the Aibo
-};
-
-/*! @file
- * @brief Describes RemoteProcess, sample RemoteProcessingOPENR process
- * @author alokl (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
- * $State: Rel $
- * $Date: 2003/09/25 15:27:50 $
- */
-
-#endif
diff -urdN ../Tekkotsu_2.3/RemoteProcess/remoteProcess.ocf ./RemoteProcess/remoteProcess.ocf
--- ../Tekkotsu_2.3/RemoteProcess/remoteProcess.ocf	Wed Mar 26 16:35:46 2003
+++ ./RemoteProcess/remoteProcess.ocf	Wed Dec 31 19:00:00 1969
@@ -1 +0,0 @@
-object remoteProcess 3072 16384 128 cache tlb user
diff -urdN ../Tekkotsu_2.3/RemoteProcess/stub.cfg ./RemoteProcess/stub.cfg
--- ../Tekkotsu_2.3/RemoteProcess/stub.cfg	Wed Mar 26 16:35:46 2003
+++ ./RemoteProcess/stub.cfg	Wed Dec 31 19:00:00 1969
@@ -1,5 +0,0 @@
-ObjectName : RemoteProcess
-NumOfOSubject   : 1
-NumOfOObserver  : 1
-Service : "RemoteProcess.RPOPENRSendString.char.S", null, RPOPENR_ready()
-Service : "RemoteProcess.RPOPENRReceiveString.char.O", null, RPOPENR_notify()
diff -urdN ../Tekkotsu_2.3/Shared/Base64.cc ./Shared/Base64.cc
--- ../Tekkotsu_2.3/Shared/Base64.cc	Wed Dec 31 19:00:00 1969
+++ ./Shared/Base64.cc	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,245 @@
+#include "Base64.h"
+#include <iostream>
+
+/*! @file
+ * @brief Describes base64 namespace, which holds some functions for encoding and decoding base64 data
+ * C_Base64 - a simple base64 encoder and decoder.
+ *
+ *     Copyright (c) 1999, Bob Withers - bwit@pobox.com
+ *
+ * This code may be freely used for any purpose, either personal
+ * or commercial, provided the authors copyright notice remains
+ * intact.
+ *
+ * Enhancements by Stanley Yamane:
+ *     - reverse lookup table for the decode function 
+ *     - reserve string buffer space in advance
+ *
+ * Modified by Ethan Tira-Thompson:
+ *     - changed Base64 class to base64 namespace
+ *     - modified functions to work on char[] instead of strings
+ *     - added doxygen commenting
+ *
+ * @author Bob Withers - bwit@pobox.com (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+using namespace std;
+
+namespace base64 {
+	static const char fillchar = '='; //!< used to mark partial words at the end
+	static const string::size_type np = string::npos; //!< shorthand for the "no position" return code from string
+	
+	//! this lookup table defines the base64 encoding
+	const string Base64Table("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
+	
+	//! Decode Table gives the index of any valid base64 character in the Base64 table]
+	/*! 65 == A, 97 == a, 48 == 0, 43 == +, 47 == / */
+	const string::size_type DecodeTable[] = {
+		np,np,np,np,np,np,np,np,np,np,  // 0 - 9
+		np,np,np,np,np,np,np,np,np,np,  //10 -19
+		np,np,np,np,np,np,np,np,np,np,  //20 -29
+		np,np,np,np,np,np,np,np,np,np,  //30 -39
+		np,np,np,62,np,np,np,63,52,53,  //40 -49
+		54,55,56,57,58,59,60,61,np,np,  //50 -59
+		np,np,np,np,np, 0, 1, 2, 3, 4,  //60 -69
+		5, 6, 7, 8, 9,10,11,12,13,14,  //70 -79
+		15,16,17,18,19,20,21,22,23,24,  //80 -89
+		25,np,np,np,np,np,np,26,27,28,  //90 -99
+		29,30,31,32,33,34,35,36,37,38,  //100 -109
+		39,40,41,42,43,44,45,46,47,48,  //110 -119
+		49,50,51,np,np,np,np,np,np,np,  //120 -129
+		np,np,np,np,np,np,np,np,np,np,  //130 -139
+		np,np,np,np,np,np,np,np,np,np,  //140 -149
+		np,np,np,np,np,np,np,np,np,np,  //150 -159
+		np,np,np,np,np,np,np,np,np,np,  //160 -169
+		np,np,np,np,np,np,np,np,np,np,  //170 -179
+		np,np,np,np,np,np,np,np,np,np,  //180 -189
+		np,np,np,np,np,np,np,np,np,np,  //190 -199
+		np,np,np,np,np,np,np,np,np,np,  //200 -209
+		np,np,np,np,np,np,np,np,np,np,  //210 -219
+		np,np,np,np,np,np,np,np,np,np,  //220 -229
+		np,np,np,np,np,np,np,np,np,np,  //230 -239
+		np,np,np,np,np,np,np,np,np,np,  //240 -249
+		np,np,np,np,np,np               //250 -256
+	};
+	
+	
+	string encode(char buf[], unsigned int len) {
+		string             ret;
+		if(len==0)
+			return "";
+		ret.reserve((len-1)/3*4 + 4 + 1);
+		
+		for (string::size_type i = 0; i < len; ++i)
+		{
+			char c;
+			c = (buf[i] >> 2) & 0x3f;
+			ret.append(1, Base64Table[c]);
+			c = (buf[i] << 4) & 0x3f;
+			if (++i < len)
+				c |= (buf[i] >> 4) & 0x0f;
+			
+			ret.append(1, Base64Table[c]);
+			if (i < len)
+			{
+				c = (buf[i] << 2) & 0x3f;
+				if (++i < len)
+					c |= (buf[i] >> 6) & 0x03;
+				
+				ret.append(1, Base64Table[c]);
+			}
+			else
+			{
+				++i;
+				ret.append(1, fillchar);
+			}
+			
+			if (i < len)
+			{
+				c = buf[i] & 0x3f;
+				ret.append(1, Base64Table[c]);
+			}
+			else
+			{
+				ret.append(1, fillchar);
+			}
+		}
+		
+		return(ret);
+	}
+	
+	unsigned int decodeSize(const std::string& data) {
+		unsigned int fills=0;
+		unsigned int size=data.size();
+		//skip any extra characters at the end (e.g. newlines or spaces)
+		while(size>0 && DecodeTable[(unsigned char)data[size-1]]==np && data[size-1]!=fillchar)
+			size--;
+		if((size/4) * 4 != size) {
+			cerr << "base 64 decodeSize error: data size is not multiple of 4" << endl;
+			return size/4*3 + 3;
+		}
+		//count fill characters ('=')
+		while(fills<size && data[size-fills-1]==fillchar)
+			fills++;
+		if(fills>2) {
+			cerr << "base 64 decodeSize error: too many fill characters";
+			size-=(fills/3) * 3;
+			fills=fills%3;
+		}
+		//cout << "Size is " << size/4*3-fills << " with " << fills << " fills and " << data.size()-size << " extra" << endl;
+		return size/4*3-fills;
+	}
+	char* decode(const std::string& data) {
+		unsigned int len=decodeSize(data);
+		char * buf = new char[len];
+		if(!decode(data,buf,len)) {
+			delete [] buf;
+			return NULL;
+		}
+		return buf;
+	}
+	bool decode(const std::string& data, char buf[], unsigned int len) {
+		const string::size_type  size = data.length();
+		string::size_type i = 0, p=0;
+		while(true)
+		{
+			bool retry=false;
+			string::size_type d=np;
+			do {
+				d=DecodeTable[(unsigned char)data[i++]];
+				retry=false;
+				if(d==np) {
+					if(fillchar == data[i-1]) {
+						cerr << "base64 decode error: unexpected fill char -- offset read?" << endl;
+						return false;
+					}
+					if(!isspace(data[i-1])) {
+						cerr << "base 64 decode error: illegal character '" << data[i-1] << '\'' << endl;
+						return false;
+					}
+					retry=true;
+				}
+			} while(retry);
+			char c = (char) d;
+			
+			do {
+				d=DecodeTable[(unsigned char)data[i++]];
+				retry=false;
+				if(d==np) {
+					if(fillchar == data[i-1]) {
+						cerr << "base64 decode error: unexpected fill char -- offset read?" << endl;
+						return false;
+					}
+					if(!isspace(data[i-1])) {
+						cerr << "base 64 decode error: illegal character '" << data[i-1] << '\'' << endl;
+						return false;
+					}
+					retry=true;
+				}
+			} while(retry);
+			if(p>=len)
+				return false;
+			char c1 = (char) d;
+			c = (c << 2) | ((c1 >> 4) & 0x3);
+			buf[p++]=c;
+			if(i>=size) {
+				cerr << "base64 decode error: Truncated data" << endl;
+				return false;
+			}
+
+			do {
+				d=DecodeTable[(unsigned char)data[i++]];
+				retry=false;
+				if(d==np) {
+					if(fillchar == data[i-1]) {
+						return true;
+					}
+					if(!isspace(data[i-1])) {
+						cerr << "base 64 decode error: illegal character '" << data[i-1] << '\'' << endl;
+						return false;
+					}
+					retry=true;
+				}
+			} while(retry);
+			if(p>=len)
+				return false;
+			c = (char) d;
+			c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
+			buf[p++]=c1;
+			if(i>=size) {
+				cerr << "base64 decode error: Truncated data" << endl;
+				return false;
+			}
+
+			do {
+				d=DecodeTable[(unsigned char)data[i++]];
+				retry=false;
+				if(d==np) {
+					if(fillchar == data[i-1]) {
+						return true;
+					}
+					if(!isspace(data[i-1])) {
+						cerr << "base 64 decode error: illegal character '" << data[i-1] << '\'' << endl;
+						return false;
+					}
+					retry=true;
+				}
+			} while(retry);
+			if(p>=len)
+				return false;
+			c1 = (char) d;
+			c = ((c << 6) & 0xc0) | c1;
+			buf[p++]=c;
+			if(i==size)
+				return true;
+		}
+		//cerr << "base64 decode error: unexpected break" << endl;
+		//return false;
+	}
+}
diff -urdN ../Tekkotsu_2.3/Shared/Base64.h ./Shared/Base64.h
--- ../Tekkotsu_2.3/Shared/Base64.h	Wed Dec 31 19:00:00 1969
+++ ./Shared/Base64.h	Sun Aug  7 00:11:03 2005
@@ -0,0 +1,52 @@
+#ifndef INCLUDED_Base64_H
+#define INCLUDED_Base64_H
+/*! @file
+ * @brief Describes base64 namespace, which holds some functions for encoding and decoding base64 data
+ * C_Base64 - a simple base64 encoder and decoder.
+ *
+ *     Copyright (c) 1999, Bob Withers - bwit@pobox.com
+ *
+ * This code may be freely used for any purpose, either personal
+ * or commercial, provided the authors copyright notice remains
+ * intact.
+ *
+ * Modified by Ethan Tira-Thompson:
+ *     - changed Base64 class to base64 namespace
+ *     - modified functions to work on char[] instead of strings
+ *     - added doxygen comments to header
+ *
+ * @author Bob Withers - bwit@pobox.com (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:03 $
+ */
+
+#include <string>
+
+//! holds some functions for encoding and decoding base64 data
+namespace base64
+{
+
+	//! returns a string containing the base64 encoding of @a len bytes from @a buf
+	std::string encode(char buf[], unsigned int len);
+
+	//! returns a pointer to a newly allocated region contained the binary data decoded from @a data
+	/*! If @a data is malformed @c NULL will be returned */
+	char* decode(const std::string& data);
+
+	//! returns the number of bytes which will be decoded from @a data
+	/*! Does not check data for correctness, just counts the fill
+	 *  characters at the end of the string */
+	unsigned int decodeSize(const std::string& data);
+
+	//! decodes @a data into @a buf, which you need to provide the size of in @a len
+	/*! If @a buf is not large enough or @a data is malformed, @c false
+	 *  will be returned; otherwise @c true */
+	bool decode(const std::string& data, char buf[], unsigned int len);
+}
+
+
+#endif
diff -urdN ../Tekkotsu_2.3/Shared/Buffer.cc ./Shared/Buffer.cc
--- ../Tekkotsu_2.3/Shared/Buffer.cc	Wed Dec 22 20:47:07 2004
+++ ./Shared/Buffer.cc	Wed Dec 22 20:47:07 2004
@@ -112,7 +112,7 @@
  * Submitted as part of "Full-duplex Audio Streaming" patch
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Exp $
  * $Date: 2004/12/23 01:47:07 $
diff -urdN ../Tekkotsu_2.3/Shared/Buffer.h ./Shared/Buffer.h
--- ../Tekkotsu_2.3/Shared/Buffer.h	Wed Dec 22 20:47:07 2004
+++ ./Shared/Buffer.h	Wed Dec 22 20:47:07 2004
@@ -61,7 +61,7 @@
  * Submitted as part of "Full-duplex Audio Streaming" patch
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.2 $
  * $State: Exp $
  * $Date: 2004/12/23 01:47:07 $
diff -urdN ../Tekkotsu_2.3/Shared/CVS/Entries ./Shared/CVS/Entries
--- ../Tekkotsu_2.3/Shared/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Shared/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,43 @@
+/Base64.cc/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/Base64.h/1.3/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/Buffer.cc/1.2/Thu Dec 23 01:47:07 2004//Ttekkotsu-2_4
+/Buffer.h/1.2/Thu Dec 23 01:47:07 2004//Ttekkotsu-2_4
+/Cloneable.h/1.1/Wed Jun 29 22:05:45 2005//Ttekkotsu-2_4
+/CommonInfo.h/1.1/Tue Dec 23 06:33:43 2003//Ttekkotsu-2_4
+/Config.cc/1.49/Fri Aug  5 19:44:22 2005//Ttekkotsu-2_4
+/Config.h/1.49/Sun Aug  7 04:11:03 2005//Ttekkotsu-2_4
+/ERS210Info.h/1.20/Wed Jun  1 05:47:48 2005//Ttekkotsu-2_4
+/ERS220Info.h/1.21/Wed Jun  1 05:47:48 2005//Ttekkotsu-2_4
+/ERS2xxInfo.h/1.15/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/ERS7Info.h/1.25/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/Factory.h/1.7/Tue Jul 26 03:11:20 2005//Ttekkotsu-2_4
+/LoadSave.cc/1.5/Thu Mar 25 17:07:44 2004//Ttekkotsu-2_4
+/LoadSave.h/1.13/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/ODataFormats.h/1.1/Wed Feb  2 18:22:29 2005//Ttekkotsu-2_4
+/Profiler.cc/1.14/Thu Jul 28 17:10:07 2005//Ttekkotsu-2_4
+/Profiler.h/1.15/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/ProjectInterface.cc/1.6/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/ProjectInterface.h/1.7/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/ReferenceCounter.h/1.8/Wed Feb  2 18:22:29 2005//Ttekkotsu-2_4
+/RobotInfo.h/1.16/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/SharedQueue.h/1.6/Wed Mar  9 02:59:53 2005//Ttekkotsu-2_4
+/SystemUtility.h/1.4/Fri Oct 10 17:46:04 2003//Ttekkotsu-2_4
+/TimeET.cc/1.3/Thu Sep 25 15:31:53 2003//Ttekkotsu-2_4
+/TimeET.h/1.5/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/Util.h/1.5/Thu Sep 25 15:31:53 2003//Ttekkotsu-2_4
+/WMclass.cc/1.3/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/WMclass.h/1.5/Tue Jul 26 03:22:04 2005//Ttekkotsu-2_4
+/WorldState.cc/1.30/Sun Jul 10 20:02:17 2005//Ttekkotsu-2_4
+/WorldState.h/1.28/Tue Jul 27 14:36:50 2004//Ttekkotsu-2_4
+/XMLLoadSave.cc/1.4/Wed Jul 27 05:58:24 2005//Ttekkotsu-2_4
+/XMLLoadSave.h/1.5/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/debuget.h/1.6/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/get_time.cc/1.4/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/get_time.h/1.4/Tue Jun 14 22:11:46 2005//Ttekkotsu-2_4
+/mathutils.h/1.3/Thu Jan  9 02:03:00 2003//Ttekkotsu-2_4
+/plist.cc/1.6/Wed Jul 27 05:58:24 2005//Ttekkotsu-2_4
+/plist.h/1.9/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/string_util.cc/1.4/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+/string_util.h/1.4/Wed Jun  1 05:47:49 2005//Ttekkotsu-2_4
+D/jpeg-6b////
+D/newmat////
diff -urdN ../Tekkotsu_2.3/Shared/CVS/Repository ./Shared/CVS/Repository
--- ../Tekkotsu_2.3/Shared/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Shared/CVS/Repository	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Tekkotsu/Shared
diff -urdN ../Tekkotsu_2.3/Shared/CVS/Root ./Shared/CVS/Root
--- ../Tekkotsu_2.3/Shared/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Shared/CVS/Root	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Shared/CVS/Tag ./Shared/CVS/Tag
--- ../Tekkotsu_2.3/Shared/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Shared/CVS/Tag	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Shared/Cloneable.h ./Shared/Cloneable.h
--- ../Tekkotsu_2.3/Shared/Cloneable.h	Wed Dec 31 19:00:00 1969
+++ ./Shared/Cloneable.h	Wed Jun 29 18:05:45 2005
@@ -0,0 +1,47 @@
+//-*-c++-*-
+#ifndef INCLUDED_Cloneable_h_
+#define INCLUDED_Cloneable_h_
+
+//! An interface for cloning objects -- needed for making copies with polymorphism (operator= doesn't work as virtual)
+class Cloneable {
+public:
+	virtual ~Cloneable() {}
+
+	//! returns a copy of @c this
+	/*! When implementing, your class @e should use its own type as the
+	 *  return type, e.g.:
+	 *
+	 *  @code
+	 *  class Foo : public Cloneable {
+	 *  public:
+	 *    //note: return Foo* instead of Cloneable* !
+	 *    //Allows users to avoid needing to cast the results
+	 *    virtual Foo* clone() { return new Foo(*this); }
+	 *  };
+	 *  @endcode
+	 *
+	 *  <i>HOWEVER, this is currently unsupported in gcc 3.3</i>, which
+	 *  the latest version for which Sony has supplied the patches to
+	 *  work on the Aibo.
+	 *
+	 *  So instead, you must currently provide the interface exactly as
+	 *  shown, and then the caller will probably need to cast the result
+	 *  to the known type.  Hopefully Sony will eventually update the
+	 *  gcc version to at least 3.4 and we can switch over to use the
+	 *  "covariant return type".
+	 */
+	virtual Cloneable* clone() const=0;
+};
+
+/*! @file
+ * @brief Defines Cloneable, and interfacing for cloning objects -- needed for making copies with polymorphism (operator= doesn't work as virtual)
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.1 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:05:45 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Shared/CommonInfo.h ./Shared/CommonInfo.h
--- ../Tekkotsu_2.3/Shared/CommonInfo.h	Tue Dec 23 01:33:43 2003
+++ ./Shared/CommonInfo.h	Tue Dec 23 01:33:43 2003
@@ -34,7 +34,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.1 $
  * $State: Exp $
  * $Date: 2003/12/23 06:33:43 $
diff -urdN ../Tekkotsu_2.3/Shared/Config.cc ./Shared/Config.cc
--- ../Tekkotsu_2.3/Shared/Config.cc	Thu Jan 20 18:18:43 2005
+++ ./Shared/Config.cc	Fri Aug  5 15:44:22 2005
@@ -10,33 +10,76 @@
 #  include <OPENR/OPrimitiveControl.h>
 #  include <OPENR/OPENRAPI.h>
 #else
-  typedef unsigned int OSpeakerVolume;
-  const OSpeakerVolume ospkvolinfdB = 0x8000;
-  const OSpeakerVolume ospkvol25dB  = 0xe700;
-  const OSpeakerVolume ospkvol18dB  = 0xee00;
-  const OSpeakerVolume ospkvol10dB  = 0xf600;
+#include <sys/param.h>
+#include <unistd.h>
+typedef unsigned int OSpeakerVolume;
+const OSpeakerVolume ospkvolinfdB = 0x8000;
+const OSpeakerVolume ospkvol25dB  = 0xe700;
+const OSpeakerVolume ospkvol18dB  = 0xee00;
+const OSpeakerVolume ospkvol10dB  = 0xf600;
 #endif
 
 Config* config=NULL;
 
-void* Config::setValue(section_t section, const char *key, const char *value,
-											 bool /*updated*/) {
-  switch (section) {
-    case sec_wireless:
-      if (strncasecmp(key,"id",29)==0) {
-        wireless.id=atoi(value);
-        return &wireless.id;
-      }
-      break;
-    case sec_vision:
-      if (strncasecmp(key,"white_balance",29)==0) {
-        if (strncasecmp(value,"indoor",49)==0) {
-          vision.white_balance=1;
-        } else if (strncasecmp(value,"flourescent",49)==0) {
-          vision.white_balance=3;
-        } else if (strncasecmp(value,"outdoor",49)==0) {
-          vision.white_balance=2;
-        }
+void Config::setFileSystemRoot(const std::string& fsr) {
+#ifdef PLATFORM_APERIOS
+	if(fsr[0]=='/')
+		fsRoot="/ms"+fsr;
+	else
+		fsRoot="/ms/"+fsr;
+#else
+	char buf[MAXPATHLEN+2];
+	if(getcwd(buf,MAXPATHLEN+2)==NULL)
+		perror("Config::setFileSystemRoot(): getcwd");
+	buf[MAXPATHLEN+1]='\0';
+	std::string sbuf(buf);
+	if(sbuf[sbuf.size()-1]!='/' && fsr[0]!='/')
+		fsRoot=sbuf+'/'+fsr;
+	else if(sbuf[sbuf.size()-1]=='/' && fsr[0]=='/')
+		fsRoot=sbuf+fsr.substr(1);
+	else
+		fsRoot=sbuf+fsr;
+#endif
+}
+
+
+std::string Config::portPath(const std::string& path) const {
+	if(fsRoot.size()==0)
+		return path;
+	if(path.size()==0)
+		return fsRoot;
+	if(path.substr(0,fsRoot.size())==fsRoot)
+		return path;
+	else if(fsRoot[fsRoot.size()-1]=='/') {
+	  if(path[0]!='/')
+	    return fsRoot+path;
+	  else
+	    return fsRoot+path.substr(1);
+	} else {
+	  if(path[0]!='/')
+	    return fsRoot+'/'+path;
+	  else
+	    return fsRoot+path;
+	}
+}
+
+void* Config::setValue(section_t section, const char *key, const char *value, bool /*updated*/) {
+	switch (section) {
+		case sec_wireless:
+			if (strncasecmp(key,"id",29)==0) {
+				wireless.id=atoi(value);
+				return &wireless.id;
+			}
+			break;
+		case sec_vision:
+			if (strncasecmp(key,"white_balance",29)==0) {
+				if (strncasecmp(value,"indoor",49)==0) {
+					vision.white_balance=1;
+				} else if (strncasecmp(value,"flourescent",49)==0) {
+					vision.white_balance=3;
+				} else if (strncasecmp(value,"outdoor",49)==0) {
+					vision.white_balance=2;
+				}
 #ifdef PLATFORM_APERIOS
 				//this will actually send the new setting to the system
 				OPrimitiveID fbkID = 0;
@@ -50,15 +93,15 @@
 					OPENR::ClosePrimitive(fbkID);
 				}
 #endif
-        return &vision.white_balance;
-      } else if (strncasecmp(key,"gain",29)==0) {
-        if (strncasecmp(value,"low",49)==0) {
-          vision.gain=1;
-        } else if (strncasecmp(value,"mid",49)==0) {
-          vision.gain=2;
-        } else if (strncasecmp(value,"high",49)==0) {
-          vision.gain=3;
-        }
+				return &vision.white_balance;
+			} else if (strncasecmp(key,"gain",29)==0) {
+				if (strncasecmp(value,"low",49)==0) {
+					vision.gain=1;
+				} else if (strncasecmp(value,"mid",49)==0) {
+					vision.gain=2;
+				} else if (strncasecmp(value,"high",49)==0) {
+					vision.gain=3;
+				}
 #ifdef PLATFORM_APERIOS
 				//this will actually send the new setting to the system
 				OPrimitiveID fbkID = 0;
@@ -71,15 +114,15 @@
 					OPENR::ClosePrimitive(fbkID);
 				}
 #endif
-        return &vision.gain;
-      } else if (strncasecmp(key,"shutter_speed",29)==0) {
-        if (strncasecmp(value,"slow",49)==0) {
-          vision.shutter_speed=1;
-        } else if (strncasecmp(value,"mid",49)==0) {
-          vision.shutter_speed=2;
-        } else if (strncasecmp(value,"fast",49)==0) {
-          vision.shutter_speed=3;
-        }
+				return &vision.gain;
+			} else if (strncasecmp(key,"shutter_speed",29)==0) {
+				if (strncasecmp(value,"slow",49)==0) {
+					vision.shutter_speed=1;
+				} else if (strncasecmp(value,"mid",49)==0) {
+					vision.shutter_speed=2;
+				} else if (strncasecmp(value,"fast",49)==0) {
+					vision.shutter_speed=3;
+				}
 #ifdef PLATFORM_APERIOS
 				//this will actually send the new setting to the system
 				OPrimitiveID fbkID = 0;
@@ -92,248 +135,300 @@
 					OPENR::ClosePrimitive(fbkID);
 				}
 #endif
-        return &vision.shutter_speed;
-      } else if (strncasecmp(key,"resolution",29)==0) {
-        if (strncasecmp(value,"full",49)==0) {
-          vision.resolution=1;
-        } else if (strncasecmp(value,"half",49)==0) {
-          vision.resolution=2;
-        } else if (strncasecmp(value,"quarter",49)==0) {
-          vision.resolution=3;
-        }
-        return &vision.resolution;
-      } else if (strncasecmp(key,"horizFOV",29)==0) {
-				vision.horizFOV=atof(value)*M_PI/180;
-        return &vision.horizFOV;
-      } else if (strncasecmp(key,"vertFOV",29)==0) {
-				vision.vertFOV=atof(value)*M_PI/180;
-        return &vision.vertFOV;
-      } else if (strncasecmp(key,"focal_length",29)==0) {
-				vision.focal_length=atof(value);
-        return &vision.focal_length;
-      } else if (strncasecmp(key,"thresh",29)==0) {
+				return &vision.shutter_speed;
+			} else if (strncasecmp(key,"resolution",29)==0) {
+				if (strncasecmp(value,"full",49)==0) {
+					vision.resolution=1;
+				} else if (strncasecmp(value,"half",49)==0) {
+					vision.resolution=2;
+				} else if (strncasecmp(value,"quarter",49)==0) {
+					vision.resolution=3;
+				}
+				return &vision.resolution;
+			} else if (strncasecmp(key,"thresh",29)==0) {
 				vision.thresh.push_back(value);
-        return &vision.thresh;
-      } else if (strncasecmp(key,"colors",29)==0) {
-        strncpy(vision.colors,value,49);
-        return &vision.colors;
-      } else if (strncasecmp(key,"raw_port",29)==0) {
-        vision.rawcam_port=atoi(value);
-        return &vision.rawcam_port;
-      } else if (strncasecmp(key,"raw_transport",29)==0) {
-        if (strncasecmp(value,"udp",49)==0)
-          vision.rawcam_transport=0;
-        else if (strncasecmp(value,"tcp",49)==0)
-          vision.rawcam_transport=1;
-        return &vision.rawcam_transport;
-      } else if (strncasecmp(key,"rle_port",29)==0) {
-        vision.rle_port=atoi(value);
-        return &vision.rle_port;
-      } else if (strncasecmp(key,"rle_transport",29)==0) {
-        if (strncasecmp(value,"udp",49)==0)
-          vision.rle_transport=0;
-        else if (strncasecmp(value,"tcp",49)==0)
-          vision.rle_transport=1;
-        return &vision.rle_transport;
-      } else if (strncasecmp(key,"obj_port",29)==0) {
-        vision.obj_port=atoi(value);
-        return &vision.obj_port;
-      } else if (strncasecmp(key,"restore_image",29)==0) {
-        vision.restore_image=atoi(value);
-        return &vision.obj_port;
-      } else if (strncasecmp(key,"jpeg_dct_method",29)==0) {
-        if (strncasecmp(value,"islow",49)==0) {
-          vision.jpeg_dct_method=JDCT_ISLOW;
-        } else if (strncasecmp(value,"ifast",49)==0) {
-          vision.jpeg_dct_method=JDCT_IFAST;
-        } else if (strncasecmp(value,"float",49)==0) {
-          vision.jpeg_dct_method=JDCT_FLOAT;
-		}
-		return &vision.jpeg_dct_method;
-      } else if (strncasecmp(key,"rawcam_encoding",29)==0) {
-        if (strncasecmp(value,"color",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_COLOR;
-          vision.rawcam_channel=RawCameraGenerator::CHAN_Y;
-        } else if (strncasecmp(value,"y_only",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
-          vision.rawcam_channel=RawCameraGenerator::CHAN_Y;
-        } else if (strncasecmp(value,"uv_only",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_COLOR;
+				return &vision.thresh;
+			} else if (strncasecmp(key,"colors",29)==0) {
+				strncpy(vision.colors,value,49);
+				return &vision.colors;
+			} else if (strncasecmp(key,"rawcam_port",29)==0 || strncasecmp(key,"raw_port",29)==0) {
+				if(strncasecmp(key,"raw_port",29)==0)
+					std::cout << "Your tekkotsu.cfg file uses deprecated raw_port -- use rawcam_port instead" << std::endl;
+				vision.rawcam_port=atoi(value);
+				return &vision.rawcam_port;
+			} else if (strncasecmp(key,"rawcam_transport",29)==0 || strncasecmp(key,"raw_transport",29)==0) {
+				if(strncasecmp(key,"raw_transport",29)==0)
+					std::cout << "Your tekkotsu.cfg file uses deprecated raw_transport -- use rawcam_transport instead" << std::endl;
+				if (strncasecmp(value,"udp",49)==0)
+					vision.rawcam_transport=0;
+				else if (strncasecmp(value,"tcp",49)==0)
+					vision.rawcam_transport=1;
+				return &vision.rawcam_transport;
+			} else if (strncasecmp(key,"rawcam_interval",29)==0) {
+				vision.rawcam_interval=(unsigned int)atoi(value);
+				return &vision.rawcam_interval;
+			} else if (strncasecmp(key,"rle_port",29)==0) {
+				vision.rle_port=atoi(value);
+				return &vision.rle_port;
+			} else if (strncasecmp(key,"rle_transport",29)==0) {
+				if (strncasecmp(value,"udp",49)==0)
+					vision.rle_transport=0;
+				else if (strncasecmp(value,"tcp",49)==0)
+					vision.rle_transport=1;
+				return &vision.rle_transport;
+			} else if (strncasecmp(key,"rle_interval",29)==0) {
+				vision.rle_interval=(unsigned int)atoi(value);
+				return &vision.rle_interval;
+			} else if (strncasecmp(key,"region_port",29)==0) {
+				vision.region_port=atoi(value);
+				return &vision.region_port;
+			} else if (strncasecmp(key,"region_transport",29)==0) {
+				if (strncasecmp(value,"udp",49)==0)
+					vision.region_transport=0;
+				else if (strncasecmp(value,"tcp",49)==0)
+					vision.region_transport=1;
+				return &vision.region_transport;
+			} else if (strncasecmp(key,"obj_port",29)==0) {
+				vision.obj_port=atoi(value);
+				return &vision.obj_port;
+			} else if (strncasecmp(key,"restore_image",29)==0) {
+				vision.restore_image=atoi(value);
+				return &vision.restore_image;
+			} else if (strncasecmp(key,"jpeg_dct_method",29)==0) {
+				if (strncasecmp(value,"islow",49)==0) {
+					vision.jpeg_dct_method=JDCT_ISLOW;
+				} else if (strncasecmp(value,"ifast",49)==0) {
+					vision.jpeg_dct_method=JDCT_IFAST;
+				} else if (strncasecmp(value,"float",49)==0) {
+					vision.jpeg_dct_method=JDCT_FLOAT;
+				}
+				return &vision.jpeg_dct_method;
+			} else if (strncasecmp(key,"rawcam_encoding",29)==0) {
+				if (strncasecmp(value,"color",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_COLOR;
+					vision.rawcam_channel=RawCameraGenerator::CHAN_Y;
+				} else if (strncasecmp(value,"y_only",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
+					vision.rawcam_channel=RawCameraGenerator::CHAN_Y;
+				} else if (strncasecmp(value,"uv_only",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_COLOR;
 					vision.rawcam_channel=-1;
-        } else if (strncasecmp(value,"u_only",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
-          vision.rawcam_channel=RawCameraGenerator::CHAN_U;
-        } else if (strncasecmp(value,"v_only",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
-          vision.rawcam_channel=RawCameraGenerator::CHAN_V;
-        } else if (strncasecmp(value,"y_dx_only",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
-          vision.rawcam_channel=RawCameraGenerator::CHAN_Y_DX;
-        } else if (strncasecmp(value,"y_dy_only",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
-          vision.rawcam_channel=RawCameraGenerator::CHAN_Y_DY;
-        } else if (strncasecmp(value,"y_dxdy_only",49)==0) {
-          vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
-          vision.rawcam_channel=RawCameraGenerator::CHAN_Y_DXDY;
-        }
-        return &vision.rawcam_encoding;
-      } else if (strncasecmp(key,"rawcam_compression",29)==0) {
-        if (strncasecmp(value,"none",49)==0) {
-          vision.rawcam_compression=vision_config::COMPRESS_NONE;
-        } else if (strncasecmp(value,"jpeg",49)==0) {
-          vision.rawcam_compression=vision_config::COMPRESS_JPEG;
+				} else if (strncasecmp(value,"u_only",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
+					vision.rawcam_channel=RawCameraGenerator::CHAN_U;
+				} else if (strncasecmp(value,"v_only",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
+					vision.rawcam_channel=RawCameraGenerator::CHAN_V;
+				} else if (strncasecmp(value,"y_dx_only",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
+					vision.rawcam_channel=RawCameraGenerator::CHAN_Y_DX;
+				} else if (strncasecmp(value,"y_dy_only",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
+					vision.rawcam_channel=RawCameraGenerator::CHAN_Y_DY;
+				} else if (strncasecmp(value,"y_dxdy_only",49)==0) {
+					vision.rawcam_encoding=vision_config::ENCODE_SINGLE_CHANNEL;
+					vision.rawcam_channel=RawCameraGenerator::CHAN_Y_DXDY;
+				}
+				return &vision.rawcam_encoding;
+			} else if (strncasecmp(key,"rawcam_compression",29)==0) {
+				if (strncasecmp(value,"none",49)==0) {
+					vision.rawcam_compression=vision_config::COMPRESS_NONE;
+				} else if (strncasecmp(value,"jpeg",49)==0) {
+					vision.rawcam_compression=vision_config::COMPRESS_JPEG;
 				}
 				return &vision.rawcam_compression;
-      } else if (strncasecmp(key,"rawcam_compress_quality",29)==0) {
-        vision.rawcam_compress_quality=atoi(value);
-        return &vision.rawcam_compress_quality;
-      } else if (strncasecmp(key,"rawcam_y_skip",29)==0) {
-        vision.rawcam_y_skip=atoi(value);
-        return &vision.rawcam_y_skip;
-      } else if (strncasecmp(key,"rawcam_uv_skip",29)==0) {
-        vision.rawcam_uv_skip=atoi(value);
-        return &vision.rawcam_uv_skip;
-      } else if (strncasecmp(key,"rlecam_skip",29)==0) {
-        vision.rlecam_skip=atoi(value);
-        return &vision.rlecam_skip;
-      } else if (strncasecmp(key,"rlecam_channel",29)==0) {
-        vision.rlecam_channel=atoi(value);
-        return &vision.rlecam_channel;
-      } else if (strncasecmp(key,"rlecam_compression",29)==0) {
-        if (strncasecmp(value,"none",49)==0) {
-          vision.rlecam_compression=vision_config::COMPRESS_NONE;
-        } else if (strncasecmp(value,"rle",49)==0) {
-          vision.rlecam_compression=vision_config::COMPRESS_RLE;
+			} else if (strncasecmp(key,"rawcam_compress_quality",29)==0) {
+				vision.rawcam_compress_quality=atoi(value);
+				return &vision.rawcam_compress_quality;
+			} else if (strncasecmp(key,"rawcam_y_skip",29)==0) {
+				vision.rawcam_y_skip=atoi(value);
+				return &vision.rawcam_y_skip;
+			} else if (strncasecmp(key,"rawcam_uv_skip",29)==0) {
+				vision.rawcam_uv_skip=atoi(value);
+				return &vision.rawcam_uv_skip;
+			} else if (strncasecmp(key,"rlecam_skip",29)==0) {
+				vision.rlecam_skip=atoi(value);
+				return &vision.rlecam_skip;
+			} else if (strncasecmp(key,"rlecam_channel",29)==0) {
+				vision.rlecam_channel=atoi(value);
+				return &vision.rlecam_channel;
+			} else if (strncasecmp(key,"rlecam_compression",29)==0) {
+				if (strncasecmp(value,"none",49)==0) {
+					vision.rlecam_compression=vision_config::COMPRESS_NONE;
+				} else if (strncasecmp(value,"rle",49)==0) {
+					vision.rlecam_compression=vision_config::COMPRESS_RLE;
 				}
 				return &vision.rlecam_compression;
+			} else if (strncasecmp(key,"regioncam_skip",29)==0) {
+				vision.regioncam_skip=atoi(value);
+				return &vision.regioncam_skip;
+			} else if (strncasecmp(key,"focal_len_x",29)==0) {
+				vision.focal_len_x=atof(value);
+				return &vision.focal_len_x;
+			} else if (strncasecmp(key,"focal_len_y",29)==0) {
+				vision.focal_len_y=atof(value);
+				return &vision.focal_len_y;
+			} else if (strncasecmp(key,"principle_point_x",29)==0) {
+				vision.principle_point_x=atof(value);
+				return &vision.principle_point_x;
+			} else if (strncasecmp(key,"principle_point_y",29)==0) {
+				vision.principle_point_y=atof(value);
+				return &vision.principle_point_y;
+			} else if (strncasecmp(key,"skew",29)==0) {
+				vision.skew=atof(value);
+				return &vision.skew;
+			} else if (strncasecmp(key,"kc1_r2",29)==0) {
+				vision.kc1_r2=atof(value);
+				return &vision.kc1_r2;
+			} else if (strncasecmp(key,"kc2_r4",29)==0) {
+				vision.kc2_r4=atof(value);
+				return &vision.kc2_r4;
+			} else if (strncasecmp(key,"kc5_r6",29)==0) {
+				vision.kc5_r6=atof(value);
+				return &vision.kc5_r6;
+			} else if (strncasecmp(key,"kc3_tan1",29)==0) {
+				vision.kc3_tan1=atof(value);
+				return &vision.kc3_tan1;
+			} else if (strncasecmp(key,"kc4_tan2",29)==0) {
+				vision.kc4_tan2=atof(value);
+				return &vision.kc4_tan2;
+			} else if (strncasecmp(key,"calibration_res_x",29)==0) {
+				vision.calibration_res_x=atoi(value);
+				return &vision.kc4_tan2;
+			} else if (strncasecmp(key,"calibration_res_y",29)==0) {
+				vision.calibration_res_y=atoi(value);
+				return &vision.calibration_res_y;
 			}
-      break;
-    case sec_main:
-      if (strncasecmp(key,"console_port",29)==0) {
-        main.console_port=atoi(value);
-        return &main.console_port;
-      } else if (strncasecmp(key,"stderr_port",29)==0) {
-        main.stderr_port=atoi(value);
-        return &main.stderr_port;
-      } else if (strncasecmp(key,"error_level",29)==0) {
-        main.error_level=atoi(value);
-        return &main.error_level;
-      } else if (strncasecmp(key,"debug_level",29)==0) {
-        main.debug_level=atoi(value);
-        return &main.debug_level;
-      } else if (strncasecmp(key,"verbose_level",29)==0) {
-        main.verbose_level=atoi(value);
-        return &main.verbose_level;
-      } else if (strncasecmp(key,"wsjoints_port",29)==0) {
-        main.wsjoints_port=atoi(value);
-        return &main.wsjoints_port;
-      } else if (strncasecmp(key,"wspids_port",29)==0) {
-        main.wspids_port=atoi(value);
-        return &main.wspids_port;
-      } else if (strncasecmp(key,"headControl_port",29)==0) {
-        main.headControl_port=atoi(value);
-        return &main.headControl_port;
-      } else if (strncasecmp(key,"walkControl_port",29)==0) {
-        main.walkControl_port=atoi(value);
-        return &main.walkControl_port;
-      } else if (strncasecmp(key,"estopControl_port",29)==0) {
-        main.estopControl_port=atoi(value);
-        return &main.estopControl_port;
-      } else if (strncasecmp(key,"aibo3d_port",29)==0) {
-        main.aibo3d_port=atoi(value);
-        return &main.aibo3d_port;
-      } else if (strncasecmp(key,"wmmonitor_port",29)==0) {
-        main.wmmonitor_port=atoi(value);
-        return &main.wmmonitor_port;
-      } else if (strncasecmp(key,"use_VT100",29)==0) {
-        main.use_VT100=extractBool(value);
-        return &main.use_VT100;
-      }
-      break;
-    case sec_behaviors:
-      if (strncasecmp(key,"flash_bytes",29)==0) {
-        behaviors.flash_bytes = atoi(value);
-        return &behaviors.flash_bytes;
-      } else if (strncasecmp(key,"flash_on_start",29)==0) {
-        behaviors.flash_on_start = atoi(value);
-        return &behaviors.flash_on_start;
+			break;
+		case sec_main:
+			if (strncasecmp(key,"seed_rng",29)==0) {
+				main.seed_rng=atoi(value);
+				return &main.console_port;
+			} else if (strncasecmp(key,"console_port",29)==0) {
+				main.console_port=atoi(value);
+				return &main.console_port;
+			} else if (strncasecmp(key,"stderr_port",29)==0) {
+				main.stderr_port=atoi(value);
+				return &main.stderr_port;
+			} else if (strncasecmp(key,"error_level",29)==0) {
+				main.error_level=atoi(value);
+				return &main.error_level;
+			} else if (strncasecmp(key,"debug_level",29)==0) {
+				main.debug_level=atoi(value);
+				return &main.debug_level;
+			} else if (strncasecmp(key,"verbose_level",29)==0) {
+				main.verbose_level=atoi(value);
+				return &main.verbose_level;
+			} else if (strncasecmp(key,"wsjoints_port",29)==0) {
+				main.wsjoints_port=atoi(value);
+				return &main.wsjoints_port;
+			} else if (strncasecmp(key,"wspids_port",29)==0) {
+				main.wspids_port=atoi(value);
+				return &main.wspids_port;
+			} else if (strncasecmp(key,"headControl_port",29)==0) {
+				main.headControl_port=atoi(value);
+				return &main.headControl_port;
+			} else if (strncasecmp(key,"walkControl_port",29)==0) {
+				main.walkControl_port=atoi(value);
+				return &main.walkControl_port;
+			} else if (strncasecmp(key,"estopControl_port",29)==0) {
+				main.estopControl_port=atoi(value);
+				return &main.estopControl_port;
+			} else if (strncasecmp(key,"aibo3d_port",29)==0) {
+				main.aibo3d_port=atoi(value);
+				return &main.aibo3d_port;
+			} else if (strncasecmp(key,"wmmonitor_port",29)==0) {
+				main.wmmonitor_port=atoi(value);
+				return &main.wmmonitor_port;
+			} else if (strncasecmp(key,"use_VT100",29)==0) {
+				main.use_VT100=extractBool(value);
+				return &main.use_VT100;
 			}
-      break;
-    case sec_controller:
-      if (strncasecmp(key,"gui_port",29)==0) {
-        controller.gui_port = atoi(value);
-        return &controller.gui_port ;
-      } else if (strncasecmp(key,"select_snd",29)==0) {
-        strncpy(controller.select_snd,value,49);
-        return &controller.select_snd;
-      } else if (strncasecmp(key,"next_snd",29)==0) {
-        strncpy(controller.next_snd,value,49);
-        return &controller.next_snd;
-      } else if (strncasecmp(key,"prev_snd",29)==0) {
-        strncpy(controller.prev_snd,value,49);
-        return &controller.prev_snd;
-      } else if (strncasecmp(key,"read_snd",29)==0) {
-        strncpy(controller.read_snd,value,49);
-        return &controller.read_snd;
-      } else if (strncasecmp(key,"cancel_snd",29)==0) {
-        strncpy(controller.cancel_snd,value,49);
-        return &controller.cancel_snd;
-      } else if (strncasecmp(key,"error_snd",29)==0) {
-        strncpy(controller.error_snd,value,49);
-        return &controller.error_snd;
-      }
-      break;
-    case sec_motion:
-      if (strncasecmp(key,"root",29)==0) {
-        motion.root=value;
-        return &motion.root;
+			break;
+		case sec_behaviors:
+			if (strncasecmp(key,"flash_bytes",29)==0) {
+				behaviors.flash_bytes = atoi(value);
+				return &behaviors.flash_bytes;
+			} else if (strncasecmp(key,"flash_on_start",29)==0) {
+				behaviors.flash_on_start = atoi(value);
+				return &behaviors.flash_on_start;
+			}
+			break;
+		case sec_controller:
+			if (strncasecmp(key,"gui_port",29)==0) {
+				controller.gui_port = atoi(value);
+				return &controller.gui_port ;
+			} else if (strncasecmp(key,"select_snd",29)==0) {
+				strncpy(controller.select_snd,value,49);
+				return &controller.select_snd;
+			} else if (strncasecmp(key,"next_snd",29)==0) {
+				strncpy(controller.next_snd,value,49);
+				return &controller.next_snd;
+			} else if (strncasecmp(key,"prev_snd",29)==0) {
+				strncpy(controller.prev_snd,value,49);
+				return &controller.prev_snd;
+			} else if (strncasecmp(key,"read_snd",29)==0) {
+				strncpy(controller.read_snd,value,49);
+				return &controller.read_snd;
+			} else if (strncasecmp(key,"cancel_snd",29)==0) {
+				strncpy(controller.cancel_snd,value,49);
+				return &controller.cancel_snd;
+			} else if (strncasecmp(key,"error_snd",29)==0) {
+				strncpy(controller.error_snd,value,49);
+				return &controller.error_snd;
+			}
+			break;
+		case sec_motion:
+			if (strncasecmp(key,"root",29)==0) {
+				motion.root=value;
+				return &motion.root;
 			} else if (strncasecmp(key,"walk",29)==0) {
-        motion.walk=value;
-        return &motion.walk;
+				motion.walk=value;
+				return &motion.walk;
 			} else if (strncasecmp(key,"kinematics",29)==0) {
-        motion.kinematics=value;
-        return &motion.walk;
-      } else if (strncasecmp(key,"kinematic_chains",29)==0) {
+				motion.kinematics=value;
+				return &motion.walk;
+			} else if (strncasecmp(key,"kinematic_chains",29)==0) {
 				motion.kinematic_chains.push_back(value);
-        return &motion.kinematic_chains;
-      } else if (strncasecmp(key,"calibrate:",10)==0) {
+				return &motion.kinematic_chains;
+			} else if (strncasecmp(key,"calibrate:",10)==0) {
 				for(unsigned int i=PIDJointOffset; i<PIDJointOffset+NumPIDJoints; i++)
 					if(strncasecmp(&key[10],outputNames[i],outputNameLen+1)==0) { //+1 to ensure full match
 						motion.calibration[i-PIDJointOffset] = atof(value);
 						return &motion.calibration[i];
 					}
-				std::cout << "WARNING: Could not match '" << (strlen(key)>10?&key[10]:key) << "' as calibration parameter" << std::endl;
+						std::cout << "WARNING: Could not match '" << (strlen(key)>10?&key[10]:key) << "' as calibration parameter" << std::endl;
 				return NULL;
-      } else if (strncasecmp(key,"estop_on_snd",29)==0) {
-        strncpy(motion.estop_on_snd,value,49);
-        return &motion.estop_on_snd;
-      } else if (strncasecmp(key,"estop_off_snd",29)==0) {
-        strncpy(motion.estop_off_snd,value,49);
-        return &motion.estop_off_snd;
-      } else if (strncasecmp(key,"max_head_tilt_speed",29)==0) {
+			} else if (strncasecmp(key,"estop_on_snd",29)==0) {
+				strncpy(motion.estop_on_snd,value,49);
+				return &motion.estop_on_snd;
+			} else if (strncasecmp(key,"estop_off_snd",29)==0) {
+				strncpy(motion.estop_off_snd,value,49);
+				return &motion.estop_off_snd;
+			} else if (strncasecmp(key,"max_head_tilt_speed",29)==0) {
 				motion.max_head_tilt_speed=atof(value);
 				return &motion.max_head_tilt_speed;
-      } else if (strncasecmp(key,"max_head_pan_speed",29)==0) {
+			} else if (strncasecmp(key,"max_head_pan_speed",29)==0) {
 				motion.max_head_pan_speed=atof(value);
 				return &motion.max_head_pan_speed;
-      } else if (strncasecmp(key,"max_head_roll_speed",29)==0) {
+			} else if (strncasecmp(key,"max_head_roll_speed",29)==0) {
 				motion.max_head_roll_speed=atof(value);
 				return &motion.max_head_roll_speed;
-      } else if (strncasecmp(key,"inf_walk_accel",29)==0) {
-        motion.inf_walk_accel = atoi(value);
-        return &motion.inf_walk_accel;
-      } else if (strncasecmp(key,"console_port",29)==0) {
-        motion.console_port = atoi(value);
-        return &motion.console_port;
-      } else if (strncasecmp(key,"stderr_port",29)==0) {
-        motion.stderr_port = atoi(value);
-        return &motion.stderr_port ;
-      }
-      break;
-    case sec_sound:
-      if (strncasecmp(key,"root",29)==0) {
-        sound.root=value;
-        return &sound.root;
+			} else if (strncasecmp(key,"inf_walk_accel",29)==0) {
+				motion.inf_walk_accel = atoi(value);
+				return &motion.inf_walk_accel;
+			} else if (strncasecmp(key,"console_port",29)==0) {
+				motion.console_port = atoi(value);
+				return &motion.console_port;
+			} else if (strncasecmp(key,"stderr_port",29)==0) {
+				motion.stderr_port = atoi(value);
+				return &motion.stderr_port ;
+			}
+			break;
+		case sec_sound:
+			if (strncasecmp(key,"root",29)==0) {
+				sound.root=value;
+				return &sound.root;
 			} else if (strncasecmp(key,"volume",29)==0) {
 				if(strncasecmp(value,"mute",49)==0)
 					sound.volume=ospkvolinfdB;
@@ -345,71 +440,71 @@
 					sound.volume=ospkvol10dB;
 				else
 					sound.volume=strtol(value,NULL,0);
-        return &sound.volume;
-      } else if (strncasecmp(key,"sample_rate",29)==0) {
-        sound.sample_rate = atoi(value);
-        return &sound.sample_rate ;
-      } else if (strncasecmp(key,"sample_bits",29)==0) {
-        sound.sample_bits = atoi(value);
-        return &sound.sample_bits ;
-      } else if (strncasecmp(key,"preload",29)==0) {
-        sound.preload.push_back(value);
-        return &sound.preload ;
-      } else if (strncasecmp(key,"streaming.mic_port",29)==0) {
-        sound.streaming.mic_port = atoi(value);
-        return &sound.streaming.mic_port;
-      } else if (strncasecmp(key,"streaming.mic_sample_rate",29)==0) {
-        sound.streaming.mic_sample_rate = atoi(value);
-        return &sound.streaming.mic_sample_rate;
-      } else if (strncasecmp(key,"streaming.mic_sample_bits",29)==0) {
-        sound.streaming.mic_sample_bits = atoi(value);
-        return &sound.streaming.mic_sample_bits;
-      } else if (strncasecmp(key,"streaming.mic_stereo",29)==0) {
-        sound.streaming.mic_stereo = extractBool(value);
-        return &sound.streaming.mic_stereo;
-      } else if (strncasecmp(key,"streaming.speaker_port",29)==0) {
-        sound.streaming.speaker_port = atoi(value);
-        return &sound.streaming.speaker_port;
-      } else if (strncasecmp(key,"streaming.speaker_frame_length",30)==0) {
-        sound.streaming.speaker_frame_length = atoi(value);
-        return &sound.streaming.speaker_frame_length;
-      } else if (strncasecmp(key,"streaming.speaker_max_delay",29)==0) {
-        sound.streaming.speaker_max_delay = atoi(value);
-        return &sound.streaming.speaker_max_delay;
-      }
-      break;
-    default:
-      break;
-  }
-  return NULL;
+				return &sound.volume;
+			} else if (strncasecmp(key,"sample_rate",29)==0) {
+				sound.sample_rate = atoi(value);
+				return &sound.sample_rate ;
+			} else if (strncasecmp(key,"sample_bits",29)==0) {
+				sound.sample_bits = atoi(value);
+				return &sound.sample_bits ;
+			} else if (strncasecmp(key,"preload",29)==0) {
+				sound.preload.push_back(value);
+				return &sound.preload ;
+			} else if (strncasecmp(key,"streaming.mic_port",29)==0) {
+				sound.streaming.mic_port = atoi(value);
+				return &sound.streaming.mic_port;
+			} else if (strncasecmp(key,"streaming.mic_sample_rate",29)==0) {
+				sound.streaming.mic_sample_rate = atoi(value);
+				return &sound.streaming.mic_sample_rate;
+			} else if (strncasecmp(key,"streaming.mic_sample_bits",29)==0) {
+				sound.streaming.mic_sample_bits = atoi(value);
+				return &sound.streaming.mic_sample_bits;
+			} else if (strncasecmp(key,"streaming.mic_stereo",29)==0) {
+				sound.streaming.mic_stereo = extractBool(value);
+				return &sound.streaming.mic_stereo;
+			} else if (strncasecmp(key,"streaming.speaker_port",29)==0) {
+				sound.streaming.speaker_port = atoi(value);
+				return &sound.streaming.speaker_port;
+			} else if (strncasecmp(key,"streaming.speaker_frame_length",30)==0) {
+				sound.streaming.speaker_frame_length = atoi(value);
+				return &sound.streaming.speaker_frame_length;
+			} else if (strncasecmp(key,"streaming.speaker_max_delay",29)==0) {
+				sound.streaming.speaker_max_delay = atoi(value);
+				return &sound.streaming.speaker_max_delay;
+			}
+			break;
+		default:
+			break;
+	}
+	return NULL;
 }
 
 Config::section_t Config::parseSection(const char* key) {
-  if (strncasecmp(key,"wireless",29)==0) {
-    return sec_wireless;
-  } else if (strncasecmp(key,"vision",29)==0) {
-    return sec_vision;
-  } else if (strncasecmp(key,"main",29)==0) {
-    return sec_main;
-  } else if (strncasecmp(key,"behaviors",29)==0) {
-    return sec_behaviors;
-  } else if (strncasecmp(key,"controller",29)==0) {
-    return sec_controller;
-  } else if (strncasecmp(key,"motion",29)==0) {
-    return sec_motion;
-  } else if (strncasecmp(key,"sound",29)==0) {
-    return sec_sound;
-  } else {
-    return sec_invalid;
-  }
+	if (strncasecmp(key,"wireless",29)==0) {
+		return sec_wireless;
+	} else if (strncasecmp(key,"vision",29)==0) {
+		return sec_vision;
+	} else if (strncasecmp(key,"main",29)==0) {
+		return sec_main;
+	} else if (strncasecmp(key,"behaviors",29)==0) {
+		return sec_behaviors;
+	} else if (strncasecmp(key,"controller",29)==0) {
+		return sec_controller;
+	} else if (strncasecmp(key,"motion",29)==0) {
+		return sec_motion;
+	} else if (strncasecmp(key,"sound",29)==0) {
+		return sec_sound;
+	} else {
+		return sec_invalid;
+	}
 }
 
-void Config::readConfig(const char* filename) {
-  FILE* fp = fopen(filename, "r");
-  char buf[80], key[30], value[50];
-  section_t section=sec_invalid;
-  if (fp==NULL) return;
-
+void Config::readConfig(const std::string& filename) {
+	FILE* fp = fopen(filename.c_str(), "r");
+	char buf[80], key[30], value[50];
+	section_t section=sec_invalid;
+	if (fp==NULL) return;
+	
 	bool ignoring=false;
 	std::vector<std::string> curmodel;
 #ifdef PLATFORM_APERIOS
@@ -430,16 +525,16 @@
 #    warning "TGT_2xx is not specific for simulation purposes - defaulting to ERS210"
 	char rdStr[]="ERS-210";
 #  else
-#    warning "TGT_<model> undefined - defaulting to ERS210"
-	char rdStr[]="ERS-210";
+#    warning "TGT_<model> undefined - defaulting to ERS7"
+	char rdStr[]="ERS-7";
 #  endif
 #endif
-
-
+	
+	
 	unsigned int lineno=0;
-  while (fscanf(fp,"%79[^\n]\n", buf)!=EOF) {
+	while (fscanf(fp,"%79[^\n]\n", buf)!=EOF) {
 		lineno++;
-    if (sscanf(buf,"<%29[^>]>",key)>0) {
+		if (sscanf(buf,"<%29[^>]>",key)>0) {
 			if(key[0]=='/') {
 				if(curmodel.size()==0) {
 					printf("WARNING: not in a model specific section, line %d\n",lineno);
@@ -466,8 +561,8 @@
 						ignoring=true;
 						break;
 					}
-				//printf("ignoring==%d\n",ignoring);
-				
+						//printf("ignoring==%d\n",ignoring);
+						
 			} else {
 				curmodel.push_back(key);
 				//printf("entering section %s\n",curmodel.back().c_str());
@@ -483,8 +578,8 @@
 				setValue(section, key, value);    
 			}
 		}
-  }
-  fclose(fp);
+	}
+		fclose(fp);
 }
 
 bool Config::matchNoCase(const std::string& model, const std::string& pattern) {
@@ -540,9 +635,9 @@
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.42 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.49 $
  * $State: Exp $
- * $Date: 2005/01/20 23:18:43 $
+ * $Date: 2005/08/05 19:44:22 $
  */
 
diff -urdN ../Tekkotsu_2.3/Shared/Config.h ./Shared/Config.h
--- ../Tekkotsu_2.3/Shared/Config.h	Thu Jan 20 18:18:43 2005
+++ ./Shared/Config.h	Sun Aug  7 00:11:03 2005
@@ -5,19 +5,30 @@
 #include <vector>
 #include <string>
 #include "RobotInfo.h"
+extern "C" {
 #include <jpeglib.h>
+}
 
 //!provides global access to system configuration information
 class Config {
  public:
 	//!constructor
-	Config(const char* filename)
-		: wireless(), vision(), main(), behaviors(), controller(), motion(),
-		sound()
-		{ readConfig(filename); }
+	Config()
+		: wireless(), vision(), main(), behaviors(), controller(), motion(this),
+		sound(this), fsRoot()
+		{setFileSystemRoot("");}
+	//!constructor
+	Config(const std::string& filename)
+		: wireless(), vision(), main(), behaviors(), controller(), motion(this),
+		sound(this), fsRoot()
+		{ setFileSystemRoot(""); readConfig(filename); }
 	//!destructor
 	~Config() {}
 
+	void setFileSystemRoot(const std::string& fsr); //!< sets #fsRoot
+	const std::string& getFileSystemRoot() const { return fsRoot; } //!< returns #fsRoot
+	std::string portPath(const std::string& path) const; //!< returns a portable version of @a path which should be usable on either the simulator or the robot
+	
 	//!section IDs
 	enum section_t {
 		sec_wireless=0,  //!< denotes wireless section of config file
@@ -43,18 +54,22 @@
 		int gain;             //!< gain
 		int shutter_speed;    //!< shutter speed
 		int resolution;       //!< resolution
-		float horizFOV;       //!< horizontal field of view of camera, in radians
-		float vertFOV;        //!< vertical field of view of camera, in radians
-		float focal_length;   //!< focal length of the camera (mm)
 		std::vector<std::string> thresh;      //!< thresholds
 		char colors[50];      //!< colors
 		int rawcam_port;      //!< port to send raw frames on
 		int rawcam_transport; //!< transport protocol: 0 for udp, 1 for tcp
+		unsigned int rawcam_interval;  //!< interval between images: 0 for fast-as-possible, 100 for 10 FPS, 200 for 5 FPS, etc.
 		int rle_port;         //!< port to send RLE frames on
 		int rle_transport;    //!< transport protocol: 0 for udp, 1 for tcp
+		unsigned int rle_interval;     //!< interval between images: 0 for fast-as-possible, 100 for 10 FPS, 200 for 5 FPS, etc.
+		int region_port;      //!< port to send Region information on
+		int region_transport; //!< transport protocol: 0 for udp, 1 for tcp
 		int obj_port;         //!< port to send object info on
 		bool restore_image;   //!< if true, replaces pixels holding image info with actual image pixels (as much as possible anyway)
 		J_DCT_METHOD jpeg_dct_method;  //!< pick between dct methods for jpeg compression
+		float aspectRatio;    //!< ratio of width to height (x_res/y_res); this is *not* read from configuration file, but set from most recent camera image (or RobotInfo namespace values if no camera image has been received)
+		float x_range;        //!< range of values for the x axis when using generalized coordinates; this is *not* read from configuration file, but set from most recent camera image (or RobotInfo namespace values if no camera image has been received)
+		float y_range;        //!< range of values for the x axis when using generalized coordinates; this is *not* read from configuration file, but set from most recent camera image (or RobotInfo namespace values if no camera image has been received)
 
 		//! type of information to send, stored in Config::vision_config::rawcam_encoding
 		enum encoding_t {
@@ -70,25 +85,51 @@
 			COMPRESS_JPEG, //!< JPEG compression
 			COMPRESS_RLE   //!< RLE compression
 		};
-    compression_t rawcam_compression;//!< holds whether to send jpeg compression
+		compression_t rawcam_compression;//!< holds whether to send jpeg compression
 
-    int rawcam_compress_quality;//!< 0-100, compression quality (currently only used by jpeg)
-    int rawcam_y_skip;     //!< resolution level to transmit y channel at
-    int rawcam_uv_skip;    //!< resolution level to transmit uv channel at (ignored for jpeg compression)
-    int rlecam_skip;       //!< resolution level to transmit segmented images at
-    int rlecam_channel;    //!< channel of RLEGenerator to send
+		int rawcam_compress_quality;//!< 0-100, compression quality (currently only used by jpeg)
+		int rawcam_y_skip;     //!< resolution level to transmit y channel at
+		int rawcam_uv_skip;    //!< resolution level to transmit uv channel at
+		int rlecam_skip;       //!< resolution level to transmit segmented images at
+		int rlecam_channel;    //!< channel of RLEGenerator to send
 		compression_t rlecam_compression; //!< what compression to use on the segmented image
+    int regioncam_skip;    //!< resolution level to transmit segmented images at 
 
-		//!provides a ray from camera through pixel in image
-		/*! Hopefully we'll eventually upgrade this to account for lens distortion
+		//!These values represent a "Plumb Bob" model introduced by Brown in 1966
+		/*!Lens Distortion for Close-Range Photogrammetry -  D.C. Brown, Photometric Engineering, pages 855-866, Vol. 37, No. 8, 1971.
+		 * 
+		 * Can be computated by 'Camera Calibration Toolbox for Matlab', by Jean-Yves Bouguet:
+		 * http://www.vision.caltech.edu/bouguetj/calib_doc/ */
+		//!@name Intrinsic Parameters
+		float focal_len_x; //!< focal length of camera, in pixels, K11
+		float focal_len_y; //!< focal length of camera, in pixels, K22
+		float principle_point_x; //!< center of optical projection, K13
+		float principle_point_y; //!< center of optical projection, K23
+		float skew; //!< CCD skew, K12 = skew*focal_len_x
+		float kc1_r2; //!< r-squared radial distortion
+		float kc2_r4; //!< r to the 4 radial distortion
+		float kc5_r6; //!< r to the 6 radial distortion
+		float kc3_tan1; //!< first tangential correction term
+		float kc4_tan2; //!< second tangential correctiont term
+		unsigned int calibration_res_x; // x resolution of images used during calibration
+		unsigned int calibration_res_y; // y resolution of images used during calibration
+
+		//!provides a ray from camera through pixel in image; where possible, use computePixel for better accuracy (i.e. try to always move from world to camera instead of the other way around)
+		/*! We can't undo some terms of the distortion model -- this is an estimate.
 		 *  @param[in] x x position in range [-1,1]
 		 *  @param[in] y y position in range [-1,1]
 		 *  @param[out] r_x x value of the ray
 		 *  @param[out] r_y y value of the ray
 		 *  @param[out] r_z z value of the ray (always 1) */
 		void computeRay(float x, float y, float& r_x, float& r_y, float& r_z) {
-			r_x=x*tan(horizFOV/2);
-			r_y=y*tan(vertFOV/2);
+			x=(x+1)*calibration_res_x/2;
+			y=(y+1)*calibration_res_y/2;
+			float yd=(y-principle_point_y)/focal_len_y;
+			float xd=(x-principle_point_x)/focal_len_x-skew*yd;
+			float r2=xd*xd+yd*yd; //estimate of original
+			float radial=(1 + kc1_r2*r2 + kc2_r4*r2*r2 + kc5_r6*r2*r2*r2);
+			r_x=(xd - 2*kc3_tan1*x*y - kc4_tan2*(r2+2*x*x))/radial; //estimating tangential component
+			r_y=(yd - kc3_tan1*(r2+2*y*y) - 2*kc4_tan2*x*y)/radial; //estimating tangential component
 			r_z=1;
 		}
       
@@ -100,16 +141,42 @@
 		 *  @param[out] x x position in range [-1,1]
 		 *  @param[out] y y position in range [-1,1] */
 		void computePixel(float r_x, float r_y, float r_z, float& x, float& y) {
-			x=r_x/(r_z*tan(horizFOV/2));
-			y=r_y/(r_z*tan(vertFOV/2));
+			if(r_z==0) {
+				x=y=0;
+				return;
+			}
+			r_x/=r_z;
+			r_y/=r_z;
+			float r2 = r_x*r_x + r_y*r_y; //'r2' for 'radius squared', not 'ray number 2'
+			float radial=(1 + kc1_r2*r2 + kc2_r4*r2*r2 + kc5_r6*r2*r2*r2);
+			float xd = radial*r_x + 2*kc3_tan1*r_x*r_y + kc4_tan2*(r2+2*r_x*r_x);
+			float yd = radial*r_y + kc3_tan1*(r2+2*r_y*r_y) + 2*kc4_tan2*r_x*r_y;
+			x=focal_len_x*(xd+skew*yd)+principle_point_x;
+			y=focal_len_y*yd+principle_point_y;
+			x=2*x/calibration_res_x-1;
+			y=2*y/calibration_res_y-1;
 		}
-      
+		//@}
+		
 		//!constructor
-		vision_config() : white_balance(3), gain(2), shutter_speed(2), resolution(2), horizFOV(0), vertFOV(0), focal_length(0), thresh(), colors(), rawcam_port(0), rawcam_transport(0), rle_port(0), rle_transport(0), obj_port(0), restore_image(true), jpeg_dct_method(JDCT_IFAST), rawcam_encoding(ENCODE_COLOR), rawcam_channel(0), rawcam_compression(COMPRESS_NONE), rawcam_compress_quality(75), rawcam_y_skip(0), rawcam_uv_skip(0), rlecam_skip(1), rlecam_channel(0), rlecam_compression(COMPRESS_RLE) {}
+		vision_config()
+			: white_balance(3), gain(2), shutter_speed(2), resolution(2),
+				thresh(), colors(), rawcam_port(10011), rawcam_transport(0), rawcam_interval(0),
+				rle_port(10012), rle_transport(0), rle_interval(0), region_port(0), region_transport(0), obj_port(0), restore_image(true), 
+				jpeg_dct_method(JDCT_IFAST), aspectRatio(CameraResolutionX/(float)CameraResolutionY),
+				x_range(aspectRatio>1?1:aspectRatio), y_range(aspectRatio>1?1/aspectRatio:1), 
+				rawcam_encoding(ENCODE_COLOR), rawcam_channel(0),
+				rawcam_compression(COMPRESS_NONE), rawcam_compress_quality(75), rawcam_y_skip(0),
+				rawcam_uv_skip(0), rlecam_skip(1), rlecam_channel(0), rlecam_compression(COMPRESS_RLE), regioncam_skip(1),
+				focal_len_x(CameraResolutionX),focal_len_y(CameraResolutionX),principle_point_x(CameraResolutionX/2),
+				principle_point_y(CameraResolutionY/2),skew(0),kc1_r2(0),kc2_r4(0),kc5_r6(0),kc3_tan1(0),kc4_tan2(0),
+				calibration_res_x(CameraResolutionX), calibration_res_y(CameraResolutionY)
+		{}
 	} vision;
 	
 	//!core functionality information
 	struct main_config {
+		bool seed_rng;     //!< if true, will call srand with timestamp data, mangled by current sensor data
 		int console_port;  //!< port to send/receive "console" information on (separate from system console)
 		int stderr_port;   //!< port to send error information to
 		int error_level;   //!< controls amount of info to error port
@@ -120,16 +187,17 @@
 		int headControl_port;	   //!< port for receiving head commands
 		int walkControl_port;	   //!< port for receiving walk commands
 		int estopControl_port;	   //!< port for receiving walk commands
-    int aibo3d_port;   //!< port for send/receive of joint positions from Aibo 3D GUI
-    int wmmonitor_port; //!< port for monitoring Watchable Memory
+		int stewart_port;  //!< port for running a stewart platform style of control
+		int aibo3d_port;   //!< port for send/receive of joint positions from Aibo 3D GUI
+		int wmmonitor_port; //!< port for monitoring Watchable Memory
 		bool use_VT100;    //!< if true, enables VT100 console codes (currently only in Controller menus - 1.3)
-
+		unsigned int worldState_interval; //!< time (in milliseconds) to wait between sending WorldState updates over wireless
 		//!constructor
 		main_config()
-			: console_port(0), stderr_port(0), error_level(0), debug_level(0),
-				verbose_level(0),wsjoints_port(0),wspids_port(0),headControl_port(0),
-				walkControl_port(0),estopControl_port(0),aibo3d_port(0),
-        wmmonitor_port(0), use_VT100(true)
+			: seed_rng(true), console_port(10001), stderr_port(10002), error_level(0), debug_level(0),
+				verbose_level(0),wsjoints_port(10031),wspids_port(10032),headControl_port(10052),
+				walkControl_port(10050),estopControl_port(10053),stewart_port(10055),aibo3d_port(10051),
+				wmmonitor_port(10061), use_VT100(true), worldState_interval(0)
 		{ }
 	} main;
 
@@ -151,13 +219,14 @@
 		char error_snd[50]; //!< sound file to use to signal errors
 
 		//!constructor
-		controller_config() : gui_port(0) {
+		controller_config() : gui_port(10020) {
 			select_snd[0]=next_snd[0]=prev_snd[0]=read_snd[0]=cancel_snd[0]=error_snd[0]='\0';
 		}
 	} controller;
     
 	//!motion information
 	struct motion_config {
+		Config* thisconfig;  //!<pointer back to the containing config object
 		std::string root;       //!< path on memory stick to "motion" files - for instance, position (.pos) and motion sequence (.mot)
 		std::string walk;       //!< the walk parameter file to load by default for new WalkMC's
 		std::string kinematics;  //!< the kinematics description file to load
@@ -175,26 +244,30 @@
 		//!returns an absolute path if @a is relative (to root), otherwise just @a name
 		std::string makePath(const std::string& name) { 
 			if(name[0]=='/')
-				return name;
+				return thisconfig->portPath(name);
 			if(root[root.size()-1]=='/')
-				return root+name;
+				return thisconfig->portPath(root+name);
 			else
-				return root+"/"+name;
+				return thisconfig->portPath(root+"/"+name);
 		}
 
 		//!constructor
-		motion_config()
-			: root(), walk(), kinematics(), kinematic_chains(), max_head_tilt_speed(0),
-				max_head_pan_speed(0), max_head_roll_speed(0), inf_walk_accel(false), console_port(0), stderr_port(0)
+		motion_config(Config* c)
+			: thisconfig(c), root(), walk(), kinematics(), kinematic_chains(), max_head_tilt_speed(0),
+				max_head_pan_speed(0), max_head_roll_speed(0), inf_walk_accel(false), console_port(10003), stderr_port(10004)
 		{
 			estop_on_snd[0]=estop_off_snd[0]='\0';
 			for(unsigned int i=0; i<NumPIDJoints; i++)
 				calibration[i]=1;
 		}
+	private:
+		motion_config(const motion_config&); //!< don't call
+		motion_config& operator=(const motion_config&); //!< don't call
 	} motion;
 
 	//!sound information
 	struct sound_config {
+		Config* thisconfig;  //!<pointer back to the containing config object
 		std::string root;         //!< path to sound clips
 		unsigned int volume;      //!< volume in decibels - the value is interpreted as a signed short, where 0 is full volume, 0x8000 is mute
 		unsigned int sample_rate; //!< sample rate to send to system, currently only 8000 or 16000 supported
@@ -204,16 +277,16 @@
 		//!returns an absolute path if @a is relative (to root), otherwise just @a name
 		std::string makePath(const std::string& name) { 
 			if(name[0]=='/')
-				return name;
+				return thisconfig->portPath(name);
 			if(root[root.size()-1]=='/')
-				return root+name;
+				return thisconfig->portPath(root+name);
 			else
-				return root+"/"+name;
+				return thisconfig->portPath(root+"/"+name);
 		}
 		
 		//! audio streaming configuration
 		struct streaming_config {
-		  unsigned int mic_port;        //!< port for streaming microphone samples
+			unsigned int mic_port;        //!< port for streaming microphone samples
 			unsigned int mic_sample_rate; //!< sample rate from the microphone
 			unsigned int mic_sample_bits; //!< sample bit depth from the microphone (either 8 or 16)
 			bool mic_stereo; //!< whether to stream stereo or mono from the microphone
@@ -223,22 +296,25 @@
 			unsigned int speaker_max_delay; //!< maximum delay (ms) during playback
 
 			//! constructor
-			streaming_config() : mic_port(0), mic_sample_rate(16000),
+			streaming_config() : mic_port(10070), mic_sample_rate(16000),
 			mic_sample_bits(16), mic_stereo(true),
-			speaker_port(0), speaker_frame_length(64),
+			speaker_port(10071), speaker_frame_length(64),
 			speaker_max_delay(1000) {}
 		} streaming;
 
 		//!constructor
-		sound_config() : root(), volume(0xF600), sample_rate(0), sample_bits(0), preload(), streaming() {}
+		sound_config(Config* c) : thisconfig(c), root(), volume(0xF600), sample_rate(0), sample_bits(0), preload(), streaming() {}
+	private:
+		sound_config(const sound_config&); //!< don't call
+		sound_config& operator=(const sound_config&); //!< don't call
 	} sound;
 
 	//! call this function when it's time to read the configuration file
-	void readConfig(const char* filename);
+	void readConfig(const std::string& filename);
 	//! returns the section structure corresponding to the section name given
-  section_t parseSection(const char* key);
+	section_t parseSection(const char* key);
 	//! pass the section, item name string, item value string - sets the value and returns pointer to the item changed
-  void* setValue(section_t section, const char *key, const char *value, bool updated=false);
+	void* setValue(section_t section, const char *key, const char *value, bool updated=false);
 
 
 protected:
@@ -247,6 +323,10 @@
 
 	//! returns bool value corresponding to a @a value of "t", "f", "true", "false", "y", "n", "yes", "no", or zero/nonzero number
 	static bool extractBool(const char* value);
+	
+	//! a prefix representing the file system root, usually indicating the robot's storage root.
+	/*! When running in the simulator, this is used to pretend that a subdirectory in the project folder (e.g. 'ms') is the root file system */
+	std::string fsRoot;
 };
 
 //!allows global access to current settings
@@ -257,10 +337,10 @@
  * @author alokl (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.41 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.49 $
  * $State: Exp $
- * $Date: 2005/01/20 23:18:43 $
+ * $Date: 2005/08/07 04:11:03 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/ERS210Info.h ./Shared/ERS210Info.h
--- ../Tekkotsu_2.3/Shared/ERS210Info.h	Tue Jan 11 18:30:43 2005
+++ ./Shared/ERS210Info.h	Wed Jun  1 01:47:48 2005
@@ -52,6 +52,12 @@
 	const unsigned NumOutputs     = NumPIDJoints + NumBinJoints + NumLEDs; //!< the total number of outputs
 	const unsigned NumReferenceFrames = NumOutputs + 1 + NumLegs + 1 + 1; //!< for the base, paw, camera, and IR sensor reference frames
 
+	const float CameraHorizFOV=57.6/180*M_PI; //!< horizontal field of view (radians)
+	const float CameraVertFOV=47.8/180*M_PI; //!< vertical field of view (radians)
+	const float CameraFOV=CameraHorizFOV; //!< should be set to maximum of #CameraHorizFOV or #CameraVertFOV
+	const unsigned int CameraResolutionX=176; //!< the number of pixels available in the 'full' layer
+	const unsigned int CameraResolutionY=144; //!< the number of pixels available in the 'full' layer
+
 	const bool IsFastOutput[NumOutputs] = { true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,false,false }; //!< true for joints which can be updated every 32 ms (all but the ears)
 	//! we need this so you can tell programmatically which joints are "real" and which are "fake" in ERS-2xx target mode
 	const bool IsRealERS210[NumOutputs] = { true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true };
@@ -133,7 +139,7 @@
 	const LEDBitMask_t HeadLEDMask = BotLLEDMask|BotRLEDMask|MidLLEDMask|MidRLEDMask|TopLLEDMask|TopRLEDMask|TopBrLEDMask; //!< LEDs for face (all but tail)
 	const LEDBitMask_t BackLEDMask = 0; //!< 210 has no back LEDs
 	const LEDBitMask_t TailLEDMask = TlRedLEDMask|TlBluLEDMask; //!< LEDs on tail
-	const LEDBitMask_t AllLEDMask  = ~0; //!< selects all of the leds
+	const LEDBitMask_t AllLEDMask  = (LEDBitMask_t)~0; //!< selects all of the leds
 	//@}
 
 
@@ -479,10 +485,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.19 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.20 $
  * $State: Exp $
- * $Date: 2005/01/11 23:30:43 $
+ * $Date: 2005/06/01 05:47:48 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/ERS220Info.h ./Shared/ERS220Info.h
--- ../Tekkotsu_2.3/Shared/ERS220Info.h	Tue Jan 11 18:30:43 2005
+++ ./Shared/ERS220Info.h	Wed Jun  1 01:47:48 2005
@@ -55,6 +55,12 @@
 	const unsigned NumOutputs     = NumPIDJoints + NumBinJoints + NumLEDs; //!< the total number of outputs
 	const unsigned NumReferenceFrames = NumOutputs + 1 + NumLegs + 1 + 1; //!< for the base, paw, camera, and IR sensor reference frames
 
+	const float CameraHorizFOV=57.6/180*M_PI; //!< horizontal field of view (radians)
+	const float CameraVertFOV=47.8/180*M_PI; //!< vertical field of view (radians)
+	const float CameraFOV=CameraHorizFOV; //!< should be set to maximum of #CameraHorizFOV or #CameraVertFOV
+	const unsigned int CameraResolutionX=176; //!< the number of pixels available in the 'full' layer
+	const unsigned int CameraResolutionY=144; //!< the number of pixels available in the 'full' layer
+
 	const bool IsFastOutput[NumOutputs] = {
 		// for PID joints
 		true, true, true,
@@ -224,7 +230,7 @@
 	| TailCenterLEDMask
 	| TailRightLEDMask;  //!< LEDs for tail
  
-	const LEDBitMask_t AllLEDMask  = ~0; //!< selects all of the leds
+	const LEDBitMask_t AllLEDMask  = (LEDBitMask_t)~0; //!< selects all of the leds
 	//@}
 
 
@@ -583,10 +589,10 @@
  * @author Daishi MORI (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.20 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.21 $
  * $State: Exp $
- * $Date: 2005/01/11 23:30:43 $
+ * $Date: 2005/06/01 05:47:48 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/ERS2xxInfo.h ./Shared/ERS2xxInfo.h
--- ../Tekkotsu_2.3/Shared/ERS2xxInfo.h	Tue Jan 11 18:30:43 2005
+++ ./Shared/ERS2xxInfo.h	Wed Jun  1 01:47:49 2005
@@ -51,6 +51,12 @@
 	const unsigned NumOutputs     = NumPIDJoints + NumBinJoints + NumLEDs; //!< the total number of outputs
 	const unsigned NumReferenceFrames = NumOutputs + 1 + NumLegs + 1 + 1; //!< for the base, paw, camera, and IR sensor reference frames
 
+	const float CameraHorizFOV=57.6/180*M_PI; //!< horizontal field of view (radians)
+	const float CameraVertFOV=47.8/180*M_PI; //!< vertical field of view (radians)
+	const float CameraFOV=CameraHorizFOV; //!< should be set to maximum of #CameraHorizFOV or #CameraVertFOV
+	const unsigned int CameraResolutionX=176; //!< the number of pixels available in the 'full' layer
+	const unsigned int CameraResolutionY=144; //!< the number of pixels available in the 'full' layer
+
 	const bool IsFastOutput[NumOutputs] = {
 		// for PID joints
 		true, true, true, //legs
@@ -259,7 +265,7 @@
 	| TlRedLEDMask
 	| TlBluLEDMask;  //!< LEDs for tail
  
-	const LEDBitMask_t AllLEDMask  = ~0; //!< selects all of the leds
+	const LEDBitMask_t AllLEDMask  = (LEDBitMask_t)~0; //!< selects all of the leds
 	//@}
 
 
@@ -625,10 +631,10 @@
  * @author Daishi MORI (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2005/01/11 23:30:43 $
+ * $Date: 2005/06/01 05:47:49 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/ERS7Info.h ./Shared/ERS7Info.h
--- ../Tekkotsu_2.3/Shared/ERS7Info.h	Tue Jan 11 18:30:43 2005
+++ ./Shared/ERS7Info.h	Wed Jun  1 01:47:49 2005
@@ -45,7 +45,13 @@
 	const unsigned NumOutputs     = NumPIDJoints + NumBinJoints + NumLEDs; //!< the total number of outputs
 	const unsigned NumReferenceFrames = NumOutputs + 1 + NumLegs + 1 + 3; //!< for the base, paws (NumLegs), camera, and IR sensors (3) reference frames
 
-	//! true for joints which can be updated every 32 ms (all but the ears)
+	const float CameraHorizFOV=56.9/180*M_PI; //!< horizontal field of view (radians)
+	const float CameraVertFOV=45.2/180*M_PI; //!< vertical field of view (radians)
+	const float CameraFOV=CameraHorizFOV; //!< should be set to maximum of #CameraHorizFOV or #CameraVertFOV
+	const unsigned int CameraResolutionX=208; //!< the number of pixels available in the 'full' layer
+	const unsigned int CameraResolutionY=160; //!< the number of pixels available in the 'full' layer
+
+	//! true for joints which can be updated every 32 ms (all ers-7 joints)
 	const bool IsFastOutput[NumOutputs] = {
 		true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true, //PID joints
 		true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true, //leds
@@ -154,11 +160,11 @@
 	const LEDBitMask_t TlRedLEDMask= 1<<(TlRedLEDOffset-LEDOffset); //!< red tail light
 	const LEDBitMask_t TlBluLEDMask= 1<<(TlBluLEDOffset-LEDOffset); //!< blue tail light
 
-	const LEDBitMask_t FaceLEDMask = (FaceLEDPanelMask<<0)|(FaceLEDPanelMask<<1)|(FaceLEDPanelMask<<2)|(FaceLEDPanelMask<<3)|(FaceLEDPanelMask<<4)|(FaceLEDPanelMask<<5)|(FaceLEDPanelMask<<6)|(FaceLEDPanelMask<<7)|(FaceLEDPanelMask<<8)|(FaceLEDPanelMask<<9)|(FaceLEDPanelMask<<10)|(FaceLEDPanelMask<<11)|(FaceLEDPanelMask<<12)|(FaceLEDPanelMask<<13); //!< LEDs for the face panel
-	const LEDBitMask_t HeadLEDMask = FaceLEDMask|HeadColorLEDMask|HeadWhiteLEDMask|ModeRedLEDMask|ModeGreenLEDMask|ModeBlueLEDMask|WirelessLEDMask; //!< LEDs for face (all but back lights)
-	const LEDBitMask_t BackLEDMask = FrBackColorLEDMask|FrBackWhiteLEDMask|MdBackColorLEDMask|MdBackWhiteLEDMask|RrBackColorLEDMask|RrBackWhiteLEDMask; //!< LEDS on the back
+	const LEDBitMask_t FaceLEDMask = (FaceLEDPanelMask<<0) | (FaceLEDPanelMask<<1) | (FaceLEDPanelMask<<2) | (FaceLEDPanelMask<<3) | (FaceLEDPanelMask<<4) | (FaceLEDPanelMask<<5) | (FaceLEDPanelMask<<6) | (FaceLEDPanelMask<<7) | (FaceLEDPanelMask<<8) | (FaceLEDPanelMask<<9) | (FaceLEDPanelMask<<10) | (FaceLEDPanelMask<<11) | (FaceLEDPanelMask<<12) | (FaceLEDPanelMask<<13); //!< LEDs for the face panel
+	const LEDBitMask_t HeadLEDMask = FaceLEDMask | HeadColorLEDMask | HeadWhiteLEDMask | ModeRedLEDMask | ModeGreenLEDMask | ModeBlueLEDMask | WirelessLEDMask; //!< LEDs for face (all but back lights)
+	const LEDBitMask_t BackLEDMask = FrBackColorLEDMask | FrBackWhiteLEDMask | MdBackColorLEDMask | MdBackWhiteLEDMask | RrBackColorLEDMask | RrBackWhiteLEDMask; //!< LEDS on the back
 	const LEDBitMask_t TailLEDMask = 0; //!< LEDs on tail (ERS-7 has none)
-	const LEDBitMask_t AllLEDMask  = ~0; //!< selects all of the leds
+	const LEDBitMask_t AllLEDMask  = (LEDBitMask_t)~0; //!< selects all of the leds
 	//@}
 
 
@@ -528,10 +534,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.23 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.25 $
  * $State: Exp $
- * $Date: 2005/01/11 23:30:43 $
+ * $Date: 2005/06/01 05:47:49 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/Factory.h ./Shared/Factory.h
--- ../Tekkotsu_2.3/Shared/Factory.h	Thu Oct 30 18:24:20 2003
+++ ./Shared/Factory.h	Mon Jul 25 23:11:20 2005
@@ -2,6 +2,13 @@
 #ifndef INCLUDED_Factory_h_
 #define INCLUDED_Factory_h_
 
+//! Base class for Factory templated subclasses
+class FactoryBase {
+public:
+	virtual ~FactoryBase() {} //!< destructor -- does nothing
+	virtual void* constructTemplate()=0; //!< return a new object from the Factory subclass
+};
+
 //! A lightweight class to override for constructing new objects (if you need to pass constructors parameters, etc.)
 /*! Say you don't want to construct your behavior at boot-up (if it's big and might not even be
  *  used) but your behavior needs special setup during creation (might be invoked
@@ -9,37 +16,42 @@
  *  your behavior is activated.\n
  *  The default is to simply call the default constructor */
 template<class B>
-class Factory {
+class Factory : public FactoryBase {
 public:
-	static B* construct() { return new B(); } //!< Just returns a new B
+	virtual B* construct() { return new B(); } //!< Just returns a new B
+	virtual void* constructTemplate() { return construct(); }
 };
 
 //! Uses template to specify a constant parameter to the constructor
 template<class B, class A1, A1 a1>
 class Factory1Arg : public Factory<B> {
 public:
-	static B* construct() { return new B(a1); } //!< Just returns a new B constructed with arguments @a a1
+	virtual B* construct() { return new B(a1); } //!< Just returns a new B constructed with arguments @a a1
+	virtual void* constructTemplate() { return construct(); }
 };
 
 //! Uses template to specify constant parameters to the constructor
 template<class B, class A1, A1 a1, class A2, A2 a2>
 class Factory2Arg : public Factory<B> {
 public:
-	static B* construct() { return new B(a1,a2); } //!< Just returns a new B constructed with arguments @a a1, @a a2
+	virtual B* construct() { return new B(a1,a2); } //!< Just returns a new B constructed with arguments @a a1, @a a2
+	virtual void* constructTemplate() { return construct(); }
 };
 
 //! Uses template to specify constant parameters to the constructor
 template<class B, class A1, A1 a1, class A2, A2 a2, class A3, A3 a3>
 class Factory3Arg : public Factory<B> {
 public:
-	static B* construct() { return new B(a1,a2,a3); } //!< Just returns a new B constructed with arguments @a a1 - @a a3
+	virtual B* construct() { return new B(a1,a2,a3); } //!< Just returns a new B constructed with arguments @a a1 - @a a3
+	virtual void* constructTemplate() { return construct(); }
 };
 
 //! Uses template to specify constant parameters to the constructor
 template<class B, class A1, A1 a1, class A2, A2 a2, class A3, A3 a3, class A4, A4 a4>
 class Factory4Arg : public Factory<B> {
 public:
-	static B* construct() { return new B(a1,a2,a3,a4); } //!< Just returns a new B constructed with arguments @a a1 - @a a4
+	virtual B* construct() { return new B(a1,a2,a3,a4); } //!< Just returns a new B constructed with arguments @a a1 - @a a4
+	virtual void* constructTemplate() { return construct(); }
 };
 
 /*! @file
@@ -47,10 +59,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
  * $State: Exp $
- * $Date: 2003/10/30 23:24:20 $
+ * $Date: 2005/07/26 03:11:20 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/ListMemBuf.h ./Shared/ListMemBuf.h
--- ../Tekkotsu_2.3/Shared/ListMemBuf.h	Tue Dec 21 15:29:14 2004
+++ ./Shared/ListMemBuf.h	Wed Dec 31 19:00:00 1969
@@ -1,343 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_ListMemBuf_h
-#define INCLUDED_ListMemBuf_h
-
-//! Provides some degree of dynamic allocation of a templated type from a buffer of set size.
-/*! Think of this as a self-contained mini-malloc...
-	  
-    This is handy for classes which inhabit a shared memory region, where
-    it's a bad idea to have pointers to other memory.  By instantiating one
-    of these in your class, you can allocate space internally for up to
-    MAX objects of type T_t.  ListMemBuf will worry about keeping track
-    of which ones are in use or are free.
-
-    Each time you request a entry to be created, the destructor will be
-    called followed by the the defaul constructor before it is given to
-    you, so the fields should be reliably 'fresh', not what was in the
-    entry last time it was used.
-*/
-template < class T_t, unsigned int MAX, class idx_t=unsigned short >
-class ListMemBuf {
-	public:
-	
-	ListMemBuf(); //!<constructor
-	
-	//!Allows outside access to storage type
-	typedef T_t T;
-	//!Allows outside access to number of entries
-	static const unsigned int MAX_ENTRIES = MAX;
-	//!Allows outside access to index type
-	typedef idx_t index_t;
-	
-	static index_t getMaxCapacity() { return MAX_ENTRIES; } //!<returns the maximum number of objects which can be used at any given time
-	index_t size() const { return cursize; } //!<returns the current number of objects in use
-	index_t countf() const; //!< for debugging, should equal size
-	index_t countb() const; //!< for debugging, should equal size
-	bool empty() const { return cursize==0; } //!<returns true if no objects are in use
-
-	inline T& operator[](unsigned int x) { return (entries[x].data); } //!<allows direct access to elements - be careful, can access 'free' elements this way
-	inline const T& operator[](unsigned int x) const { return (entries[x].data); } //!<allows direct access to elements - be careful, can access 'free' elements this way
-
-	inline index_t begin() const { return activeBegin; } //!<returns index of first used entry
-	T& front() { return (entries[activeBegin].data); } //!< returns reference to first used entry
-	const T& front() const { return (entries[activeBegin].data); } //!< returns const reference to first used entry
-
-	inline index_t end() const { return (index_t)-1; } //!<returns the one-past-end index
-	T& back() { return (entries[activeBack].data); } //!<returns reference to last used entry
-	const T& back() const { return (entries[activeBack].data); } //!<returns const reference to last used entry
-
-	index_t new_front(); //!<pushes a 'blank' entry on the front of the used list
-	index_t push_front(const T& data) { index_t tmp=new_front(); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<pushes an entry on the front of the used chain and assigns @a data to it
-	void pop_front(); //!<pops the front of the used chain
-	void pop_front(T& ret) { ret=front(); pop_front(); } //!<pops the front of the chain into @a ret
-
-	index_t new_back(); //!<pushes a 'blank' entry on the back of the used list
-	index_t push_back(const T& data) { index_t tmp=new_back(); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<pushes an entry on the back of the used chain and assigns @a data to it
-	void pop_back(); //!<pops the last of the used chain
-	void pop_back(T& ret) { ret=back(); pop_back(); } //!<pops the last of the used chain into @a ret
-
-	index_t new_before(index_t x); //!<inserts a 'blank' entry before element @a x in the used chain
-	index_t push_before(index_t x, const T& data) { index_t tmp=new_before(x); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<inserts a 'blank' entry before element @a x in the used chain and assigns @a data to it
-
-	index_t new_after(index_t x) { return new_before(next(x)); } //!<inserts a 'blank' entry after element @a x in the used chain
-	index_t push_after(index_t x, const T& data) { index_t tmp=new_after(x); if(tmp!=end()) operator[](tmp)=data; return tmp; } //!<inserts a 'blank' entry after element @a x in the used chain and assigns @a data to it
-
-	void erase(index_t x); //!<removes element @a x from the used chain
-	void clear(); //!<frees all used entries
-
-	void swap(index_t a, index_t b); //!<swaps the two entries' position in the list
-
-	index_t next(index_t x) const { return x==end()?activeBegin:entries[x].next; } //!< returns the next used element following @a x
-	index_t prev(index_t x) const { return x==end()?activeBack:entries[x].prev; } //!< returns the preceeding used element following @a x
- 
-	protected:
-	index_t pop_free(); //!<removes an element from the front of the free list, returns its index
-	void push_free(index_t x); //!<pushes @a x onto the back of the free list
-	
-	//!holds data about an entry in the free/used lists
-	struct entry_t {
-		//!constructor
-		entry_t() : data(), next(static_cast<index_t>(-1)), prev(static_cast<index_t>(-1)) {}
-		T data; //!<The data being stored, not actually an instantiation of T, but big enough to hold it.
-		index_t next; //!<The next element in the used or free chain
-		index_t prev; //!<The previous element in the used chain, invalid if in the free chain
-	};
-	entry_t entries[MAX_ENTRIES]; //!<the main block of data
-	index_t activeBegin; //!<beginning of used chain
-	index_t activeBack; //!<end of used chain
-	index_t freeBegin; //!<beginning of free chain
-	index_t freeBack; //!<end of free chain
-	index_t cursize; //!< current number of used elements
-};
-
-template < class T, unsigned int MAX, class index_t >
-ListMemBuf<T,MAX,index_t>::ListMemBuf()
-	: activeBegin(end()), activeBack(end()), freeBegin(end()), freeBack(end()), cursize(0)
-{
-	for(push_free(0); freeBack<MAX_ENTRIES-1; push_free(freeBack+1)) {}
-	cursize=0; //important to do this - push_free() above will subtract one each time otherwise
-}
-
-template < class T, unsigned int MAX, class index_t>
-index_t
-ListMemBuf<T,MAX,index_t>::countf() const {
-	int x=0;
-	for(index_t c=begin(); c!=end(); c=next(c))
-		x++;
-	return x;
-}
-
-template < class T, unsigned int MAX, class index_t>
-index_t
-ListMemBuf<T,MAX,index_t>::countb() const {
-	int x=0;
-	for(index_t c=end(); c!=begin(); c=prev(c))
-		x++;
-	return x;
-}
-
-template < class T, unsigned int MAX, class index_t >
-index_t
-ListMemBuf<T,MAX,index_t>::new_front() {
-	index_t tmp = pop_free();
-	if(tmp==end())
-		return end();
-	entries[tmp].prev=end();
-	entries[tmp].next=activeBegin;
-	if(activeBegin!=end())
-		entries[activeBegin].prev=tmp;
-	else
-		activeBack=tmp;
-	activeBegin=tmp;
-	return tmp;
-}
-
-template < class T, unsigned int MAX, class index_t >
-index_t
-ListMemBuf<T,MAX,index_t>::new_back() {
-	index_t tmp = pop_free();
-	if(tmp==end())
-		return end();
-	entries[tmp].prev=activeBack;
-	entries[tmp].next=end();
-	if(activeBack!=end())
-		entries[activeBack].next=tmp;
-	else
-		activeBegin=tmp;
-	activeBack=tmp;
-	return tmp;
-}
-
-template < class T, unsigned int MAX, class index_t >
-index_t
-ListMemBuf<T,MAX,index_t>::new_before(index_t x) {
-	if(x==end())
-		return new_back();
-	if(entries[x].prev==end())
-		return new_front();
-	index_t tmp = pop_free();
-	if(tmp==end())
-		return end();
-	entries[tmp].next=x;
-	entries[tmp].prev=entries[x].prev;
-	entries[x].prev=tmp;
-	entries[ entries[tmp].prev ].next = tmp;
-	return tmp;
-}
-
-template < class T, unsigned int MAX, class index_t >
-void
-ListMemBuf<T,MAX,index_t>::pop_front() {
-	index_t tmp = activeBegin;
-	activeBegin = entries[activeBegin].next;
-	if(activeBegin==end())
-		activeBack=end();
-	else
-		entries[activeBegin].prev = end();
-	push_free(tmp);
-}
-
-template < class T, unsigned int MAX, class index_t >
-void
-ListMemBuf<T,MAX,index_t>::pop_back() {
-	index_t tmp = activeBack;
-	activeBack = entries[activeBack].prev;
-	if(activeBack==end())
-		activeBegin=end();
-	else
-		entries[activeBack].next = end();
-	push_free(tmp);
-}
-
-template < class T, unsigned int MAX, class index_t >
-void
-ListMemBuf<T,MAX,index_t>::erase(index_t x) {
-	if(x==activeBegin) {
-		pop_front();
-		return;
-	}
-	if(x==activeBack) {
-		pop_back();
-		return;
-	}
-	entries[ entries[x].next ].prev = entries[x].prev;
-	entries[ entries[x].prev ].next = entries[x].next;
-	push_free(x);
-}
-
-template < class T, unsigned int MAX, class index_t >
-void
-ListMemBuf<T,MAX,index_t>::clear() {
-	if(cursize!=0) {
-		if(freeBack==end())
-			freeBegin=activeBegin;
-		else
-			entries[freeBack].next=activeBegin;
-		freeBack=activeBack;
-		activeBegin=activeBack=end();
-	}
-	cursize=0;
-}
-
-template < class T, unsigned int MAX, class index_t >
-void
-ListMemBuf<T,MAX,index_t>::swap(index_t a, index_t b) {
-	if(a==b || a==end() || b==end())
-		return;
-	if(entries[a].prev==b) {
-		entries[a].prev=entries[b].prev;
-		entries[b].next=entries[a].next;
-		entries[a].next=b;
-		entries[b].prev=a;
-		if(entries[a].prev!=end())
-			entries[entries[a].prev].next=a;
-		else
-			activeBegin=a;
-		if(entries[b].next!=end())
-			entries[entries[b].next].prev=b;
-		else
-			activeBack=b;
-	} else if(entries[a].next==b) {
-		entries[a].next=entries[b].next;
-		entries[b].prev=entries[a].prev;
-		entries[a].prev=b;
-		entries[b].next=a;
-		if(entries[a].next!=end())
-			entries[entries[a].next].prev=a;
-		else
-			activeBack=a;
-		if(entries[b].prev!=end())
-			entries[entries[b].prev].next=b;
-		else
-			activeBegin=b;
-	} else {
-		index_t tmpp=entries[a].prev, tmpn=entries[a].next;
-		entries[a].prev=entries[b].prev;
-		entries[a].next=entries[b].next;
-		entries[b].prev=tmpp;
-		entries[b].next=tmpn;
-		if(entries[a].prev!=end())
-			entries[entries[a].prev].next=a;
-		else
-			activeBegin=a;
-		if(entries[a].next!=end())
-			entries[entries[a].next].prev=a;
-		else
-			activeBack=a;
-		if(entries[b].prev!=end())
-			entries[entries[b].prev].next=b;
-		else
-			activeBegin=b;
-		if(entries[b].next!=end())
-			entries[entries[b].next].prev=b;
-		else
-			activeBack=b;
-	}
-	/*
-	// Front Back => Front Back
-	//  a     b       b     a
-	//  a     -       b     -
-	//  b     a       a     b
-	//  b     -       a     -
-	//  -     a       -     b
-	//  -     b       -     a
-	if(activeBegin==a) {
-		activeBegin=b;
-		if(activeBack==b)
-			activeBack=a;
-	} else if(activeBegin==b) {
-		activeBegin=a;
-		if(activeBack==a)
-			activeBack=b;
-	} else {
-		if(activeBack==a)
-			activeBack=b;
-		else if(activeBack=b)
-			activeBack==a;
-	}
-	*/
-}
-
-
-/*! free list is a queue... pop front, push back - hopefully more robust with multi-threads
-    is purposely sloppy with unused links, a little faster*/
-template < class T, unsigned int MAX, class index_t >
-index_t
-ListMemBuf<T,MAX,index_t>::pop_free() {
-	if(freeBegin==end())
-		return end();
-	index_t tmp=freeBegin;
-	if(freeBegin==freeBack)
-		freeBegin=freeBack=end();
-	else
-		freeBegin=entries[freeBegin].next;
-	cursize++;
-	new (&entries[tmp].data) T;  //calls constructor so that the data is "fresh"
-	return tmp;
-}
-
-/*! @see pop_free() */
-template < class T, unsigned int MAX, class index_t >
-void
-ListMemBuf<T,MAX,index_t>::push_free(index_t x) {
-	if(freeBack==end())
-		freeBegin=x;
-	else
-		entries[freeBack].next=x;
-	freeBack=x;
-	cursize--;
-	operator[](x).~T(); //to match the constructor call in pop_free() (or the entry_t constructor during initialization)
-}
-
-/*! @file
- * @brief Defines ListMemBuf, which provides some degree of dynamic allocation of a templated type from a buffer of set size.
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
- * $State: Exp $
- * $Date: 2004/12/21 20:29:14 $
- */
- 
- #endif
diff -urdN ../Tekkotsu_2.3/Shared/LoadSave.cc ./Shared/LoadSave.cc
--- ../Tekkotsu_2.3/Shared/LoadSave.cc	Thu Mar 25 12:07:44 2004
+++ ./Shared/LoadSave.cc	Thu Mar 25 12:07:44 2004
@@ -161,7 +161,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Exp $
  * $Date: 2004/03/25 17:07:44 $
diff -urdN ../Tekkotsu_2.3/Shared/LoadSave.h ./Shared/LoadSave.h
--- ../Tekkotsu_2.3/Shared/LoadSave.h	Thu Apr  8 12:28:06 2004
+++ ./Shared/LoadSave.h	Sun Aug  7 00:11:04 2005
@@ -3,6 +3,32 @@
 #define INCLUDED_LoadSave_h
 
 #include <string>
+#include <sys/param.h>
+
+#ifndef LOADSAVE_SWAPBYTES
+
+#ifdef BYTE_ORDER
+#  if BYTE_ORDER == BIG_ENDIAN
+#    define LOADSAVE_SWAPBYTES 1
+#  elif BYTE_ORDER == LITTLE_ENDIAN
+#    define LOADSAVE_SWAPBYTES 0
+#  else
+#    warning unknown byte ordering for current platform, assuming no swap
+#    define LOADSAVE_SWAPBYTES 0
+#  endif
+#else
+//aperios distribution doesn't actually define BYTE_ORDER :(
+//just as well, since we're using that byte order anyway
+#  ifdef PLATFORM_APERIOS
+//!On PLATFORM_APERIOS, we avoid swapping bytes, since it's likely to be the most CPU constrained platform
+#    define LOADSAVE_SWAPBYTES 0
+#  else
+#    warning unknown byte ordering for current platform, assuming no swap
+#    define LOADSAVE_SWAPBYTES 0
+#  endif
+#endif
+
+#endif
 
 //! Intended as an interface to allow easy and uniform file operations
 /*!
@@ -227,10 +253,7 @@
 	inline static unsigned int encode(const LoadSave& x, FILE* f)                  { return x.SaveFileStream(f); }
 	inline static unsigned int decode(LoadSave& x, FILE* f)                        { return x.LoadFileStream(f); }
 	
-	//I don't know what compiler flag to use - this one is fake.
-	//Ideally, we should be able to detect host orientation
-	//and then pick a standard byte order.
-#ifdef LOADSAVE_SWAPBYTES
+#if LOADSAVE_SWAPBYTES
 	
 	inline static unsigned int encode(const double x, char buf[], unsigned int cap)          { if(cap<sizeof(x)) return 0; byteswap(*(double*)buf,x); return sizeof(x); }
 	inline static unsigned int decode(double& x, const char buf[], unsigned int cap)         { if(cap<sizeof(x)) return 0; byteswap(x,*(const double*)buf); return sizeof(x);}
@@ -345,14 +368,13 @@
 
 /*! @file
  * @brief Describes LoadSave, inherit from this to use a standard interface for loading and saving
- * @todo detect appropriate byte ordering for other platforms
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.13 $
  * $State: Exp $
- * $Date: 2004/04/08 16:28:06 $
+ * $Date: 2005/08/07 04:11:04 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/LockScope.h ./Shared/LockScope.h
--- ../Tekkotsu_2.3/Shared/LockScope.h	Thu Sep 25 11:31:53 2003
+++ ./Shared/LockScope.h	Wed Dec 31 19:00:00 1969
@@ -1,31 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_LockScope_h_
-#define INCLUDED_LockScope_h_
-
-#include "Shared/MutexLock.h"
-
-//! Locks a MutexLock until the LockScope goes out of scope
-/*! This can help prevent forgetting to do it if you function has multiple return points */
-template<unsigned int num_doors>
-class LockScope {
-public:
-	//!constructor, locks @a lock with @a id
-	LockScope(MutexLock<num_doors>& lock, int id) : l(lock) {l.lock(id);}
-	//!destructor, releases lock received in constructor
-	~LockScope() { l.release(); }
-protected:
-	MutexLock<num_doors>& l; //!< the lock
-};
-
-/*! @file
- * @brief Defines LockScope, which locks a MutexLock until the LockScope goes out of scope
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/09/25 15:31:53 $
- */
-
-#endif
diff -urdN ../Tekkotsu_2.3/Shared/MutexLock.h ./Shared/MutexLock.h
--- ../Tekkotsu_2.3/Shared/MutexLock.h	Thu Feb 12 12:48:59 2004
+++ ./Shared/MutexLock.h	Wed Dec 31 19:00:00 1969
@@ -1,269 +0,0 @@
-//-*-c++-*-
-#ifndef __MUTEX_LOCK_ET__
-#define __MUTEX_LOCK_ET__
-
-#include "debuget.h"
-#include <iostream>
-
-//#define MUTEX_LOCK_ET_USE_SPINCOUNT
-
-//! A software only mutual exclusion lock.
-/*! Use this to prevent more than one process from accessing a data structure
- *  at the same time (which often leads to unpredictable and unexpected results)
- *
- *  The template parameter specifies the maximum number of different processes
- *  which need to be protected.  This needs to be allocated ahead of time, as
- *  there doesn't seem to be a way to dynamically scale as needed without
- *  risking possible errors if two processes are both trying to set up at the
- *  same time.  Also, by using a template parameter, all data structures are
- *  contained within the class's memory allocation, so no pointers are involved.
- *
- *  Locks in this class can be recursive or non-recursive, depending
- *  whether you call release() or unlock().  If you lock 5 times, then
- *  you should call release() 5 times as well before it will be
- *  unlocked.  However, if you lock 5 times, just one call to unlock()
- *  will undo all 5 levels of locking.
- *
- *  Just remember, release() releases one level.  But unlock() completely unlocks.
- *
- *  Note that there is no check that the process doing the unlocking is the one
- *  that actually has the lock.  Be careful about this.
- *
- *  @warning Doing mutual exclusion in software is tricky business, be careful about any
- *  modifications you make!
- *
- * Implements a first-come-first-served Mutex as laid out on page 11 of: \n
- * "A First Come First Served Mutal Exclusion Algorithm with Small Communication Variables" \n
- * Edward A. Lycklama, Vassos Hadzilacos - Aug. 1991
-*/
-template<unsigned int num_doors>
-class MutexLock {
- public:
-	static const unsigned int NO_OWNER=-1U; //!< marks as unlocked
-
-	//! constructor, just calls the init() function.
-	MutexLock() : doors_used(0), owner_index(NO_OWNER), lockcount(0) { init();	}
-
-	//! blocks (by busy looping on do_try_lock()) until a lock is achieved
-	/*! You should pass some process-specific ID number as the input - just
-	 *  make sure no other process will be using the same value.
-	 *
-	 *  This is not a recursive lock - repeated locks still only require one
-	 *  release to undo them.
-	 *  @todo - I'd like to not use a loop here */
-	void lock(int id);
-
-	//! attempts to get a lock, returns true if it succeeds
-	/*! You should pass some process-specific ID number as the input - just
-	 *  make sure no other process will be using the same value.
-	 *
-	 *  This is not a recursive lock - repeated locks still only require one
-	 *  release to undo them. */
-	bool try_lock(int id);
-
-	//! releases one recursive lock-level from whoever has the current lock
-	void release();
-
-	//! completely unlocks, regardless of how many times a recursive lock has been obtained
-	inline void unlock() { lockcount=1; release(); }
-
-	//! returns the lockcount
-	unsigned int get_lock_level() const { return lockcount;	}
-
-	//! returns the current owner's id
-	inline int owner() { return owner_index==NO_OWNER ? NO_OWNER : doors[owner_index].id; }
-
-	//! allows you to reset one of the possible owners, so another process can take its place.  This is not tested
-	void forget(int id);
-
-#ifdef MUTEX_LOCK_ET_USE_SPINCOUNT
-	inline unsigned int getSpincount() { return spincount; } //!< returns the number of times the spin() function has been called
-	inline unsigned int resetSpincount() { spincount=0; } //!< resets the counter of the number of times the spin() function has been called
-#endif
-	
- protected:
-	//! Does the work of trying to get a lock
-	/*! Pass @c true for @a block if you want it to use FCFS blocking
-	 *  instead of just returning right away if another process has the lock */
-	bool do_try_lock(unsigned int index, bool block);
-
-	//! returns the internal index mapping to the id number supplied by the process
-	unsigned int lookup(int id); //may create a new entry
-
-#ifdef MUTEX_LOCK_ET_USE_SPINCOUNT
-	volatile unsigned int spincount; //!< handy to track how much time we're wasting
-	void init() { spincount=0; }//memset((void*)doors,0,sizeof(doors)); } //!< just resets spincount
-	inline void spin() { spincount++; } //!< if you find a way to sleep for a few microseconds instead of busy waiting, put it here
-#else
-	void init() { } //!< Doesn't do anything if you have the MUTEX_LOCK_ET_USE_SPINCOUNT undef'ed.  Used to do a memset, but that was causing problems....
-	//memset((void*)doors,0,sizeof(doors)); } 
-	inline void spin() {} //!< If you find a way to sleep for a few microseconds instead of busy waiting, put it here
-#endif
-		
-	//! Holds per process shared info, one of these per process
-	struct door_t {
-		door_t() : id(NO_OWNER), FCFS_in_use(false), BL_ready(false), BL_in_use(false), turn('\0'), next_turn_bit('\0') {} //!< constructor
-		//door_t(int i) : id(i), FCFS_in_use(false), BL_ready(false), BL_in_use(false), next_turn_bit('\0') {}
-		int id; //!< process ID this doorway is assigned to
-		volatile bool FCFS_in_use; //!< In FCFS doorway, corresponds to 'c_i'
-		volatile bool BL_ready; //!< Signals past FCFS doorway, ready for BL doorway, corresponds to 'v_i'
-		volatile bool BL_in_use; //!< Burns-Lamport doorway, corresponds to 'x_i'
-		volatile unsigned char turn; //!< clock pulse, initial value doesn't matter
-		unsigned char next_turn_bit; //!< selects which bit of turn will be flipped next
-	};
-
-	door_t doors[num_doors]; //!< holds all the doors
-	unsigned int doors_used; //!< counts the number of doors used
-	unsigned int owner_index; //!< holds the door index of the current lock owner
-	unsigned int lockcount; //!< the depth of the lock, 0 when unlocked
-};
-
-
-template<unsigned int num_doors>
-void
-MutexLock<num_doors>::lock(int id) {
-	if(owner()!=id)
-		while(!do_try_lock(lookup(id),true))
-			spin();
-	lockcount++;
-}
-
-
-template<unsigned int num_doors>
-bool
-MutexLock<num_doors>::try_lock(int id) {
-	if(owner()==id) {
-		lockcount++;
-		return true;
-	} else {
-		if(do_try_lock(lookup(id),false)) {
-			lockcount++;
-			return true;
-		} else
-			return false;
-	}
-}
-
-
-template<unsigned int num_doors>
-void
-MutexLock<num_doors>::release() {
-	if(lockcount>0)
-		if(--lockcount==0)
-			if(owner_index!=NO_OWNER) {
-				unsigned int tmp = owner_index;
-				owner_index=NO_OWNER;
-				doors[tmp].BL_in_use=false;
-				doors[tmp].BL_ready=false;
-				// *** Lock has been released *** //
-			}
-}
-
-
-//! If you define this to do something more interesting, can use it to see what's going on in the locking process
-#define mutexdebugout(i,c) {}
-//#define mutexdebugout(i,c) { std::cout << ((char)(i==0?c:((i==1?'M':'a')+(c-'A')))) << std::flush; }
-
-
-template<unsigned int num_doors>
-bool
-MutexLock<num_doors>::do_try_lock(unsigned int i, bool block) {
-	if(i==NO_OWNER) {
-		std::cerr << "WARNING: new process attempted to lock beyond num_doors ("<<num_doors<<")" << std::endl;
-		return false;
-	}
-	unsigned char S[num_doors]; // a local copy of everyone's doors
-	// *** Entering FCFS doorway *** //
-//	pprintf(TextOutputStream,"**%d**\n",i);
-mutexdebugout(i,'A');
-	doors[i].FCFS_in_use=true;
-	for(unsigned int j=0; j<num_doors; j++)
-		S[j]=doors[j].turn;
-	doors[i].next_turn_bit=1-doors[i].next_turn_bit;
-	doors[i].turn^=(1<<doors[i].next_turn_bit);
-	doors[i].BL_ready=true;
-	doors[i].FCFS_in_use=false;
-	// *** Leaving FCFS doorway *** //
-mutexdebugout(i,'B');
-	for(unsigned int j=0; j<num_doors; j++) {
-mutexdebugout(i,'C');
-		while(doors[j].FCFS_in_use || (doors[j].BL_ready && S[j]==doors[j].turn))
-			if(block)
-				spin();
-			else {
-				doors[i].BL_ready=false;
-				return false;
-			}
-mutexdebugout(i,'D');
-	}
-	// *** Entering Burns-Lamport *** //
-mutexdebugout(i,'E');
-	do {
-		doors[i].BL_in_use=true;
-		for(unsigned int t=0; t<i; t++)
-			if(doors[t].BL_in_use) {
-				doors[i].BL_in_use=false;
-				if(!block) {
-					doors[i].BL_ready=false;
-					return false;
-				}
-mutexdebugout(i,'F');
-				while(doors[t].BL_in_use)
-					spin();
-mutexdebugout(i,'G');
-				break;
-			}
-	} while(!doors[i].BL_in_use);
-	for(unsigned int t=i+1; t<num_doors; t++)
-		while(doors[t].BL_in_use)
-			spin();
-	// *** Leaving Burns-Lamport ***//
-	// *** Lock has been given *** //
-mutexdebugout(i,'H');
-	owner_index=i;
-	return true;
-}
-
-
-template<unsigned int num_doors>
-unsigned int
-MutexLock<num_doors>::lookup(int id) {
-	// TODO - this could break if two new processes are adding themselves at the same time
-	//        or an id is being forgotten at the same time
-	//I'm expecting a very small number of processes to be involved
-	//probably not worth overhead of doing something fancy like a sorted array
-	unsigned int i;
-	for(i=0; i<doors_used; i++)
-		if(doors[i].id==id)
-			return i;
-	if(i==num_doors)
-		return NO_OWNER;
-	doors[i].id=id;
-	doors_used++;
-	return i;
-}
-
-
-template<unsigned int num_doors>
-void
-MutexLock<num_doors>::forget(int id) { //not tested thoroughly
-	unsigned int i = lookup(id);
-	do_try_lock(i,true);
-	doors[i].id=doors[--doors_used].id;
-	doors[doors_used].id=NO_OWNER;
-	release();
-}
-
-
-/*! @file 
- * @brief Defines MutexLock, a software only mutual exclusion lock.
- * @author ejt (Creator), Edward A. Lycklama, Vassos Hadzilacos (paper from which this was based)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
- * $State: Exp $
- * $Date: 2004/02/12 17:48:59 $
- */
-
-#endif
diff -urdN ../Tekkotsu_2.3/Shared/ODataFormats.h ./Shared/ODataFormats.h
--- ../Tekkotsu_2.3/Shared/ODataFormats.h	Wed Dec 31 19:00:00 1969
+++ ./Shared/ODataFormats.h	Wed Feb  2 13:22:29 2005
@@ -0,0 +1,148 @@
+//-*-c++-*-
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/ODataFormats.h>
+#else
+#  ifndef INCLUDED_ODataFormats_h_
+#  define INCLUDED_ODataFormats_h_
+
+#include <stdlib.h>
+
+//! provides compatability with the OPEN-R type of the same name
+struct ODataVectorInfo {
+	size_t numData;
+};
+
+typedef unsigned char byte;
+typedef unsigned short word;
+typedef unsigned long longword;
+typedef word OSoundFormat;
+const OSoundFormat osoundformatUNDEF     = 0;
+const OSoundFormat osoundformatPCM       = 1;
+const OSoundFormat osoundformatUSB_MIDI  = 2;
+const OSoundFormat osoundformatSMF       = 3; // STANDARD MIDI FILE
+
+
+typedef word OSoundChannel;
+const OSoundChannel osoundchannelUNDEF  = 0;
+const OSoundChannel osoundchannelMONO   = 1;
+const OSoundChannel osoundchannelSTEREO = 2;
+
+//! provides compatability with the OPEN-R type of the same name
+struct OSoundInfo {		                 // 64 bytes (total)
+	typedef int longword;
+	typedef short word;
+
+    longword             frameNumber;    //  4 bytes
+    size_t               frameSize;      //  4 bytes
+    size_t               dataOffset;	 //  4 bytes
+    size_t               maxDataSize;	 //  4 bytes
+    size_t               dataSize;       //  4 bytes
+    OSoundFormat         format;         //  2 bytes
+    OSoundChannel        channel;        //  2 bytes
+    word                 samplingRate;   //  2 bytes
+    word                 bitsPerSample;  //  2 bytes
+    size_t               actualDataSize; //  4 bytes
+    longword             padding[6];	 // 24 bytes
+};
+
+//! provides compatability with the OPEN-R type of the same name
+struct OSoundVectorData {
+    ODataVectorInfo  vectorInfo;
+    OSoundInfo       info[1];
+
+    void SetNumData(size_t ndata)  { vectorInfo.numData = ndata; }
+    OSoundInfo* GetInfo(int index) { return &info[index];        }
+    byte*       GetData(int index) {
+        return ((byte*)&vectorInfo + info[index].dataOffset);
+    }
+};
+
+//! provides compatability with the OPEN-R type of the same name
+struct OFbkImageInfo {          // 32 bytes (total)
+    longword      frameNumber;  //  4 bytes
+    size_t        dataOffset;   //  4 bytes
+    size_t        dataSize;     //  4 bytes
+    size_t        width;        //  4 bytes
+    size_t        height;       //  4 bytes
+    size_t        padding[1];   //  4 bytes
+};
+
+//! provides compatability with the OPEN-R type of the same name
+struct OFbkImageVectorData {
+    ODataVectorInfo  vectorInfo;
+    OFbkImageInfo    info[1];
+
+    OFbkImageInfo* GetInfo(int index) { return &info[index]; }
+    byte*          GetData(int index) {
+        return ((byte*)&vectorInfo + info[index].dataOffset);
+    }
+};
+
+typedef int OFbkImageLayer;
+const OFbkImageLayer ofbkimageLAYER_H = 0;
+const OFbkImageLayer ofbkimageLAYER_M = 1;
+const OFbkImageLayer ofbkimageLAYER_L = 2;
+const OFbkImageLayer ofbkimageLAYER_C = 3;
+
+const int ocdtNUM_CHANNELS  =  8;
+typedef longword OCdtChannel;
+const OCdtChannel ocdtCHANNEL_UNDEF = 0x00;
+const OCdtChannel ocdtCHANNEL0      = 0x01;
+const OCdtChannel ocdtCHANNEL1      = 0x02;
+const OCdtChannel ocdtCHANNEL2      = 0x04;
+const OCdtChannel ocdtCHANNEL3      = 0x08;
+const OCdtChannel ocdtCHANNEL4      = 0x10;
+const OCdtChannel ocdtCHANNEL5      = 0x20;
+const OCdtChannel ocdtCHANNEL6      = 0x40;
+const OCdtChannel ocdtCHANNEL7      = 0x80;
+
+const int ocdtMAX_Y_SEGMENT    = 32;
+const longword ocdtINIT        = 0x80808080;
+const longword ocdtCr_MAX_MASK = 0x0000ff00;
+const longword ocdtCr_MIN_MASK = 0x000000ff;
+const longword ocdtCb_MAX_MASK = 0xff000000;
+const longword ocdtCb_MIN_MASK = 0x00ff0000;
+
+struct OCdtInfo {		                    // 144 bytes
+    OCdtChannel   channel;		            //   4 bytes
+    longword      table[ocdtMAX_Y_SEGMENT]; // 128 bytes
+    longword      padding;		            //   4 bytes
+    
+    void Init(OCdtChannel chan) {
+        channel     = chan;
+        for (int i = 0; i < ocdtMAX_Y_SEGMENT; i++) table[i] = ocdtINIT;
+    }
+    void Set(int y_segment,byte cr_max, byte cr_min, byte cb_max, byte cb_min) {
+        longword crMax = (longword)cr_max;
+        longword crMin = (longword)cr_min;
+        longword cbMax = (longword)cb_max;
+        longword cbMin = (longword)cb_min;
+        crMax = (crMax <<  8) & ocdtCr_MAX_MASK;
+        crMin = (crMin      ) & ocdtCr_MIN_MASK;
+        cbMax = (cbMax << 24) & ocdtCb_MAX_MASK;
+        cbMin = (cbMin << 16) & ocdtCb_MIN_MASK;
+        table[y_segment] =  crMax | crMin | cbMax | cbMin;
+    }
+};
+
+struct OCdtVectorData{
+    ODataVectorInfo  vectorInfo;
+    OCdtInfo         info[ocdtNUM_CHANNELS];
+
+    void SetNumData(size_t ndata) { vectorInfo.numData = ndata; }
+    OCdtInfo* GetInfo(int index)  { return &info[index];        }
+};
+
+/*! @file
+ * @brief Defines several data structures for compatability with OPEN-R
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.1 $
+ * $State: Exp $
+ * $Date: 2005/02/02 18:22:29 $
+ */
+
+#  endif
+#endif
diff -urdN ../Tekkotsu_2.3/Shared/ProcessID.cc ./Shared/ProcessID.cc
--- ../Tekkotsu_2.3/Shared/ProcessID.cc	Thu Sep 25 11:31:53 2003
+++ ./Shared/ProcessID.cc	Wed Dec 31 19:00:00 1969
@@ -1,15 +0,0 @@
-#include "ProcessID.h"
-
-ProcessID::ProcessID_t ProcessID::ID=ProcessID::NumProcesses;
-
-/*! @file
- * @brief Declares the static ProcessID::ID, that's all
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/09/25 15:31:53 $
- */
-
diff -urdN ../Tekkotsu_2.3/Shared/ProcessID.h ./Shared/ProcessID.h
--- ../Tekkotsu_2.3/Shared/ProcessID.h	Thu Sep 25 11:31:53 2003
+++ ./Shared/ProcessID.h	Wed Dec 31 19:00:00 1969
@@ -1,36 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_ProcessID_h_
-#define INCLUDED_ProcessID_h_
-
-//! this is a class instead of a namespace so i can limit write access of the ID value to the OObjects
-class ProcessID {
-public:
-	//! Holds ID number for each process
-	enum ProcessID_t {
-		MainProcess,   //!< MainObj process
-		MotionProcess, //!< MotoObj process
-		SoundProcess,  //!< SoundPlay process
-		NumProcesses   //!< count of processes
-	};
-	
-	static ProcessID_t getID() { return ID; }  //!< returns process's ID number, or if within a virtual function on a shared object, the process which created it (annoying)
-	
-private:
-	friend class MMCombo; //!< so that it can set the ID during init
-	friend class SoundPlay; //!< so that it can set the ID during init
-	static void setID(ProcessID_t id) { ID=id; } //!< sets the ID during init
-	static ProcessID_t ID; //!< holds ID number
-};
-
-/*! @file
- * @brief Defines ProcessID - simple little global for checking which process is currently running, kind of. (see ProcessID::getID() )
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/09/25 15:31:53 $
- */
-
-#endif
diff -urdN ../Tekkotsu_2.3/Shared/Profiler.cc ./Shared/Profiler.cc
--- ../Tekkotsu_2.3/Shared/Profiler.cc	Thu Mar 25 12:08:57 2004
+++ ./Shared/Profiler.cc	Thu Jul 28 13:10:07 2005
@@ -5,8 +5,7 @@
 
 float Profiler::buckets[Profiler::HistSize];
 
-#warning Note: Ignore warning on next line (sorry!)
-unsigned int Profiler::infosOffset=offsetof(ProfilerOfSize<1>,infos); //(unsigned int)(static_cast<ProfilerOfSize<1>*>(NULL)->infos);
+unsigned int Profiler::infosOffset=((size_t)(&static_cast<ProfilerOfSize<1>*>(NULL)[1].infos))-((size_t)(&static_cast<ProfilerOfSize<1>*>(NULL)[1].prof));
 
 /*! Tells the profiler that this is now the active timer, so new timers will fit "under" this.\n
  *  Timer isn't actually started here, lets Profiler::setCurrent do that.
@@ -113,9 +112,20 @@
 }
 
 Profiler::Profiler(unsigned int mx)
-	: curSection(-1U), startTime(), gamma(.85), maxSections(mx), sectionsUsed(0)
+	: curSection(-1U), startTime(), gamma(.85), maxSections(mx), sectionsUsed(0), autoInit()
 { }
 
+unsigned int Profiler::AutoInit::refcount=0;
+unsigned int Profiler::AutoInit::totalcount=0;
+
+Profiler::AutoInit::AutoInit() {
+	if(totalcount==0)
+		Profiler::initBuckets();
+	totalcount++;
+	refcount++;
+}
+
+Profiler::AutoInit::~AutoInit() { refcount--; }
 
 void Profiler::setCurrent(Timer& tr) {
 	SectionInfo& info=getInfos()[tr._id];
@@ -163,8 +173,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.13 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.14 $
  * $State: Exp $
- * $Date: 2004/03/25 17:08:57 $
+ * $Date: 2005/07/28 17:10:07 $
  */
diff -urdN ../Tekkotsu_2.3/Shared/Profiler.h ./Shared/Profiler.h
--- ../Tekkotsu_2.3/Shared/Profiler.h	Wed Feb  4 18:06:47 2004
+++ ./Shared/Profiler.h	Sun Aug  7 00:11:04 2005
@@ -13,7 +13,7 @@
  */
 #define PROFSECTION(NAME,PROF) \
   static unsigned int _PROFSECTION_id=PROF.getNewID(NAME);\
-  Profiler::Timer timer(_PROFSECTION_id,&PROF);
+  Profiler::Timer _PROFSECTION_timer(_PROFSECTION_id,&PROF.prof);
 
 //! Managers a hierarchy of timers for profiling time spent in code, gives microsecond resolution
 /*! Doesn't use any pointers so it's safe to put this in shared memory regions.\n
@@ -29,7 +29,7 @@
  *  
  *  void f() {
  *    static unsigned int id=prof.getNewID("f"); // <== Get the ID number 
- *    Profiler::Timer timer(id,&prof);           // <== start the timer
+ *    Profiler::Timer timer(id,&prof.prof);      // <== start the timer
  *    //...
  *    if(rand()>RAND_MAX/2)
  *      return; // destruction of timer occurs automatically!
@@ -86,6 +86,9 @@
  */
 class Profiler {
 public:
+	//! constructor, but you don't want to construct one of these!  Use ProfilerOfSize<x> instead!
+	Profiler(unsigned int mx);
+	
 	//! maximum length of names of timers
 	static const unsigned int MaxSectionNameLen=75;
 	//! number of slots in the histograms
@@ -122,7 +125,7 @@
 		Timer() : _prof(NULL), _id(-1U), _parent(-1U), _t() {} //!< constructor - starts timer, but you can restart it...
 		Timer(unsigned int id, Profiler* prof); //!< constructor - starts the timer, sets current timer in @a prof
 		Timer(const Timer& t) : _prof(t._prof), _id(t._id), _parent(t._parent),_t(t._t) { } //!< copy constructor, not that you should need it, does same as default
-		Timer operator=(const Timer& t) { _prof=t._prof; _id=t._id; _parent=t._parent; _t=t._t; return *this; } //!< not that you should need it, does same as default
+		Timer& operator=(const Timer& t) { _prof=t._prof; _id=t._id; _parent=t._parent; _t=t._t; return *this; } //!< not that you should need it, does same as default
 		~Timer(); //!< destructor - stops the timer, reports results
 		void setID(unsigned int id, Profiler* prof); //!< sets the ID and profiler, also starts timer
 		void start() { _t.Set(); } //!< starts timer (or resets it)
@@ -160,9 +163,6 @@
 	inline SectionInfo* getInfos() { return (SectionInfo*)((char*)this+infosOffset); }
 		
 protected:
-	//! constructor, protected because you don't want to construct one of these - use ProfilerOfSize<x>!
-	Profiler(unsigned int mx);
-
 	//! Only the Timer's should be calling setCurrent() and finished() upon the Timer's construction and destruction
 	friend class Timer;
 	//! called automatically by Timer() - sets the current timer
@@ -189,14 +189,32 @@
 	static float buckets[HistSize];  //!< holds boundaries for each bucket
 
 	static unsigned int infosOffset; //!< NASTY HACK - this is how we get around using virtual functions
+	
+	//! Automatically causes initialization of the histogram buckets when the first Profiler is instantiated
+	class AutoInit {
+	public:
+		AutoInit();
+		~AutoInit();
+	protected:
+		static unsigned int refcount; //!< the number of profilers in existance
+		static unsigned int totalcount; //!< the number of profilers which have been created
+	} autoInit;
 };
 
 //! templated subclass allows compile-time flexibility of how much memory to use.
 template<unsigned int MaxSections>
-class ProfilerOfSize : public Profiler {
+class ProfilerOfSize {
 public:
-	ProfilerOfSize() : Profiler(MaxSections) {} //!< constructor
-	SectionInfo infos[MaxSections]; //!< the actual profiling information storage
+	ProfilerOfSize() : prof(MaxSections) {} //!< constructor
+	
+	//! call this to get a new ID number
+	unsigned int getNewID(const char* name) { return prof.getNewID(name); }
+	
+	//! outputs profiling information
+	std::string report() { return prof.report(); }
+	
+	Profiler prof; //!< the profiler that does the work, must immediately preceed #infos!
+	Profiler::SectionInfo infos[MaxSections]; //!< the actual profiling information storage
 };
 
 /*! @file
@@ -204,10 +222,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2004/02/04 23:06:47 $
+ * $Date: 2005/08/07 04:11:04 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/ProjectInterface.cc ./Shared/ProjectInterface.cc
--- ../Tekkotsu_2.3/Shared/ProjectInterface.cc	Fri Jul 16 15:25:09 2004
+++ ./Shared/ProjectInterface.cc	Wed Jun  1 01:47:49 2005
@@ -3,11 +3,11 @@
 
 FilterBankGenerator * ProjectInterface::defRawCameraGenerator=0;
 FilterBankGenerator * ProjectInterface::defInterleavedYUVGenerator=0;
-FilterBankGenerator * ProjectInterface::defColorJPEGGenerator=0;
-FilterBankGenerator * ProjectInterface::defGrayscaleJPEGGenerator=0;
+JPEGGenerator * ProjectInterface::defColorJPEGGenerator=0;
+JPEGGenerator * ProjectInterface::defGrayscaleJPEGGenerator=0;
 SegmentedColorGenerator * ProjectInterface::defSegmentedColorGenerator=0;
-FilterBankGenerator * ProjectInterface::defRLEGenerator=0;
-FilterBankGenerator * ProjectInterface::defRegionGenerator=0;
+RLEGenerator * ProjectInterface::defRLEGenerator=0;
+RegionGenerator * ProjectInterface::defRegionGenerator=0;
 
 unsigned int ProjectInterface::visRawCameraSID=0;
 
@@ -38,9 +38,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
  * $State: Exp $
- * $Date: 2004/07/16 19:25:09 $
+ * $Date: 2005/06/01 05:47:49 $
  */
 
diff -urdN ../Tekkotsu_2.3/Shared/ProjectInterface.h ./Shared/ProjectInterface.h
--- ../Tekkotsu_2.3/Shared/ProjectInterface.h	Wed Dec 22 20:47:07 2004
+++ ./Shared/ProjectInterface.h	Wed Jun  1 01:47:49 2005
@@ -5,6 +5,9 @@
 class BehaviorBase;
 class FilterBankGenerator;
 class SegmentedColorGenerator;
+class RLEGenerator;
+class RegionGenerator;
+class JPEGGenerator;
 
 //! A collection of the global variables which should be set by a project to use the Tekkotsu framework
 /*! You don't necessarily need to define all of these, but if you want
@@ -27,19 +30,25 @@
 	//! REQUIRED: you must define a behavior which will be started when the boot is complete
 	/*! This is similar in idea to the Linux init process - it should do
 	 *  some basic initialization and then launch any other behavior you
-	 *  would like to run at boot. */
-	extern BehaviorBase& startupBehavior;
+	 *  would like to run at boot.
+	 *  To avoid static initialization ordering issues, this is a function
+	 *  which will be called after environment setup is complete, which
+	 *  should then return a behavior to use as the startup behavior.
+	 *  This behavior should not be reference counted, and probably makes
+	 *  most sense to implement as a static local variable of the function.
+	 *  (Each call should return the same behavior) */
+	BehaviorBase& startupBehavior();
 
 	//! A collection of the various stages of vision processing.  None of these are absolutely required, but are needed to run included demo behaviors and TekkotsuMon modules
 	/*! @name Vision Setup */
 	//! pointer to generator
 	extern FilterBankGenerator * defRawCameraGenerator;
 	extern FilterBankGenerator * defInterleavedYUVGenerator;
-	extern FilterBankGenerator * defColorJPEGGenerator;
-	extern FilterBankGenerator * defGrayscaleJPEGGenerator;
+	extern JPEGGenerator * defColorJPEGGenerator;
+	extern JPEGGenerator * defGrayscaleJPEGGenerator;
 	extern SegmentedColorGenerator * defSegmentedColorGenerator;
-	extern FilterBankGenerator * defRLEGenerator;
-	extern FilterBankGenerator * defRegionGenerator;
+	extern RLEGenerator * defRLEGenerator;
+	extern RegionGenerator * defRegionGenerator;
 	//@}
 
 	//! Default source IDs for the various generators; These are given default values, but you can reassign them if you like.
@@ -73,10 +82,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/06/01 05:47:49 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/ReferenceCounter.h ./Shared/ReferenceCounter.h
--- ../Tekkotsu_2.3/Shared/ReferenceCounter.h	Thu Nov 11 15:35:00 2004
+++ ./Shared/ReferenceCounter.h	Wed Feb  2 13:22:29 2005
@@ -35,7 +35,7 @@
 	}
 	//! returns the number of references
 	/*! @return references */
-	virtual unsigned int GetReferences() { return references; }
+	virtual unsigned int GetReferences() const { return references; }
 
 	//! if true, next time a RemoveReference() causes #references to hit 0, the object will delete itself
 	void SetAutoDelete(bool b) {RC_autodelete=b;}
@@ -73,10 +73,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/11/11 20:35:00 $
+ * $Date: 2005/02/02 18:22:29 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/RobotInfo.h ./Shared/RobotInfo.h
--- ../Tekkotsu_2.3/Shared/RobotInfo.h	Mon Feb  9 17:45:28 2004
+++ ./Shared/RobotInfo.h	Wed Jun  1 01:47:49 2005
@@ -6,13 +6,13 @@
 #	include "ERS220Info.h"
 #elif TGT_ERS210
 #	include "ERS210Info.h"
+#elif TGT_ERS2xx
+#	include "ERS2xxInfo.h"
 #elif TGT_ERS7
 #	include "ERS7Info.h"
-#else //default case, ERS2xx
-#	if TGT_ERS2xx==0
-#		warning "TGT_<model> undefined - defaulting to ERS2xx"
-#	endif
-#	include "ERS2xxInfo.h"
+#else //default case, currently ERS-7
+#	warning "TGT_<model> undefined or unknown model set - defaulting to ERS7 (valid values are TGT_ERS210, TGT_ERS220, TGT_ERS2xx, or TGT_ERS7)"
+#	include "ERS7Info.h"
 #endif //model selection
 
 //! Contains information about the robot, such as number of joints, PID defaults, timing information, etc.
@@ -29,8 +29,10 @@
 	using namespace ERS210Info;
 #elif TGT_ERS7
 	using namespace ERS7Info;
-#else //default case, ERS2xx
+#elif TGT_ERS2xx
 	using namespace ERS2xxInfo;
+#else //default case, ERS7
+	using namespace ERS7Info;
 #endif //model selection	
 }
 
@@ -41,10 +43,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.15 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.16 $
  * $State: Exp $
- * $Date: 2004/02/09 22:45:28 $
+ * $Date: 2005/06/01 05:47:49 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/SharedObject.h ./Shared/SharedObject.h
--- ../Tekkotsu_2.3/Shared/SharedObject.h	Fri Sep 12 19:42:12 2003
+++ ./Shared/SharedObject.h	Wed Dec 31 19:00:00 1969
@@ -1,125 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_SharedObject_h
-#define INCLUDED_SharedObject_h
-
-#include <OPENR/RCRegion.h>
-
-//! It's nice to have a parent class of SharedObject (which is what you probably want to be reading) so that you can pass around the data structure without worrying about what type is inside the shared memory region.
-/*! See MotionManager for an example on how to use this. */
-class SharedObjectBase {
-public:
-	void* data() const { return rcr->Base(); } //!< returns a pointer to the data region
-	RCRegion * getRegion() const { return rcr; } //!< returns the OPEN-R memory region, should you need it
-
-protected:
-	SharedObjectBase() : rcr(NULL) {} //!< constructor, protected because you shouldn't need to create this directly, just a common interface to all templates of SharedObject
-
-	//< destructor, automatically dereferences #rcr
-	virtual ~SharedObjectBase() {
-		//std::cout << "~SharedObjectBase(): rcr->NumberOfReference()==" << rcr->NumberOfReference() << std::endl;
-		if(rcr && rcr->NumberOfReference()>0)
-			rcr->RemoveReference();
-		else
-			std::cout << "WARNING: SharedObjectBase destructed without reference" << std::endl;
-		//std::cout << "~SharedObjectBase()NOW: rcr->NumberOfReference()==" << rcr->NumberOfReference() << std::endl;
-	} 
-	RCRegion * rcr; //!< the pointer to the shared memory region this is in charge of
-	
-private:
-	SharedObjectBase(const SharedObjectBase&); //!< this shouldn't be called...
-	SharedObjectBase& operator=(const SharedObjectBase&); //!< this shouldn't be called...
-};	
-
-//! This templated class allows convenient creation of any type of class wrapped in a shared memory region
-/*! @see MotionManager for an example on how to use this.*/
-template<class MC>
-class SharedObject : public SharedObjectBase {
-public:
-	//!if you really need more than 5 arguments for your class, well, you're one crazy puppy but if you really want to, just make more like shown... (yay templates!)
-	//!@name templated contructors - allows you to pass constructor arguments on to the object being created
-
-	//! Creates the class with the default constructor
-	SharedObject() : SharedObjectBase() {
-		rcr=createRCRegion();
-		new (rcr->Base()) MC;
-	}
-	//! Creates the class, passing its constructor t1
-	template<class T1> SharedObject(T1 t1) : SharedObjectBase() {
-		rcr=createRCRegion();
-		new (rcr->Base()) MC(t1);
-	}
-	//! Creates the class, passing its constructor t1 and t2
-	template<class T1, class T2> SharedObject(T1 t1, T2 t2) : SharedObjectBase(){
-		rcr=createRCRegion();
-		new (rcr->Base()) MC(t1,t2);
-	}
-	//! Creates the class, passing its constructor t1, t2, and t3
-	template<class T1, class T2, class T3> SharedObject(T1 t1, T2 t2, T3 t3) : SharedObjectBase(){
-		rcr=createRCRegion();
-		new (rcr->Base()) MC(t1,t2,t3);
-	}
-	//! Creates the class, passing its constructor t1, t2, t3 and t4
-	template<class T1, class T2, class T3, class T4> SharedObject(T1 t1, T2 t2, T3 t3, T4 t4) : SharedObjectBase(){
-		rcr=createRCRegion();
-		new (rcr->Base()) MC(t1,t2,t3,t4);
-	}
-	//! Creates the class, passing its constructor t1, t2, t3, t4 and t5 - if you need more arguments, just add them
-	template<class T1, class T2, class T3, class T4, class T5> SharedObject(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) : SharedObjectBase(){
-		rcr=createRCRegion();
-		new (rcr->Base()) MC(t1,t2,t3,t4,t5);
-	}
-	//@}
-
-	MC* operator->() const { return dataCasted(); } //!< smart pointer to the underlying class
-	MC& operator*() const { return *dataCasted(); } //!< smart pointer to the underlying class
-	MC& operator[](int i) const { return dataCasted()[i]; } //!< smart pointer to the underlying class
-protected:
-	//! creates and returns RCRegion of correct size for current class.  Adds a reference (which is removed in the destructor)
-	static RCRegion * createRCRegion() {
-		RCRegion * r = new RCRegion(calcsize());
-		//std::cout << "createRCRegion(): rcr->NumberOfReference()==" << r->NumberOfReference() << std::endl;
-		r->AddReference();
-		//std::cout << "createRCRegion()NOW: rcr->NumberOfReference()==" << r->NumberOfReference() << std::endl;
-		return r;
-	}
-	MC* dataCasted() const { return static_cast<MC*>(data()); } //!< returns a correctly typed pointer to the object's memory
-
-	//!Calculates the size of the memory region to be used, rounding up to the nearest page size
-	/*! Not sure this is completely necessary, but may be nice.  Of course, this also means even
-	 *  small regions are going to be at least 4K (current page size)  If memory gets tight or we
-	 *  get a lot of little regions floating around, this might be worth checking into */
-	static unsigned int calcsize() {
-		size_t size = sizeof(MC);
-		sError error;
-		size_t page_size;
-		error = GetPageSize(&page_size);
-		if (error != sSUCCESS) {
-			cout << "error: " << error << " getting page size in SharedMem" << endl;
-			page_size = 4096;
-		}
-		
-		int new_size,num_pages;
-		num_pages = (size+page_size-1)/page_size;
-		new_size = num_pages*page_size;
-		//cout << "req" << size << "new" << new_size << "ps" << page_size << endl;
-		/*		cout << "data size is " << sizeof(MC) << endl;
-					cout << "msg size is " << MotionManagerMsg::SIZEOF_MSG << endl;
-					cout << "SIZE is " << rcr->Size() << endl;
-					cout << "PAGE is " << page_size << endl;
-					cout << "BASE is " << (void*)rcr->Base() << endl; */
-		return new_size;
-	}
-};
-
-/*! @file
- * @brief Defines SharedObject, a wrapper for objects in order to facilitate sending them between processes
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/09/12 23:42:12 $
- */
-
-#endif //INCLUDED_SharedObject_h
diff -urdN ../Tekkotsu_2.3/Shared/SharedQueue.h ./Shared/SharedQueue.h
--- ../Tekkotsu_2.3/Shared/SharedQueue.h	Sun Jan 18 05:16:58 2004
+++ ./Shared/SharedQueue.h	Tue Mar  8 21:59:53 2005
@@ -95,7 +95,7 @@
 template<unsigned int maxsize, unsigned int maxentries> template<class T>
 bool
 SharedQueue<maxsize,maxentries>::push(const T& obj) {
-	AutoLock(lock,ProcessID::getID());
+	AutoLock autolock(lock,ProcessID::getID());
 	if(len>=MAX_ENTRIES)
 		return false;
 	entries[len].offset=buf_end();
@@ -109,7 +109,7 @@
 template<unsigned int maxsize, unsigned int maxentries>
 void*
 SharedQueue<maxsize,maxentries>::reserve(unsigned int sz) {
-	AutoLock(lock,ProcessID::getID());
+	lock.lock(ProcessID::getID()); //note *not* an AutoLock -- we want it to stay locked until done() is called!
 	if(len>=MAX_ENTRIES)
 		return NULL;
 	entries[len].offset=buf_end();
@@ -122,7 +122,7 @@
 template<unsigned int maxsize, unsigned int maxentries>
 bool
 SharedQueue<maxsize,maxentries>::clear(unsigned int taken) {
-	AutoLock(lock,ProcessID::getID());
+	AutoLock autolock(lock,ProcessID::getID());
 	if(size()!=taken)
 		return false;
 	len=0;
@@ -134,10 +134,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
  * $State: Exp $
- * $Date: 2004/01/18 10:16:58 $
+ * $Date: 2005/03/09 02:59:53 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/SystemUtility.h ./Shared/SystemUtility.h
--- ../Tekkotsu_2.3/Shared/SystemUtility.h	Fri Oct 10 13:46:04 2003
+++ ./Shared/SystemUtility.h	Fri Oct 10 13:46:04 2003
@@ -60,7 +60,7 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.4 $
  * $State: Rel $
  * $Date: 2003/10/10 17:46:04 $
diff -urdN ../Tekkotsu_2.3/Shared/TimeET.cc ./Shared/TimeET.cc
--- ../Tekkotsu_2.3/Shared/TimeET.cc	Thu Sep 25 11:31:53 2003
+++ ./Shared/TimeET.cc	Thu Sep 25 11:31:53 2003
@@ -7,7 +7,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.3 $
  * $State: Rel $
  * $Date: 2003/09/25 15:31:53 $
diff -urdN ../Tekkotsu_2.3/Shared/TimeET.h ./Shared/TimeET.h
--- ../Tekkotsu_2.3/Shared/TimeET.h	Thu Mar 25 12:09:18 2004
+++ ./Shared/TimeET.h	Wed Jun  1 01:47:49 2005
@@ -76,14 +76,14 @@
 
 	//@{
 	//!for comparing times
-  inline bool operator<(long ms) { //what if ms is negative?
+  inline bool operator<(long ms) const { //what if ms is negative?
     time_t sec = ms/ms_per_sec;
     return tv.tv_sec<sec || tv.tv_sec==sec && tv.tv_usec<static_cast<long>((ms-sec*ms_per_sec)*us_per_ms);
   }
-  inline bool operator<(double t) {
+  inline bool operator<(double t) const {
     return Value()<t;
   }
-  inline bool operator<(const TimeET& t) {
+  inline bool operator<(const TimeET& t) const {
     return tv.tv_sec<t.tv.tv_sec || tv.tv_sec==t.tv.tv_sec && tv.tv_usec<t.tv.tv_usec;
   }
 	//@}
@@ -148,10 +148,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/03/25 17:09:18 $
+ * $Date: 2005/06/01 05:47:49 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/Util.h ./Shared/Util.h
--- ../Tekkotsu_2.3/Shared/Util.h	Thu Sep 25 11:31:53 2003
+++ ./Shared/Util.h	Thu Sep 25 11:31:53 2003
@@ -300,7 +300,7 @@
  * @endverbatim
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.5 $
  * $State: Rel $
  * $Date: 2003/09/25 15:31:53 $
diff -urdN ../Tekkotsu_2.3/Shared/WMclass.cc ./Shared/WMclass.cc
--- ../Tekkotsu_2.3/Shared/WMclass.cc	Mon Oct  6 21:01:09 2003
+++ ./Shared/WMclass.cc	Wed Jun  1 01:47:49 2005
@@ -10,6 +10,8 @@
 // toString() methods for various classes
 //
 
+#ifndef __CYGWIN__
+
 template<>
 std::string WMitem<int>::toString(void) const {
   char print_buffer[30];
@@ -67,10 +69,12 @@
 template<>
 std::string WMitem<WMregistry>::toString(void) const {
   char print_buffer[300];
-  sprintf(print_buffer,"<%s, %d entries>",
-	  get_value().name.data(),get_value().entries.size());
+  sprintf(print_buffer,"<%s, %lu entries>",
+	  get_value().name.data(),(unsigned long)get_value().entries.size());
   return std::string(print_buffer);
 }
+
+#endif //CYGWIN-compiler incompatable
 
 WMregistry GlobalWM("GlobalWM");
 
diff -urdN ../Tekkotsu_2.3/Shared/WMclass.h ./Shared/WMclass.h
--- ../Tekkotsu_2.3/Shared/WMclass.h	Fri Oct 10 13:46:04 2003
+++ ./Shared/WMclass.h	Mon Jul 25 23:22:04 2005
@@ -14,10 +14,10 @@
  *  @author alokl (Ported)
  *  
  *  $Author: ejt $
- *  $Name: tekkotsu-2_3 $
- *  $Revision: 1.3 $
- *  $State: Rel $
- *  $Date: 2003/10/10 17:46:04 $
+ *  $Name: tekkotsu-2_4 $
+ *  $Revision: 1.5 $
+ *  $State: Exp $
+ *  $Date: 2005/07/26 03:22:04 $
  *
  * \par These macros allow you to quickly create a WM variable, but only if
  * it's staticly defined - you can't use these with a dynamic number
@@ -121,6 +121,7 @@
 //! WMitem_base is the base class from which all WMitem<T> subclasses are derived.
 class WMitem_base {
 public:
+  virtual ~WMitem_base() {} //!< destructor, does nothing
   void* const         value;    //!< Pointer to the actual variable referenced by this WMitem.
   WMentry*            entry;    //!< Pointer to the WMentry describing this variable.
   virtual std::string toString(void) const = 0; //!< override this to return appropriate string representation
diff -urdN ../Tekkotsu_2.3/Shared/WorldState.cc ./Shared/WorldState.cc
--- ../Tekkotsu_2.3/Shared/WorldState.cc	Tue Jan 11 18:49:23 2005
+++ ./Shared/WorldState.cc	Sun Jul 10 16:02:17 2005
@@ -300,7 +300,7 @@
 
 	//Apply sensor calibrations (currently only joint positions - perhaps IR as well?)
 	for(unsigned int i=0; i<NumPIDJoints; i++)
-		outputs[PIDJointOffset+i]/=config->motion.calibration[i];
+		outputs[PIDJointOffset+i]*=config->motion.calibration[i];
 
 	unsigned int dif=curtime-lastSensorUpdateTime;
 	lastSensorUpdateTime=curtime;
@@ -410,8 +410,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.29 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.30 $
  * $State: Exp $
- * $Date: 2005/01/11 23:49:23 $
+ * $Date: 2005/07/10 20:02:17 $
  */
diff -urdN ../Tekkotsu_2.3/Shared/WorldState.h ./Shared/WorldState.h
--- ../Tekkotsu_2.3/Shared/WorldState.h	Tue Jul 27 10:36:50 2004
+++ ./Shared/WorldState.h	Tue Jul 27 10:36:50 2004
@@ -214,7 +214,7 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.28 $
  * $State: Exp $
  * $Date: 2004/07/27 14:36:50 $
diff -urdN ../Tekkotsu_2.3/Shared/XMLLoadSave.cc ./Shared/XMLLoadSave.cc
--- ../Tekkotsu_2.3/Shared/XMLLoadSave.cc	Wed Dec 31 19:00:00 1969
+++ ./Shared/XMLLoadSave.cc	Wed Jul 27 01:58:24 2005
@@ -0,0 +1,354 @@
+#include "XMLLoadSave.h"
+#include <iostream>
+#include <string>
+#include <libxml/xmlmemory.h>
+#include <libxml/parser.h>
+#include <libxml/parserInternals.h>
+
+using namespace std;
+
+unsigned int XMLLoadSave::AutoInit::libxmlrefc=0;
+
+XMLLoadSave::AutoInit::AutoInit() {
+	if(libxmlrefc==0) {
+		//cout << "libxmlinit" << endl;
+		xmlInitParser();
+		xmlKeepBlanksDefault(1);
+		xmlLineNumbersDefault(1);
+		xmlIndentTreeOutput = 1;
+	}
+	libxmlrefc++;
+}
+
+XMLLoadSave::AutoInit::~AutoInit() {
+	libxmlrefc--;
+	if(libxmlrefc==0) {
+		xmlCleanupParser();
+		//cout << "libxmldest" << endl;
+	}
+}
+
+XMLLoadSave::XMLLoadSave()
+  : xmldocument(NULL), compressionLevel(-1), autoFormat(true), libxmlInit()
+{}
+
+XMLLoadSave::XMLLoadSave(const XMLLoadSave& xls)
+  : LoadSave(xls), xmldocument(xls.xmldocument==NULL?NULL:xmlCopyDoc(xls.xmldocument,true)), compressionLevel(xls.compressionLevel), autoFormat(xls.autoFormat), libxmlInit()
+{}
+
+XMLLoadSave& XMLLoadSave::operator=(const XMLLoadSave& xls) {
+	LoadSave::operator=(xls);
+	if(xls.xmldocument==NULL)
+		clearParseTree();
+	else
+		setParseTree(xmlCopyDoc(xls.xmldocument,true));
+	compressionLevel = xls.compressionLevel;
+	autoFormat=xls.autoFormat;
+	return *this;
+}
+
+XMLLoadSave::~XMLLoadSave() {
+	clearParseTree();
+}
+
+void XMLLoadSave::reportError(const std::string& context, const bad_format& err) const {
+	cerr << context << endl;
+	cerr << "  " << err.what() << endl;
+	if(err.getNode()!=NULL) {
+		xmlChar* path=xmlGetNodePath(err.getNode());
+		cerr << "  Error was flagged during processing of node at line " << xmlGetLineNo(err.getNode()) << ": " << path << " '" << xmlNodeGetContent(err.getNode()) << '\'' << endl;
+		xmlFree(path);
+	}
+}
+
+unsigned int XMLLoadSave::getBinSize() const {
+	try {
+		if(xmldocument==NULL)
+			setParseTree(xmlNewDoc((const xmlChar*)"1.0"));
+		if(compressionLevel>=0)
+			xmlSetDocCompressMode(xmldocument,compressionLevel);
+		xmlNode * cur = FindRootXMLElement(xmldocument);
+		SaveXML(cur);
+		xmlChar* buf=NULL;
+		int size=0;
+		xmlDocDumpFormatMemory(xmldocument, &buf, &size, autoFormat);
+		xmlFree(buf);
+		return size;
+	} catch(const bad_format& err) {
+		reportError("During calculation of size:",err);
+		return 0;
+	}
+}
+unsigned int XMLLoadSave::LoadBuffer(const char buf[], unsigned int len) {
+	if(xmldocument!=NULL)
+		xmlFreeDoc(xmldocument);
+	
+	//does actual low-level XML parsing
+	xmlParserCtxt* ctxt=xmlCreateMemoryParserCtxt(buf,len);
+	if(ctxt==NULL) {
+		cerr << "Error: XMLLoadSave could not create memory parser context" << endl;
+		return 0;
+	}
+	xmldocument = xmlParseDocument(ctxt)==0?ctxt->myDoc:NULL;
+	if (xmldocument == NULL ) {
+		cerr << "Error: XMLLoadSave buffer not parsed successfully. (xml syntax error)\n"
+		     << "       Attempting to recover..." << endl;
+		xmlFreeParserCtxt(ctxt);
+		ctxt=xmlCreateMemoryParserCtxt(buf,len);
+		if(ctxt==NULL) {
+			cerr << "Error: XMLLoadSave could not create memory parser context" << endl;
+			return 0;
+		}
+		ctxt->recovery=1;
+		xmldocument = xmlParseDocument(ctxt)==0?ctxt->myDoc:NULL;
+		if(xmldocument==NULL) {
+			cerr << "Error: XMLLoadSave recovery failed." << endl;
+			xmlFreeParserCtxt(ctxt);
+			return 0;
+		}
+	}
+	unsigned int size=ctxt->nbChars;
+	xmlFreeParserCtxt(ctxt);
+	
+	try {
+		xmlNodePtr cur = FindRootXMLElement(xmldocument);
+		LoadXML(cur);
+		return size;
+	} catch(const bad_format& err) {
+		reportError("During load of memory buffer:",err);
+		xmlFreeDoc(xmldocument);
+		xmldocument=NULL;
+		return 0;
+	}
+}
+unsigned int XMLLoadSave::SaveBuffer(char buf[], unsigned int len) const {
+	try {
+		if(xmldocument==NULL)
+			setParseTree(xmlNewDoc((const xmlChar*)"1.0"));
+		if(compressionLevel>=0)
+			xmlSetDocCompressMode(xmldocument,compressionLevel);
+		xmlNode * cur = FindRootXMLElement(xmldocument);
+		SaveXML(cur);
+		xmlChar* xbuf=NULL;
+		int size=0;
+		xmlDocDumpFormatMemory(xmldocument, &xbuf, &size, autoFormat);
+		if((unsigned int)size<=len)
+			memcpy(buf,xbuf,size);
+		else {
+			cerr << "Error: XMLLoadSave::SaveBuffer xmlDocDumpFormatMemory returned larger region than the target buffer" << endl;
+			size=0;
+		}
+		return size;
+	} catch(const bad_format& err) {
+		reportError("During save to memory buffer:",err);
+		return 0;
+	}
+}
+
+unsigned int XMLLoadSave::LoadFile(const char* filename) {
+	if(xmldocument!=NULL)
+		xmlFreeDoc(xmldocument);
+	
+	//does actual low-level XML parsing
+	xmlParserCtxt* ctxt=xmlCreateFileParserCtxt(filename);
+	if(ctxt==NULL) {
+		cerr << "Error: XMLLoadSave could not create parser context for '"<< filename << "'" << endl;
+		return 0;
+	}
+	xmldocument = xmlParseDocument(ctxt)==0?ctxt->myDoc:NULL;
+	if (xmldocument == NULL ) {
+		cerr << "Error: XMLLoadSave document '" << filename << "' not parsed successfully. (file not found or xml syntax error)\n"
+		<< "       Attempting to recover..." << endl;
+		xmlFreeParserCtxt(ctxt);
+		ctxt=xmlCreateFileParserCtxt(filename);
+		if(ctxt==NULL) {
+			cerr << "Error: XMLLoadSave could not create parser context for '"<< filename << "'" << endl;
+			return 0;
+		}
+		ctxt->recovery=1;
+		xmldocument = xmlParseDocument(ctxt)==0?ctxt->myDoc:NULL;
+		if(xmldocument==NULL) {
+			cerr << "Error: XMLLoadSave document '" << filename << "' recovery failed." << endl;
+			xmlFreeParserCtxt(ctxt);
+			return 0;
+		}
+	}
+	unsigned int size=ctxt->nbChars;
+	xmlFreeParserCtxt(ctxt);
+	
+	try {
+		xmlNodePtr cur = FindRootXMLElement(xmldocument);
+		LoadXML(cur);
+		return size;
+	} catch(const bad_format& err) {
+		string context("During load of '");
+		context+=filename;
+		context+="':";
+		reportError(context,err);
+		xmlFreeDoc(xmldocument);
+		xmldocument=NULL;
+		return 0;
+	}
+}
+unsigned int XMLLoadSave::SaveFile(const char* filename) const {
+	try {
+		if(xmldocument==NULL)
+			setParseTree(xmlNewDoc((const xmlChar*)"1.0"));
+		if(compressionLevel>=0)
+			xmlSetDocCompressMode(xmldocument,compressionLevel);
+		xmlNode * cur = FindRootXMLElement(xmldocument);
+		SaveXML(cur);
+		int size=xmlSaveFormatFile (filename, xmldocument, autoFormat);
+		if(size==-1)
+			cerr << "Error: XMLLoadSave::SaveFile: xmlSaveFormatFile(\"" << filename << "\",...) returned -1" << endl;
+		return size==-1?0:size;
+	} catch(const bad_format& err) {
+		string context("During save to '");
+		context+=filename;
+		context+="':";
+		reportError(context,err);
+		return 0;
+	}
+}
+
+unsigned int XMLLoadSave::LoadFileStream(FILE* f) {
+	if(xmldocument!=NULL)
+		xmlFreeDoc(xmldocument);
+	
+	//does actual low-level XML parsing
+	//This is a little sketchy trying to shoehorn a SAX style call, but it seems to work
+	xmlParserCtxt* ctxt=xmlCreateIOParserCtxt(NULL,NULL,fileReadCallback,fileCloseCallback,f,XML_CHAR_ENCODING_UTF8);
+	if(ctxt==NULL) {
+		cerr << "Error: XMLLoadSave could not create file stream parser context" << endl;
+		return 0;
+	}
+	ctxt->recovery=1;
+	xmldocument = xmlParseDocument(ctxt)==0?ctxt->myDoc:NULL;
+	unsigned int size=ctxt->nbChars;
+	bool wellFormed=ctxt->wellFormed;
+	xmlFreeParserCtxt(ctxt);
+	if (xmldocument == NULL ) {
+		cerr << "Error: XMLLoadSave file stream not parsed successfully. (xml syntax error)\n" << endl;
+		return 0;
+	}
+	if(!wellFormed)
+		cerr << "Warning: XMLLoadSave file stream was not well formed (but was recovered)." << endl;
+	
+	try {
+		xmlNodePtr cur = FindRootXMLElement(xmldocument);
+		LoadXML(cur);
+		return size;
+	} catch(const bad_format& err) {
+		reportError("During load of file stream:",err);
+		xmlFreeDoc(xmldocument);
+		xmldocument=NULL;
+		return 0;
+	}
+}
+unsigned int XMLLoadSave::SaveFileStream(FILE* f) const {
+	try {
+		if(xmldocument==NULL)
+			setParseTree(xmlNewDoc((const xmlChar*)"1.0"));
+		if(compressionLevel>=0)
+			xmlSetDocCompressMode(xmldocument,compressionLevel);
+		xmlNode * cur = FindRootXMLElement(xmldocument);
+		SaveXML(cur);
+		int size=xmlDocFormatDump(f, xmldocument, autoFormat);
+		if(size==-1)
+			cerr << "Error: XMLLoadSave::SaveFileStream: xmlDocFormatDump(...) returned -1" << endl;
+		return size==-1?0:size;
+	} catch(const bad_format& err) {
+		reportError("During save to file stream:",err);
+		return 0;
+	}
+}
+
+void XMLLoadSave::clearParseTree() {
+	xmlFreeDoc(xmldocument);
+	xmldocument=NULL;
+}
+void XMLLoadSave::setParseTree(xmlDoc* doc) const {
+	if(doc==xmldocument)
+		return;
+	xmlFreeDoc(xmldocument);
+	xmldocument=doc;
+}
+void XMLLoadSave::readParseTree() {
+	if(xmldocument==NULL)
+		return;
+	try {
+		xmlNodePtr cur = FindRootXMLElement(xmldocument);
+		LoadXML(cur);
+	} catch(const bad_format& err) {
+		reportError("During readParseTree:",err);
+		xmlFreeDoc(xmldocument);
+		xmldocument=NULL;
+	}
+}
+void XMLLoadSave::writeParseTree() {
+	try {
+		if(xmldocument==NULL)
+			setParseTree(xmlNewDoc((const xmlChar*)"1.0"));
+		if(compressionLevel>=0)
+			xmlSetDocCompressMode(xmldocument,compressionLevel);
+		xmlNode * cur = FindRootXMLElement(xmldocument);
+		SaveXML(cur);
+	} catch(const bad_format& err) {
+		reportError("During writeParseTree:",err);
+	}
+}
+
+void XMLLoadSave::setCompression(int level) {
+	compressionLevel=level;
+	if(xmldocument!=NULL)
+		xmlSetDocCompressMode(xmldocument,compressionLevel);
+}
+
+xmlNode* XMLLoadSave::FindRootXMLElement(xmlDoc* doc) const {
+	if(doc==NULL)
+		return NULL;
+	xmlNode* cur=xmlDocGetRootElement(doc);
+	if(cur==NULL) {
+		//empty file
+		cur = xmlNewNode(NULL,(const xmlChar*)"");
+		xmlDocSetRootElement(doc,cur);
+	} 
+	return cur;
+}
+
+int XMLLoadSave::fileReadCallback(void* f,char* buf, int len) {
+	return ferror((FILE*)f)?-1:(int)fread(buf,sizeof(char),len,(FILE*)f);
+}
+int XMLLoadSave::fileCloseCallback(void* f) {
+	return fclose((FILE*)f)==0?0:-1;
+}
+
+xmlNode* XMLLoadSave::skipToElement(xmlNode* cur) {
+	while(cur!=NULL && cur->type!=XML_ELEMENT_NODE)
+		cur=cur->next;
+	return cur;
+}
+
+xmlNode* XMLLoadSave::skipToElement(xmlNode* cur, std::string& comment) {
+	comment.clear();
+	while(cur!=NULL && cur->type!=XML_ELEMENT_NODE) {
+		if(cur->type==XML_COMMENT_NODE) {
+			xmlChar* cont=xmlNodeGetContent(cur);
+			comment+=(char*)cont;
+			xmlFree(cont);
+		}
+		cur=cur->next;
+	}
+	return cur;
+}
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/07/27 05:58:24 $
+ */
diff -urdN ../Tekkotsu_2.3/Shared/XMLLoadSave.h ./Shared/XMLLoadSave.h
--- ../Tekkotsu_2.3/Shared/XMLLoadSave.h	Wed Dec 31 19:00:00 1969
+++ ./Shared/XMLLoadSave.h	Sun Aug  7 00:11:04 2005
@@ -0,0 +1,142 @@
+//-*-c++-*-
+#ifndef INCLUDED_XMLLoadSave_h_
+#define INCLUDED_XMLLoadSave_h_
+
+#include "LoadSave.h"
+
+//!@name libxml2 forward declarations
+//!forward declaration of the libxml2 struct of the same name
+struct _xmlNode;
+struct _xmlDoc;
+struct _xmlAttr;
+typedef _xmlNode xmlNode;
+typedef _xmlDoc xmlDoc;
+typedef _xmlAttr xmlAttr;
+//@}
+
+//! XMLLoadSave adds functions for XML format serialization, although if you write binary LoadSave functions as well, you can do either
+class XMLLoadSave : public LoadSave {
+public:
+	
+	//! an exception to be thrown when a bad XML file is parsed, allows file position information to be passed to the user
+	class bad_format : std::exception {
+	public:
+		//!constructor
+		bad_format(xmlNode * node, const char * msg="invalid format in plist") throw() : std::exception(), node_(node), msg_(msg) {}
+		//!copy constructor
+		bad_format(const bad_format& bf) : std::exception(bf), node_(bf.node_), msg_(bf.msg_) {}
+		//!assignment
+		bad_format& operator=(const bad_format& bf) { std::exception::operator=(bf); node_=bf.node_; msg_=bf.msg_; return *this; }
+		virtual ~bad_format() throw() {} //!< destructor
+		virtual const char * what() const throw() { return msg_; } //!< standard interface for getting the exception's message string
+		virtual xmlNode * getNode() const throw() { return node_; } //!< returns the xmlNode at which the error occurred
+	protected:
+		xmlNode * node_; //!< the node of the error
+		const char * msg_; //!< message regarding the type of error
+	};
+	
+	XMLLoadSave(); //!< constructor
+	XMLLoadSave(const XMLLoadSave& xls); //!< copy constructor
+	XMLLoadSave& operator=(const XMLLoadSave& xls); //!< assignment operator
+	virtual ~XMLLoadSave(); //!< destructor
+	
+	//! This is called when the subclass needs to update its values from those values in the parse tree
+	/*! @a node is the current node in the tree -- it may be the root, but it
+	 *  may also be a subnode within the tree if a recursive structure is used */
+	virtual void LoadXML(xmlNode* node)=0;
+	//! This is called when XMLLoadSave needs to have the subclass update values in the tree currently in memory -- may already be filled out by previous contents
+	/*! @a node is the current node in the tree -- it may be the root, but it
+	 *  may also be a subnode within the tree if a recursive structure is used */
+	virtual void SaveXML(xmlNode * node) const=0;
+	
+	virtual unsigned int getBinSize() const;
+	virtual unsigned int LoadBuffer(const char buf[], unsigned int len);
+	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
+
+	virtual	unsigned int LoadFile(const char* filename);
+	virtual unsigned int SaveFile(const char* filename) const;
+	
+	virtual unsigned int LoadFileStream(FILE* f);
+	virtual unsigned int SaveFileStream(FILE* f) const;
+	
+	//! resets the parse tree currently in memory so that a future save will write a "fresh" copy from scratch.
+	/*! You may also want to call this in order to save memory after a Load so that
+	 *  the parse tree information isn't retained in memory if you don't care about
+	 *  retaining the file formatting */
+	virtual void clearParseTree();
+
+	//! assigns a parse tree which you have obtained from some other source
+	/*! This doesn't update the contents of the subclass's values.  The values in
+	 *  @a doc will be overwritten by those in the subclass on the next Save.
+	 *  If you wish to have the subclass's values updated from @a doc, call
+	 *  readParseTree() after calling this. */
+	virtual void setParseTree(xmlDoc* doc) const;
+	
+	//! returns the current parse tree, either from a previous Load, Save, or setParseTree()
+	virtual xmlDoc* getParseTree() const { return xmldocument; }
+	
+	//! calls LoadXML with the root of the current parse tree
+	virtual void readParseTree();
+	//! calls SaveXML with the root of the current parse tree
+	virtual void writeParseTree();
+	
+	//! allows you to set the compression level used by libxml2 -- this corresponds to the compression level setting of zlib, i.e. 0-9
+	virtual void setCompression(int level);
+	//! returns the current compression level setting used by libxml2 (via zlib)
+	virtual int getCompression() const { return compressionLevel; }
+	
+protected:
+	//! returns the root element of the xml document
+	virtual xmlNode* FindRootXMLElement(xmlDoc* doc) const;
+
+	//! cleans up after an error occurs and sends a message to cerr
+	void reportError(const std::string& context, const bad_format& err) const;
+
+	//! called by libxml2 when it's ready for more data to be read from the source (in this case, a file)
+	static int fileReadCallback(void* f,char* buf, int len);
+
+	//! called by libxml2 when it's done reading data
+	static int fileCloseCallback(void* f);
+
+	//! returns the next element following @a cur
+	/*! You should call this with node->next, otherwise you'll just keep getting the same node back again */
+	static xmlNode* skipToElement(xmlNode* cur);
+
+	//! returns the next element following @a cur; comment is set to the concatination of any comments is encountered in the interim
+	/*! You should call this with node->next, otherwise you'll just keep getting the same node back again */
+	static xmlNode* skipToElement(xmlNode* cur, std::string& comment);
+
+	//! the cached xml parse tree -- contains additional formatting information such as white space and comments
+	mutable xmlDoc* xmldocument;
+
+	//! the current compression level, or level to be used for the next save
+	int compressionLevel;
+	
+	//! if true, the saved document will use automatic indenting and formatting
+	bool autoFormat;
+
+	//static const char * const base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+	
+	//! allows automatic (de)initialization of libxml when the first or last XMLLoadSave class is created or destroyed
+	class AutoInit {
+	public:
+		AutoInit(); //!< if #libxmlrefc is 0, calls libxml2 initialization and configuration functions
+		~AutoInit(); //!< if #libxmlrefc is 1, calls libxml2 destruction functions
+	protected:
+		static unsigned int libxmlrefc; //!< current number of XMLLoadSave subclass instances
+	} libxmlInit; //!< allows tracking of libxml usage so the library can be initialized and destructed automatically
+	
+};
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:04 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Shared/debuget.h ./Shared/debuget.h
--- ../Tekkotsu_2.3/Shared/debuget.h	Thu Sep 25 11:31:53 2003
+++ ./Shared/debuget.h	Sun Aug  7 00:11:04 2005
@@ -68,30 +68,79 @@
 	}
 }
 
+//! displays hex and ascii values of @a size bytes from @a p
+inline void hexout2(const void* p, size_t size) {
+	const char* buf=static_cast<const char*>(p);
+	unsigned int prev_line=0;
+	const unsigned int cols=4;
+	const unsigned int n_per_col=4;
+	printf("Base: %p\n",buf);
+	for(unsigned int i=0; i<size; i++) {
+		if(i%(cols*n_per_col)==0)
+			printf("%6u  |",i);
+		printf("%02hx",buf[i]);
+		if((i+1)%(cols*n_per_col)==0) {
+			printf("|  ");
+			for(unsigned int j=prev_line; j<=i; j++)
+				printf("%c",isprint(buf[j])?buf[j]:'.');
+			prev_line=i+1;
+			printf("\n");
+		} else if((i+1)%(n_per_col)==0)
+			printf(" ");
+	}
+	for(unsigned int i=size; i%(cols*n_per_col)!=0; i++) {
+		printf("  ");
+		if((i+1)%(cols*n_per_col)==0) {
+			printf("|  ");
+			for(unsigned int j=prev_line; j<size; j++)
+				printf("%c",isprint(buf[j])?buf[j]:'.');
+			prev_line=i;
+			printf("\n");
+		} else if((i+1)%(n_per_col)==0)
+			printf(" ");
+	}
+}
+
+#include <ctype.h>
+
+//! displays hex and ascii values of @a size bytes from @a p
+inline void hexout3(const char* buf, size_t size) {
+	const unsigned int linelen=24;
+	for(unsigned int i=0; i<size; i++) {
+		printf("%.2hx",buf[i]);
+		if((i+1)%linelen==0) {
+			printf("   ");
+			for(unsigned int j=i+1-linelen; j<=i; j++)
+				putchar(isprint(buf[j])?buf[j]:'.');
+			printf("\n");
+		} else if((i+1)%4==0)
+			printf(" ");
+	}
+	//finish off the last line (still need to do human-readable version)
+	for(unsigned int i=size; i%linelen!=0; i++) {
+		printf("  ");
+		if((i+1)%linelen==0) {
+			printf("   ");
+			for(unsigned int j=(size/linelen)*linelen; j<size; j++)
+				putchar(isprint(buf[j])?buf[j]:'.');
+			printf("\n");
+		} else if((i+1)%4==0)
+			printf(" ");
+	}
+}
+
 /*! @file
  * @brief Defines several debugging functions and macros, including ::ASSERT (and variations)
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.2 $
- * $State: Rel $
- * $Date: 2003/09/25 15:31:53 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:04 $
+ * $Revision: 1.6 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:04 $
  */
-
-// static void hexout(unsigned int in) {
-//   char buf;
-//   std::cout << "0x";
-//   if (in == 0) std::cout << "0";
-//   else {
-//     while (in != 0) {
-//       if (in % 16 > 9) buf = 'A' + in % 16 - 9;
-//       else buf = '0' + in % 16;
-//       std::cout << buf;
-//       in /= 16;
-//     }
-//   }
-//   std::cout << std::endl;
-// }
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/get_time.cc ./Shared/get_time.cc
--- ../Tekkotsu_2.3/Shared/get_time.cc	Fri Jul 25 16:18:07 2003
+++ ./Shared/get_time.cc	Wed Jun  1 01:47:49 2005
@@ -1,17 +1,22 @@
 #include "get_time.h"
 
-#ifndef PLATFORM_APERIOS
-extern unsigned int simulator_time; //!< the current time the simulator wants it to be
-unsigned int get_time() {
-  return simulator_time;
-}
-#else
+#ifdef PLATFORM_APERIOS
 #include <MCOOP.h>
 unsigned int get_time() {
   static struct SystemTime time;
   GetSystemTime(&time);
   return time.seconds*1000+time.useconds/1000;
 }
+#else
+#include "TimeET.h"
+namespace project_get_time {
+	unsigned int simulation_time=-1U;
+	unsigned int default_get_time_callback() {
+		static TimeET first;
+		return static_cast<unsigned int>(first.Age().Value()*1000);
+	}
+	unsigned int (*get_time_callback)()=&default_get_time_callback;
+}
 #endif
 
 /*! @file
@@ -19,8 +24,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/07/25 20:18:07 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:49 $
  */
diff -urdN ../Tekkotsu_2.3/Shared/get_time.h ./Shared/get_time.h
--- ../Tekkotsu_2.3/Shared/get_time.h	Fri Jul 25 16:18:08 2003
+++ ./Shared/get_time.h	Tue Jun 14 18:11:46 2005
@@ -1,18 +1,48 @@
 #ifndef INCLUDED_get_time_h
 #define INCLUDED_get_time_h
 
+#ifdef PLATFORM_APERIOS
+
 //!a simple way to get the current time since boot in milliseconds (see TimeET for better accuracy)
 unsigned int get_time();
 
+#else //PLATFORM_LOCAL
+
+//! If we're running locally, these will let users in "project" space control time for simulation
+namespace project_get_time {
+	//! This will default to -1, which signals get_time() to use get_time_callback.  Any other value will cause that value to be used instead.
+	extern unsigned int simulation_time;
+	//! This by default will return the time in milliseconds since the first call was made.  Note this is a function pointer, so you can reassign it to your own implementation!
+	/*! For instance, the simulator can assign a function which forwards
+	 *  the call to SharedGlobals::get_time(), so that all processes get
+	 *  consistent time values under control of the simulator */
+	extern unsigned int (*get_time_callback)();
+}
+
+//! This will call and return project_get_time::get_time_callback if project_get_time::simulation_time is -1.  Otherwise simulation_time is returned.
+/*! Default values are set such that the system clock will be used,
+ *  and values will range from 0 (first call) onward.   However, by
+ *  reassigning project_get_time::get_time_callback to your own
+ *  function, you can control the flow of time however you wish. */
+inline unsigned int get_time() {
+	if(project_get_time::simulation_time==-1U)
+		return (*project_get_time::get_time_callback)();
+	else
+		return project_get_time::simulation_time;
+}
+
+#endif
+
+
 /*! @file
  * @brief prototype for get_time(), a simple way to get the current time since boot in milliseconds
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.2 $
- * $State: Rel $
- * $Date: 2003/07/25 20:18:08 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/06/14 22:11:46 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/ADDED.txt ./Shared/jpeg-6b/ADDED.txt
--- ../Tekkotsu_2.3/Shared/jpeg-6b/ADDED.txt	Mon Dec  1 12:30:32 2003
+++ ./Shared/jpeg-6b/ADDED.txt	Wed Dec 31 19:00:00 1969
@@ -1,4 +0,0 @@
-jpeg_mem_dest.c
-jpeg_mem_dest.h
-write_jpeg.c
-write_jpeg.h
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Entries ./Shared/jpeg-6b/CVS/Entries
--- ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Shared/jpeg-6b/CVS/Entries	Wed Aug 10 11:03:20 2005
@@ -0,0 +1,5 @@
+/jpeg_mem_dest.cc/1.2/Wed Jun  1 05:47:52 2005//Ttekkotsu-2_4
+/jpeg_mem_dest.h/1.3/Wed Jun  1 05:47:52 2005//Ttekkotsu-2_4
+/write_jpeg.cc/1.2/Wed Jun  1 05:47:53 2005//Ttekkotsu-2_4
+/write_jpeg.h/1.1/Mon Dec  1 17:30:41 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Repository ./Shared/jpeg-6b/CVS/Repository
--- ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Shared/jpeg-6b/CVS/Repository	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+Tekkotsu/Shared/jpeg-6b
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Root ./Shared/jpeg-6b/CVS/Root
--- ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Shared/jpeg-6b/CVS/Root	Wed Aug 10 11:03:19 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Tag ./Shared/jpeg-6b/CVS/Tag
--- ../Tekkotsu_2.3/Shared/jpeg-6b/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Shared/jpeg-6b/CVS/Tag	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/Makefile ./Shared/jpeg-6b/Makefile
--- ../Tekkotsu_2.3/Shared/jpeg-6b/Makefile	Tue Nov  9 16:26:13 2004
+++ ./Shared/jpeg-6b/Makefile	Wed Dec 31 19:00:00 1969
@@ -1,236 +0,0 @@
-# Makefile for Independent JPEG Group's software
-
-# This makefile is suitable for Unix-like systems with non-ANSI compilers.
-# If you have an ANSI compiler, makefile.ansi is a better starting point.
-
-ifndef TEKKOTSU_ENVIRONMENT_CONFIGURATION
-$(error An error has occured, TEKKOTSU_ENVIRONMENT_CONFIGURATION was not defined)
-endif
-include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
-FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(FILTERSYSWARN))
-COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(COLORFILT))
-BUILDDIR=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(TK_BD)/Shared/jpeg-6b)
-SRCSUFFIX=.c
-
-# You may need to adjust these cc options:
-CFLAGS= -O3 -frename-registers -fomit-frame-pointer -ffast-math -fno-common
-# Generally, we recommend defining any configuration symbols in jconfig.h,
-# NOT via -D switches here.
-# However, any special defines for ansi2knr.c may be included here:
-ANSI2KNRFLAGS= 
-
-# Link-time cc options:
-LDFLAGS=
-
-# To link any special libraries, add the necessary -l commands here.
-LDLIBS= 
-
-# Put here the object file name for the correct system-dependent memory
-# manager file.  For Unix this is usually jmemnobs.o, but you may want
-# to use jmemansi.o or jmemname.o if you have limited swap space.
-SYSDEPMEM= jmemnobs.o
-
-# miscellaneous OS-dependent stuff
-# linker
-LN= $(CC)
-# file deletion command
-RM= rm -f
-# file rename command
-MV= mv
-
-# End of configurable options.
-
-
-# source files: JPEG library proper
-LIBSOURCES= jcapimin.c jcapistd.c jccoefct.c jccolor.c jcdctmgr.c jchuff.c \
-        jcinit.c jcmainct.c jcmarker.c jcmaster.c jcomapi.c jcparam.c \
-        jcphuff.c jcprepct.c jcsample.c jctrans.c jdapimin.c jdapistd.c \
-        jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c jddctmgr.c jdhuff.c \
-        jdinput.c jdmainct.c jdmarker.c jdmaster.c jdmerge.c jdphuff.c \
-        jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c jfdctfst.c \
-        jfdctint.c jidctflt.c jidctfst.c jidctint.c jidctred.c jquant1.c \
-        jquant2.c jutils.c jmemmgr.c
-# memmgr back ends: compile only one of these into a working library
-SYSDEPSOURCES= jmemansi.c jmemname.c jmemnobs.c jmemdos.c jmemmac.c
-# source files: cjpeg/djpeg/jpegtran applications, also rdjpgcom/wrjpgcom
-APPSOURCES= cjpeg.c djpeg.c jpegtran.c rdjpgcom.c wrjpgcom.c cdjpeg.c \
-        rdcolmap.c rdswitch.c transupp.c rdppm.c wrppm.c rdgif.c wrgif.c \
-        rdtarga.c wrtarga.c rdbmp.c wrbmp.c rdrle.c wrrle.c
-SONYSOURCES= jpeg_mem_dest.c write_jpeg.c
-SOURCES= $(LIBSOURCES) $(SYSDEPSOURCES) $(APPSOURCES) $(SONYSOURCES)
-# files included by source files
-INCLUDES= jchuff.h jdhuff.h jdct.h jerror.h jinclude.h jmemsys.h jmorecfg.h \
-        jpegint.h jpeglib.h jversion.h cdjpeg.h cderror.h transupp.h
-# documentation, test, and support files
-DOCS= README install.doc usage.doc cjpeg.1 djpeg.1 jpegtran.1 rdjpgcom.1 \
-        wrjpgcom.1 wizard.doc example.c libjpeg.doc structure.doc \
-        coderules.doc filelist.doc change.log
-MKFILES= configure makefile.cfg makefile.ansi makefile.unix makefile.bcc \
-        makefile.mc6 makefile.dj makefile.wat makefile.vc makelib.ds \
-        makeapps.ds makeproj.mac makcjpeg.st makdjpeg.st makljpeg.st \
-        maktjpeg.st makefile.manx makefile.sas makefile.mms makefile.vms \
-        makvms.opt
-CONFIGFILES= jconfig.cfg jconfig.bcc jconfig.mc6 jconfig.dj jconfig.wat \
-        jconfig.vc jconfig.mac jconfig.st jconfig.manx jconfig.sas \
-        jconfig.vms
-CONFIGUREFILES= config.guess config.sub install-sh ltconfig ltmain.sh
-OTHERFILES= jconfig.doc ckconfig.c ansi2knr.c ansi2knr.1 jmemdosa.asm
-TESTFILES= testorig.jpg testimg.ppm testimg.bmp testimg.jpg testprog.jpg \
-        testimgp.jpg
-DISTFILES= $(DOCS) $(MKFILES) $(CONFIGFILES) $(SOURCES) $(INCLUDES) \
-        $(CONFIGUREFILES) $(OTHERFILES) $(TESTFILES)
-# library object files common to compression and decompression
-COMOBJECTS= jcomapi.o jutils.o jerror.o jmemmgr.o $(SYSDEPMEM)
-# compression library object files
-CLIBOBJECTS= jcapimin.o jcapistd.o jctrans.o jcparam.o jdatadst.o jcinit.o \
-        jcmaster.o jcmarker.o jcmainct.o jcprepct.o jccoefct.o jccolor.o \
-        jcsample.o jchuff.o jcphuff.o jcdctmgr.o jfdctfst.o jfdctflt.o \
-        jfdctint.o
-# decompression library object files
-DLIBOBJECTS= jdapimin.o jdapistd.o jdtrans.o jdatasrc.o jdmaster.o \
-        jdinput.o jdmarker.o jdhuff.o jdphuff.o jdmainct.o jdcoefct.o \
-        jdpostct.o jddctmgr.o jidctfst.o jidctflt.o jidctint.o jidctred.o \
-        jdsample.o jdcolor.o jquant1.o jquant2.o jdmerge.o
-# These objectfiles are included in libjpeg.a
-LIBOBJECTS= $(addprefix $(BUILDDIR)/,$(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS) $(SONYSOURCES:.c=.o))
-# object files for sample applications (excluding library files)
-COBJECTS= cjpeg.o rdppm.o rdgif.o rdtarga.o rdrle.o rdbmp.o rdswitch.o \
-        cdjpeg.o
-DOBJECTS= djpeg.o wrppm.o wrgif.o wrtarga.o wrrle.o wrbmp.o rdcolmap.o \
-        cdjpeg.o
-TROBJECTS= jpegtran.o rdswitch.o cdjpeg.o transupp.o
-
-
-all: $(BUILDDIR)/libjpeg.a
-
-.PHONY: all clean
-
-# This rule [no longer] causes ansi2knr to be invoked.
-%.o:
-	@mkdir -p $(dir $@)
-	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(BUILDDIR)/%,%,$@)); \
-	echo "Compiling libjpeg::$$src... (Reduced warnings)"; \
-	$(CC) $(CFLAGS) -o $@ -c $$src > $*.log 2>&1; \
-	retval=$$?; \
-	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
-	test $$retval -eq 0;
-
-ansi2knr: ansi2knr.c
-	$(CC) $(CFLAGS) $(ANSI2KNRFLAGS) -o ansi2knr ansi2knr.c
-
-$(BUILDDIR)/libjpeg.a: $(LIBOBJECTS)
-	$(RM) $@
-	@echo "Linking $@..."
-	@$(AR) $@  $(LIBOBJECTS)
-	@$(AR2) $@
-
-cjpeg: ansi2knr $(COBJECTS) libjpeg.a
-	$(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) libjpeg.a $(LDLIBS)
-
-djpeg: ansi2knr $(DOBJECTS) libjpeg.a
-	$(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) libjpeg.a $(LDLIBS)
-
-jpegtran: ansi2knr $(TROBJECTS) libjpeg.a
-	$(LN) $(LDFLAGS) -o jpegtran $(TROBJECTS) libjpeg.a $(LDLIBS)
-
-rdjpgcom: rdjpgcom.o
-	$(LN) $(LDFLAGS) -o rdjpgcom rdjpgcom.o $(LDLIBS)
-
-wrjpgcom: wrjpgcom.o
-	$(LN) $(LDFLAGS) -o wrjpgcom wrjpgcom.o $(LDLIBS)
-
-jconfig.h: jconfig.doc
-	echo You must prepare a system-dependent jconfig.h file.
-	echo Please read the installation directions in install.doc.
-	exit 1
-
-clean:
-	$(RM) *.o libjpeg.a core testout*
-#	$(RM) *.o cjpeg djpeg jpegtran libjpeg.a rdjpgcom wrjpgcom
-#	$(RM) ansi2knr core testout*
-
-test: cjpeg djpeg jpegtran
-	$(RM) testout*
-	./djpeg -dct int -ppm -outfile testout.ppm  testorig.jpg
-	./djpeg -dct int -bmp -colors 256 -outfile testout.bmp  testorig.jpg
-	./cjpeg -dct int -outfile testout.jpg  testimg.ppm
-	./djpeg -dct int -ppm -outfile testoutp.ppm testprog.jpg
-	./cjpeg -dct int -progressive -opt -outfile testoutp.jpg testimg.ppm
-	./jpegtran -outfile testoutt.jpg testprog.jpg
-	cmp testimg.ppm testout.ppm
-	cmp testimg.bmp testout.bmp
-	cmp testimg.jpg testout.jpg
-	cmp testimg.ppm testoutp.ppm
-	cmp testimgp.jpg testoutp.jpg
-	cmp testorig.jpg testoutt.jpg
-
-
-$(BUILDDIR)/jcapimin.o: jcapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcapistd.o: jcapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jccoefct.o: jccoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jccolor.o: jccolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcdctmgr.o: jcdctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jchuff.o: jchuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
-$(BUILDDIR)/jcinit.o: jcinit.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcmainct.o: jcmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcmarker.o: jcmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcmaster.o: jcmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcomapi.o: jcomapi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcparam.o: jcparam.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcphuff.o: jcphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jchuff.h
-$(BUILDDIR)/jcprepct.o: jcprepct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jcsample.o: jcsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jctrans.o: jctrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdapimin.o: jdapimin.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdapistd.o: jdapistd.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdatadst.o: jdatadst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
-$(BUILDDIR)/jdatasrc.o: jdatasrc.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h
-$(BUILDDIR)/jdcoefct.o: jdcoefct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdcolor.o: jdcolor.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jddctmgr.o: jddctmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jdhuff.o: jdhuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
-$(BUILDDIR)/jdinput.o: jdinput.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdmainct.o: jdmainct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdmarker.o: jdmarker.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdmaster.o: jdmaster.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdmerge.o: jdmerge.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdphuff.o: jdphuff.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdhuff.h
-$(BUILDDIR)/jdpostct.o: jdpostct.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdsample.o: jdsample.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jdtrans.o: jdtrans.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jerror.o: jerror.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jversion.h jerror.h
-$(BUILDDIR)/jfdctflt.o: jfdctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jfdctfst.o: jfdctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jfdctint.o: jfdctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jidctflt.o: jidctflt.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jidctfst.o: jidctfst.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jidctint.o: jidctint.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jidctred.o: jidctred.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jdct.h
-$(BUILDDIR)/jquant1.o: jquant1.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jquant2.o: jquant2.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jutils.o: jutils.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h
-$(BUILDDIR)/jmemmgr.o: jmemmgr.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
-$(BUILDDIR)/jmemansi.o: jmemansi.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
-$(BUILDDIR)/jmemname.o: jmemname.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
-$(BUILDDIR)/jmemnobs.o: jmemnobs.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
-$(BUILDDIR)/jmemdos.o: jmemdos.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
-$(BUILDDIR)/jmemmac.o: jmemmac.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h jmemsys.h
-$(BUILDDIR)/cjpeg.o: cjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h $(BUILDDIR)/jversion.h
-$(BUILDDIR)/djpeg.o: djpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h $(BUILDDIR)/jversion.h
-$(BUILDDIR)/jpegtran.o: jpegtran.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h $(BUILDDIR)/transupp.h jversion.h
-$(BUILDDIR)/rdjpgcom.o: rdjpgcom.c jinclude.h jconfig.h
-$(BUILDDIR)/wrjpgcom.o: wrjpgcom.c jinclude.h jconfig.h
-$(BUILDDIR)/cdjpeg.o: cdjpeg.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/rdcolmap.o: rdcolmap.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/rdswitch.o: rdswitch.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/transupp.o: transupp.c jinclude.h jconfig.h jpeglib.h jmorecfg.h jpegint.h jerror.h $(BUILDDIR)/transupp.h
-$(BUILDDIR)/rdppm.o: rdppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/wrppm.o: wrppm.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/rdgif.o: rdgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/wrgif.o: wrgif.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/rdtarga.o: rdtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/wrtarga.o: wrtarga.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/rdbmp.o: rdbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/wrbmp.o: wrbmp.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/rdrle.o: rdrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
-$(BUILDDIR)/wrrle.o: wrrle.c cdjpeg.h jinclude.h jconfig.h jpeglib.h jmorecfg.h jerror.h cderror.h
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/README ./Shared/jpeg-6b/README
--- ../Tekkotsu_2.3/Shared/jpeg-6b/README	Mon Dec  1 12:30:32 2003
+++ ./Shared/jpeg-6b/README	Wed Dec 31 19:00:00 1969
@@ -1,385 +0,0 @@
-The Independent JPEG Group's JPEG software
-==========================================
-
-README for release 6b of 27-Mar-1998
-====================================
-
-This distribution contains the sixth public release of the Independent JPEG
-Group's free JPEG software.  You are welcome to redistribute this software and
-to use it for any purpose, subject to the conditions under LEGAL ISSUES, below.
-
-Serious users of this software (particularly those incorporating it into
-larger programs) should contact IJG at jpeg-info@uunet.uu.net to be added to
-our electronic mailing list.  Mailing list members are notified of updates
-and have a chance to participate in technical discussions, etc.
-
-This software is the work of Tom Lane, Philip Gladstone, Jim Boucher,
-Lee Crocker, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi,
-Guido Vollbeding, Ge' Weijers, and other members of the Independent JPEG
-Group.
-
-IJG is not affiliated with the official ISO JPEG standards committee.
-
-
-DOCUMENTATION ROADMAP
-=====================
-
-This file contains the following sections:
-
-OVERVIEW            General description of JPEG and the IJG software.
-LEGAL ISSUES        Copyright, lack of warranty, terms of distribution.
-REFERENCES          Where to learn more about JPEG.
-ARCHIVE LOCATIONS   Where to find newer versions of this software.
-RELATED SOFTWARE    Other stuff you should get.
-FILE FORMAT WARS    Software *not* to get.
-TO DO               Plans for future IJG releases.
-
-Other documentation files in the distribution are:
-
-User documentation:
-  install.doc       How to configure and install the IJG software.
-  usage.doc         Usage instructions for cjpeg, djpeg, jpegtran,
-                    rdjpgcom, and wrjpgcom.
-  *.1               Unix-style man pages for programs (same info as usage.doc).
-  wizard.doc        Advanced usage instructions for JPEG wizards only.
-  change.log        Version-to-version change highlights.
-Programmer and internal documentation:
-  libjpeg.doc       How to use the JPEG library in your own programs.
-  example.c         Sample code for calling the JPEG library.
-  structure.doc     Overview of the JPEG library's internal structure.
-  filelist.doc      Road map of IJG files.
-  coderules.doc     Coding style rules --- please read if you contribute code.
-
-Please read at least the files install.doc and usage.doc.  Useful information
-can also be found in the JPEG FAQ (Frequently Asked Questions) article.  See
-ARCHIVE LOCATIONS below to find out where to obtain the FAQ article.
-
-If you want to understand how the JPEG code works, we suggest reading one or
-more of the REFERENCES, then looking at the documentation files (in roughly
-the order listed) before diving into the code.
-
-
-OVERVIEW
-========
-
-This package contains C software to implement JPEG image compression and
-decompression.  JPEG (pronounced "jay-peg") is a standardized compression
-method for full-color and gray-scale images.  JPEG is intended for compressing
-"real-world" scenes; line drawings, cartoons and other non-realistic images
-are not its strong suit.  JPEG is lossy, meaning that the output image is not
-exactly identical to the input image.  Hence you must not use JPEG if you
-have to have identical output bits.  However, on typical photographic images,
-very good compression levels can be obtained with no visible change, and
-remarkably high compression levels are possible if you can tolerate a
-low-quality image.  For more details, see the references, or just experiment
-with various compression settings.
-
-This software implements JPEG baseline, extended-sequential, and progressive
-compression processes.  Provision is made for supporting all variants of these
-processes, although some uncommon parameter settings aren't implemented yet.
-For legal reasons, we are not distributing code for the arithmetic-coding
-variants of JPEG; see LEGAL ISSUES.  We have made no provision for supporting
-the hierarchical or lossless processes defined in the standard.
-
-We provide a set of library routines for reading and writing JPEG image files,
-plus two sample applications "cjpeg" and "djpeg", which use the library to
-perform conversion between JPEG and some other popular image file formats.
-The library is intended to be reused in other applications.
-
-In order to support file conversion and viewing software, we have included
-considerable functionality beyond the bare JPEG coding/decoding capability;
-for example, the color quantization modules are not strictly part of JPEG
-decoding, but they are essential for output to colormapped file formats or
-colormapped displays.  These extra functions can be compiled out of the
-library if not required for a particular application.  We have also included
-"jpegtran", a utility for lossless transcoding between different JPEG
-processes, and "rdjpgcom" and "wrjpgcom", two simple applications for
-inserting and extracting textual comments in JFIF files.
-
-The emphasis in designing this software has been on achieving portability and
-flexibility, while also making it fast enough to be useful.  In particular,
-the software is not intended to be read as a tutorial on JPEG.  (See the
-REFERENCES section for introductory material.)  Rather, it is intended to
-be reliable, portable, industrial-strength code.  We do not claim to have
-achieved that goal in every aspect of the software, but we strive for it.
-
-We welcome the use of this software as a component of commercial products.
-No royalty is required, but we do ask for an acknowledgement in product
-documentation, as described under LEGAL ISSUES.
-
-
-LEGAL ISSUES
-============
-
-In plain English:
-
-1. We don't promise that this software works.  (But if you find any bugs,
-   please let us know!)
-2. You can use this software for whatever you want.  You don't have to pay us.
-3. You may not pretend that you wrote this software.  If you use it in a
-   program, you must acknowledge somewhere in your documentation that
-   you've used the IJG code.
-
-In legalese:
-
-The authors make NO WARRANTY or representation, either express or implied,
-with respect to this software, its quality, accuracy, merchantability, or
-fitness for a particular purpose.  This software is provided "AS IS", and you,
-its user, assume the entire risk as to its quality and accuracy.
-
-This software is copyright (C) 1991-1998, Thomas G. Lane.
-All Rights Reserved except as specified below.
-
-Permission is hereby granted to use, copy, modify, and distribute this
-software (or portions thereof) for any purpose, without fee, subject to these
-conditions:
-(1) If any part of the source code for this software is distributed, then this
-README file must be included, with this copyright and no-warranty notice
-unaltered; and any additions, deletions, or changes to the original files
-must be clearly indicated in accompanying documentation.
-(2) If only executable code is distributed, then the accompanying
-documentation must state that "this software is based in part on the work of
-the Independent JPEG Group".
-(3) Permission for use of this software is granted only if the user accepts
-full responsibility for any undesirable consequences; the authors accept
-NO LIABILITY for damages of any kind.
-
-These conditions apply to any software derived from or based on the IJG code,
-not just to the unmodified library.  If you use our work, you ought to
-acknowledge us.
-
-Permission is NOT granted for the use of any IJG author's name or company name
-in advertising or publicity relating to this software or products derived from
-it.  This software may be referred to only as "the Independent JPEG Group's
-software".
-
-We specifically permit and encourage the use of this software as the basis of
-commercial products, provided that all warranty or liability claims are
-assumed by the product vendor.
-
-
-ansi2knr.c is included in this distribution by permission of L. Peter Deutsch,
-sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA.
-ansi2knr.c is NOT covered by the above copyright and conditions, but instead
-by the usual distribution terms of the Free Software Foundation; principally,
-that you must include source code if you redistribute it.  (See the file
-ansi2knr.c for full details.)  However, since ansi2knr.c is not needed as part
-of any program generated from the IJG code, this does not limit you more than
-the foregoing paragraphs do.
-
-The Unix configuration script "configure" was produced with GNU Autoconf.
-It is copyright by the Free Software Foundation but is freely distributable.
-The same holds for its supporting scripts (config.guess, config.sub,
-ltconfig, ltmain.sh).  Another support script, install-sh, is copyright
-by M.I.T. but is also freely distributable.
-
-It appears that the arithmetic coding option of the JPEG spec is covered by
-patents owned by IBM, AT&T, and Mitsubishi.  Hence arithmetic coding cannot
-legally be used without obtaining one or more licenses.  For this reason,
-support for arithmetic coding has been removed from the free JPEG software.
-(Since arithmetic coding provides only a marginal gain over the unpatented
-Huffman mode, it is unlikely that very many implementations will support it.)
-So far as we are aware, there are no patent restrictions on the remaining
-code.
-
-The IJG distribution formerly included code to read and write GIF files.
-To avoid entanglement with the Unisys LZW patent, GIF reading support has
-been removed altogether, and the GIF writer has been simplified to produce
-"uncompressed GIFs".  This technique does not use the LZW algorithm; the
-resulting GIF files are larger than usual, but are readable by all standard
-GIF decoders.
-
-We are required to state that
-    "The Graphics Interchange Format(c) is the Copyright property of
-    CompuServe Incorporated.  GIF(sm) is a Service Mark property of
-    CompuServe Incorporated."
-
-
-REFERENCES
-==========
-
-We highly recommend reading one or more of these references before trying to
-understand the innards of the JPEG software.
-
-The best short technical introduction to the JPEG compression algorithm is
-	Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
-	Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
-(Adjacent articles in that issue discuss MPEG motion picture compression,
-applications of JPEG, and related topics.)  If you don't have the CACM issue
-handy, a PostScript file containing a revised version of Wallace's article is
-available at ftp://ftp.uu.net/graphics/jpeg/wallace.ps.gz.  The file (actually
-a preprint for an article that appeared in IEEE Trans. Consumer Electronics)
-omits the sample images that appeared in CACM, but it includes corrections
-and some added material.  Note: the Wallace article is copyright ACM and IEEE,
-and it may not be used for commercial purposes.
-
-A somewhat less technical, more leisurely introduction to JPEG can be found in
-"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by
-M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1.  This book provides
-good explanations and example C code for a multitude of compression methods
-including JPEG.  It is an excellent source if you are comfortable reading C
-code but don't know much about data compression in general.  The book's JPEG
-sample code is far from industrial-strength, but when you are ready to look
-at a full implementation, you've got one here...
-
-The best full description of JPEG is the textbook "JPEG Still Image Data
-Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published
-by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1.  Price US$59.95, 638 pp.
-The book includes the complete text of the ISO JPEG standards (DIS 10918-1
-and draft DIS 10918-2).  This is by far the most complete exposition of JPEG
-in existence, and we highly recommend it.
-
-The JPEG standard itself is not available electronically; you must order a
-paper copy through ISO or ITU.  (Unless you feel a need to own a certified
-official copy, we recommend buying the Pennebaker and Mitchell book instead;
-it's much cheaper and includes a great deal of useful explanatory material.)
-In the USA, copies of the standard may be ordered from ANSI Sales at (212)
-642-4900, or from Global Engineering Documents at (800) 854-7179.  (ANSI
-doesn't take credit card orders, but Global does.)  It's not cheap: as of
-1992, ANSI was charging $95 for Part 1 and $47 for Part 2, plus 7%
-shipping/handling.  The standard is divided into two parts, Part 1 being the
-actual specification, while Part 2 covers compliance testing methods.  Part 1
-is titled "Digital Compression and Coding of Continuous-tone Still Images,
-Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS
-10918-1, ITU-T T.81.  Part 2 is titled "Digital Compression and Coding of
-Continuous-tone Still Images, Part 2: Compliance testing" and has document
-numbers ISO/IEC IS 10918-2, ITU-T T.83.
-
-Some extensions to the original JPEG standard are defined in JPEG Part 3,
-a newer ISO standard numbered ISO/IEC IS 10918-3 and ITU-T T.84.  IJG
-currently does not support any Part 3 extensions.
-
-The JPEG standard does not specify all details of an interchangeable file
-format.  For the omitted details we follow the "JFIF" conventions, revision
-1.02.  A copy of the JFIF spec is available from:
-	Literature Department
-	C-Cube Microsystems, Inc.
-	1778 McCarthy Blvd.
-	Milpitas, CA 95035
-	phone (408) 944-6300,  fax (408) 944-6314
-A PostScript version of this document is available by FTP at
-ftp://ftp.uu.net/graphics/jpeg/jfif.ps.gz.  There is also a plain text
-version at ftp://ftp.uu.net/graphics/jpeg/jfif.txt.gz, but it is missing
-the figures.
-
-The TIFF 6.0 file format specification can be obtained by FTP from
-ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz.  The JPEG incorporation scheme
-found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems.
-IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6).
-Instead, we recommend the JPEG design proposed by TIFF Technical Note #2
-(Compression tag 7).  Copies of this Note can be obtained from ftp.sgi.com or
-from ftp://ftp.uu.net/graphics/jpeg/.  It is expected that the next revision
-of the TIFF spec will replace the 6.0 JPEG design with the Note's design.
-Although IJG's own code does not support TIFF/JPEG, the free libtiff library
-uses our library to implement TIFF/JPEG per the Note.  libtiff is available
-from ftp://ftp.sgi.com/graphics/tiff/.
-
-
-ARCHIVE LOCATIONS
-=================
-
-The "official" archive site for this software is ftp.uu.net (Internet
-address 192.48.96.9).  The most recent released version can always be found
-there in directory graphics/jpeg.  This particular version will be archived
-as ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz.  If you don't have
-direct Internet access, UUNET's archives are also available via UUCP; contact
-help@uunet.uu.net for information on retrieving files that way.
-
-Numerous Internet sites maintain copies of the UUNET files.  However, only
-ftp.uu.net is guaranteed to have the latest official version.
-
-You can also obtain this software in DOS-compatible "zip" archive format from
-the SimTel archives (ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/), or
-on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12
-"JPEG Tools".  Again, these versions may sometimes lag behind the ftp.uu.net
-release.
-
-The JPEG FAQ (Frequently Asked Questions) article is a useful source of
-general information about JPEG.  It is updated constantly and therefore is
-not included in this distribution.  The FAQ is posted every two weeks to
-Usenet newsgroups comp.graphics.misc, news.answers, and other groups.
-It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/
-and other news.answers archive sites, including the official news.answers
-archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/.
-If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu
-with body
-	send usenet/news.answers/jpeg-faq/part1
-	send usenet/news.answers/jpeg-faq/part2
-
-
-RELATED SOFTWARE
-================
-
-Numerous viewing and image manipulation programs now support JPEG.  (Quite a
-few of them use this library to do so.)  The JPEG FAQ described above lists
-some of the more popular free and shareware viewers, and tells where to
-obtain them on Internet.
-
-If you are on a Unix machine, we highly recommend Jef Poskanzer's free
-PBMPLUS software, which provides many useful operations on PPM-format image
-files.  In particular, it can convert PPM images to and from a wide range of
-other formats, thus making cjpeg/djpeg considerably more useful.  The latest
-version is distributed by the NetPBM group, and is available from numerous
-sites, notably ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/.
-Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is;
-you are likely to have difficulty making it work on any non-Unix machine.
-
-A different free JPEG implementation, written by the PVRG group at Stanford,
-is available from ftp://havefun.stanford.edu/pub/jpeg/.  This program
-is designed for research and experimentation rather than production use;
-it is slower, harder to use, and less portable than the IJG code, but it
-is easier to read and modify.  Also, the PVRG code supports lossless JPEG,
-which we do not.  (On the other hand, it doesn't do progressive JPEG.)
-
-
-FILE FORMAT WARS
-================
-
-Some JPEG programs produce files that are not compatible with our library.
-The root of the problem is that the ISO JPEG committee failed to specify a
-concrete file format.  Some vendors "filled in the blanks" on their own,
-creating proprietary formats that no one else could read.  (For example, none
-of the early commercial JPEG implementations for the Macintosh were able to
-exchange compressed files.)
-
-The file format we have adopted is called JFIF (see REFERENCES).  This format
-has been agreed to by a number of major commercial JPEG vendors, and it has
-become the de facto standard.  JFIF is a minimal or "low end" representation.
-We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF
-Technical Note #2) for "high end" applications that need to record a lot of
-additional data about an image.  TIFF/JPEG is fairly new and not yet widely
-supported, unfortunately.
-
-The upcoming JPEG Part 3 standard defines a file format called SPIFF.
-SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should
-be able to read the most common variant of SPIFF.  SPIFF has some technical
-advantages over JFIF, but its major claim to fame is simply that it is an
-official standard rather than an informal one.  At this point it is unclear
-whether SPIFF will supersede JFIF or whether JFIF will remain the de-facto
-standard.  IJG intends to support SPIFF once the standard is frozen, but we
-have not decided whether it should become our default output format or not.
-(In any case, our decoder will remain capable of reading JFIF indefinitely.)
-
-Various proprietary file formats incorporating JPEG compression also exist.
-We have little or no sympathy for the existence of these formats.  Indeed,
-one of the original reasons for developing this free software was to help
-force convergence on common, open format standards for JPEG files.  Don't
-use a proprietary file format!
-
-
-TO DO
-=====
-
-The major thrust for v7 will probably be improvement of visual quality.
-The current method for scaling the quantization tables is known not to be
-very good at low Q values.  We also intend to investigate block boundary
-smoothing, "poor man's variable quantization", and other means of improving
-quality-vs-file-size performance without sacrificing compatibility.
-
-In future versions, we are considering supporting some of the upcoming JPEG
-Part 3 extensions --- principally, variable quantization and the SPIFF file
-format.
-
-As always, speeding things up is of great interest.
-
-Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net.
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/REMOVED.txt ./Shared/jpeg-6b/REMOVED.txt
--- ../Tekkotsu_2.3/Shared/jpeg-6b/REMOVED.txt	Mon Dec  1 12:30:32 2003
+++ ./Shared/jpeg-6b/REMOVED.txt	Wed Dec 31 19:00:00 1969
@@ -1,68 +0,0 @@
-ansi2knr.1
-ansi2knr.c
-cderror.h
-cdjpeg.c
-cdjpeg.h
-cjpeg.1
-cjpeg.c
-ckconfig.c
-config.guess
-config.sub
-configure
-djpeg.1
-djpeg.c
-example.c
-install.doc
-install-sh
-jconfig.bcc
-jconfig.cfg
-jconfig.dj
-jconfig.mac
-jconfig.manx
-jconfig.mc6
-jconfig.sas
-jconfig.st
-jconfig.vc
-jconfig.vms
-jconfig.wat
-jpegtran.1
-jpegtran.c
-ltconfig
-ltmain.sh
-makcjpeg.st
-makdjpeg.st
-makeapps.ds
-Makefile
-makefile.ansi
-makefile.bcc
-makefile.cfg
-makefile.dj
-makefile.manx
-makefile.mc6
-makefile.mms
-makefile.sas
-makefile.unix
-makefile.vc
-makefile.vms
-makefile.wat
-makelib.ds
-makeproj.mac
-makljpeg.st
-maktjpeg.st
-makvms.opt
-rdcolmap.c
-rdjpgcom.1
-rdjpgcom.c
-rdswitch.c
-testimg.bmp
-testimg.jpg
-testimgp.jpg
-testimg.ppm
-testorig.jpg
-testprog.jpg
-transupp.c
-transupp.h
-usage.doc
-wizard.doc
-wrjpgcom.1
-wrjpgcom.c
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/change.log ./Shared/jpeg-6b/change.log
--- ../Tekkotsu_2.3/Shared/jpeg-6b/change.log	Mon Dec  1 12:30:32 2003
+++ ./Shared/jpeg-6b/change.log	Wed Dec 31 19:00:00 1969
@@ -1,230 +0,0 @@
-CHANGE LOG for Independent JPEG Group's JPEG software
-
-Incorporation into Tekkotsu framework 13-Nov-2003
--------------------------------------------------
-
-Many of the support utilities and installation files were removed to
-ease integration and reduce file size of the source.
-
-The rd*.c and wr*.c files have been retained in case they are of use.
-However, these files are not part of jpeglib, they were used by the
-cjpeg/djpeg example utilities.  See filelist.doc for more information.
-
-Files which have been removed are listed in REMOVED.txt, files which
-have been added (from the Sony sample code) are listed in ADDED.txt.
-
-
-Version 6b  27-Mar-1998
------------------------
-
-jpegtran has new features for lossless image transformations (rotation
-and flipping) as well as "lossless" reduction to grayscale.
-
-jpegtran now copies comments by default; it has a -copy switch to enable
-copying all APPn blocks as well, or to suppress comments.  (Formerly it
-always suppressed comments and APPn blocks.)  jpegtran now also preserves
-JFIF version and resolution information.
-
-New decompressor library feature: COM and APPn markers found in the input
-file can be saved in memory for later use by the application.  (Before,
-you had to code this up yourself with a custom marker processor.)
-
-There is an unused field "void * client_data" now in compress and decompress
-parameter structs; this may be useful in some applications.
-
-JFIF version number information is now saved by the decoder and accepted by
-the encoder.  jpegtran uses this to copy the source file's version number,
-to ensure "jpegtran -copy all" won't create bogus files that contain JFXX
-extensions but claim to be version 1.01.  Applications that generate their
-own JFXX extension markers also (finally) have a supported way to cause the
-encoder to emit JFIF version number 1.02.
-
-djpeg's trace mode reports JFIF 1.02 thumbnail images as such, rather
-than as unknown APP0 markers.
-
-In -verbose mode, djpeg and rdjpgcom will try to print the contents of
-APP12 markers as text.  Some digital cameras store useful text information
-in APP12 markers.
-
-Handling of truncated data streams is more robust: blocks beyond the one in
-which the error occurs will be output as uniform gray, or left unchanged
-if decoding a progressive JPEG.  The appearance no longer depends on the
-Huffman tables being used.
-
-Huffman tables are checked for validity much more carefully than before.
-
-To avoid the Unisys LZW patent, djpeg's GIF output capability has been
-changed to produce "uncompressed GIFs", and cjpeg's GIF input capability
-has been removed altogether.  We're not happy about it either, but there
-seems to be no good alternative.
-
-The configure script now supports building libjpeg as a shared library
-on many flavors of Unix (all the ones that GNU libtool knows how to
-build shared libraries for).  Use "./configure --enable-shared" to
-try this out.
-
-New jconfig file and makefiles for Microsoft Visual C++ and Developer Studio.
-Also, a jconfig file and a build script for Metrowerks CodeWarrior
-on Apple Macintosh.  makefile.dj has been updated for DJGPP v2, and there
-are miscellaneous other minor improvements in the makefiles.
-
-jmemmac.c now knows how to create temporary files following Mac System 7
-conventions.
-
-djpeg's -map switch is now able to read raw-format PPM files reliably.
-
-cjpeg -progressive -restart no longer generates any unnecessary DRI markers.
-
-Multiple calls to jpeg_simple_progression for a single JPEG object
-no longer leak memory.
-
-
-Version 6a  7-Feb-96
---------------------
-
-Library initialization sequence modified to detect version mismatches
-and struct field packing mismatches between library and calling application.
-This change requires applications to be recompiled, but does not require
-any application source code change.
-
-All routine declarations changed to the style "GLOBAL(type) name ...",
-that is, GLOBAL, LOCAL, METHODDEF, EXTERN are now macros taking the
-routine's return type as an argument.  This makes it possible to add
-Microsoft-style linkage keywords to all the routines by changing just
-these macros.  Note that any application code that was using these macros
-will have to be changed.
-
-DCT coefficient quantization tables are now stored in normal array order
-rather than zigzag order.  Application code that calls jpeg_add_quant_table,
-or otherwise manipulates quantization tables directly, will need to be
-changed.  If you need to make such code work with either older or newer
-versions of the library, a test like "#if JPEG_LIB_VERSION >= 61" is
-recommended.
-
-djpeg's trace capability now dumps DQT tables in natural order, not zigzag
-order.  This allows the trace output to be made into a "-qtables" file
-more easily.
-
-New system-dependent memory manager module for use on Apple Macintosh.
-
-Fix bug in cjpeg's -smooth option: last one or two scanlines would be
-duplicates of the prior line unless the image height mod 16 was 1 or 2.
-
-Repair minor problems in VMS, BCC, MC6 makefiles.
-
-New configure script based on latest GNU Autoconf.
-
-Correct the list of include files needed by MetroWerks C for ccommand().
-
-Numerous small documentation updates.
-
-
-Version 6  2-Aug-95
--------------------
-
-Progressive JPEG support: library can read and write full progressive JPEG
-files.  A "buffered image" mode supports incremental decoding for on-the-fly
-display of progressive images.  Simply recompiling an existing IJG-v5-based
-decoder with v6 should allow it to read progressive files, though of course
-without any special progressive display.
-
-New "jpegtran" application performs lossless transcoding between different
-JPEG formats; primarily, it can be used to convert baseline to progressive
-JPEG and vice versa.  In support of jpegtran, the library now allows lossless
-reading and writing of JPEG files as DCT coefficient arrays.  This ability
-may be of use in other applications.
-
-Notes for programmers:
-* We changed jpeg_start_decompress() to be able to suspend; this makes all
-decoding modes available to suspending-input applications.  However,
-existing applications that use suspending input will need to be changed
-to check the return value from jpeg_start_decompress().  You don't need to
-do anything if you don't use a suspending data source.
-* We changed the interface to the virtual array routines: access_virt_array
-routines now take a count of the number of rows to access this time.  The
-last parameter to request_virt_array routines is now interpreted as the
-maximum number of rows that may be accessed at once, but not necessarily
-the height of every access.
-
-
-Version 5b  15-Mar-95
----------------------
-
-Correct bugs with grayscale images having v_samp_factor > 1.
-
-jpeg_write_raw_data() now supports output suspension.
-
-Correct bugs in "configure" script for case of compiling in
-a directory other than the one containing the source files.
-
-Repair bug in jquant1.c: sometimes didn't use as many colors as it could.
-
-Borland C makefile and jconfig file work under either MS-DOS or OS/2.
-
-Miscellaneous improvements to documentation.
-
-
-Version 5a  7-Dec-94
---------------------
-
-Changed color conversion roundoff behavior so that grayscale values are
-represented exactly.  (This causes test image files to change.)
-
-Make ordered dither use 16x16 instead of 4x4 pattern for a small quality
-improvement.
-
-New configure script based on latest GNU Autoconf.
-Fix configure script to handle CFLAGS correctly.
-Rename *.auto files to *.cfg, so that configure script still works if
-file names have been truncated for DOS.
-
-Fix bug in rdbmp.c: didn't allow for extra data between header and image.
-
-Modify rdppm.c/wrppm.c to handle 2-byte raw PPM/PGM formats for 12-bit data.
-
-Fix several bugs in rdrle.c.
-
-NEED_SHORT_EXTERNAL_NAMES option was broken.
-
-Revise jerror.h/jerror.c for more flexibility in message table.
-
-Repair oversight in jmemname.c NO_MKTEMP case: file could be there
-but unreadable.
-
-
-Version 5  24-Sep-94
---------------------
-
-Version 5 represents a nearly complete redesign and rewrite of the IJG
-software.  Major user-visible changes include:
-  * Automatic configuration simplifies installation for most Unix systems.
-  * A range of speed vs. image quality tradeoffs are supported.
-    This includes resizing of an image during decompression: scaling down
-    by a factor of 1/2, 1/4, or 1/8 is handled very efficiently.
-  * New programs rdjpgcom and wrjpgcom allow insertion and extraction
-    of text comments in a JPEG file.
-
-The application programmer's interface to the library has changed completely.
-Notable improvements include:
-  * We have eliminated the use of callback routines for handling the
-    uncompressed image data.  The application now sees the library as a
-    set of routines that it calls to read or write image data on a
-    scanline-by-scanline basis.
-  * The application image data is represented in a conventional interleaved-
-    pixel format, rather than as a separate array for each color channel.
-    This can save a copying step in many programs.
-  * The handling of compressed data has been cleaned up: the application can
-    supply routines to source or sink the compressed data.  It is possible to
-    suspend processing on source/sink buffer overrun, although this is not
-    supported in all operating modes.
-  * All static state has been eliminated from the library, so that multiple
-    instances of compression or decompression can be active concurrently.
-  * JPEG abbreviated datastream formats are supported, ie, quantization and
-    Huffman tables can be stored separately from the image data.
-  * And not only that, but the documentation of the library has improved
-    considerably!
-
-
-The last widely used release before the version 5 rewrite was version 4A of
-18-Feb-93.  Change logs before that point have been discarded, since they
-are not of much interest after the rewrite.
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/coderules.doc ./Shared/jpeg-6b/coderules.doc
--- ../Tekkotsu_2.3/Shared/jpeg-6b/coderules.doc	Mon Dec  1 12:30:32 2003
+++ ./Shared/jpeg-6b/coderules.doc	Wed Dec 31 19:00:00 1969
@@ -1,118 +0,0 @@
-IJG JPEG LIBRARY:  CODING RULES
-
-Copyright (C) 1991-1996, Thomas G. Lane.
-This file is part of the Independent JPEG Group's software.
-For conditions of distribution and use, see the accompanying README file.
-
-
-Since numerous people will be contributing code and bug fixes, it's important
-to establish a common coding style.  The goal of using similar coding styles
-is much more important than the details of just what that style is.
-
-In general we follow the recommendations of "Recommended C Style and Coding
-Standards" revision 6.1 (Cannon et al. as modified by Spencer, Keppel and
-Brader).  This document is available in the IJG FTP archive (see
-jpeg/doc/cstyle.ms.tbl.Z, or cstyle.txt.Z for those without nroff/tbl).
-
-Block comments should be laid out thusly:
-
-/*
- *  Block comments in this style.
- */
-
-We indent statements in K&R style, e.g.,
-	if (test) {
-	  then-part;
-	} else {
-	  else-part;
-	}
-with two spaces per indentation level.  (This indentation convention is
-handled automatically by GNU Emacs and many other text editors.)
-
-Multi-word names should be written in lower case with underscores, e.g.,
-multi_word_name (not multiWordName).  Preprocessor symbols and enum constants
-are similar but upper case (MULTI_WORD_NAME).  Names should be unique within
-the first fifteen characters.  (On some older systems, global names must be
-unique within six characters.  We accommodate this without cluttering the
-source code by using macros to substitute shorter names.)
-
-We use function prototypes everywhere; we rely on automatic source code
-transformation to feed prototype-less C compilers.  Transformation is done
-by the simple and portable tool 'ansi2knr.c' (courtesy of Ghostscript).
-ansi2knr is not very bright, so it imposes a format requirement on function
-declarations: the function name MUST BEGIN IN COLUMN 1.  Thus all functions
-should be written in the following style:
-
-LOCAL(int *)
-function_name (int a, char *b)
-{
-    code...
-}
-
-Note that each function definition must begin with GLOBAL(type), LOCAL(type),
-or METHODDEF(type).  These macros expand to "static type" or just "type" as
-appropriate.  They provide a readable indication of the routine's usage and
-can readily be changed for special needs.  (For instance, special linkage
-keywords can be inserted for use in Windows DLLs.)
-
-ansi2knr does not transform method declarations (function pointers in
-structs).  We handle these with a macro JMETHOD, defined as
-	#ifdef HAVE_PROTOTYPES
-	#define JMETHOD(type,methodname,arglist)  type (*methodname) arglist
-	#else
-	#define JMETHOD(type,methodname,arglist)  type (*methodname) ()
-	#endif
-which is used like this:
-	struct function_pointers {
-	  JMETHOD(void, init_entropy_encoder, (int somearg, jparms *jp));
-	  JMETHOD(void, term_entropy_encoder, (void));
-	};
-Note the set of parentheses surrounding the parameter list.
-
-A similar solution is used for forward and external function declarations
-(see the EXTERN and JPP macros).
-
-If the code is to work on non-ANSI compilers, we cannot rely on a prototype
-declaration to coerce actual parameters into the right types.  Therefore, use
-explicit casts on actual parameters whenever the actual parameter type is not
-identical to the formal parameter.  Beware of implicit conversions to "int".
-
-It seems there are some non-ANSI compilers in which the sizeof() operator
-is defined to return int, yet size_t is defined as long.  Needless to say,
-this is brain-damaged.  Always use the SIZEOF() macro in place of sizeof(),
-so that the result is guaranteed to be of type size_t.
-
-
-The JPEG library is intended to be used within larger programs.  Furthermore,
-we want it to be reentrant so that it can be used by applications that process
-multiple images concurrently.  The following rules support these requirements:
-
-1. Avoid direct use of file I/O, "malloc", error report printouts, etc;
-pass these through the common routines provided.
-
-2. Minimize global namespace pollution.  Functions should be declared static
-wherever possible.  (Note that our method-based calling conventions help this
-a lot: in many modules only the initialization function will ever need to be
-called directly, so only that function need be externally visible.)  All
-global function names should begin with "jpeg_", and should have an
-abbreviated name (unique in the first six characters) substituted by macro
-when NEED_SHORT_EXTERNAL_NAMES is set.
-
-3. Don't use global variables; anything that must be used in another module
-should be in the common data structures.
-
-4. Don't use static variables except for read-only constant tables.  Variables
-that should be private to a module can be placed into private structures (see
-the system architecture document, structure.doc).
-
-5. Source file names should begin with "j" for files that are part of the
-library proper; source files that are not part of the library, such as cjpeg.c
-and djpeg.c, do not begin with "j".  Keep source file names to eight
-characters (plus ".c" or ".h", etc) to make life easy for MS-DOSers.  Keep
-compression and decompression code in separate source files --- some
-applications may want only one half of the library.
-
-Note: these rules (particularly #4) are not followed religiously in the
-modules that are used in cjpeg/djpeg but are not part of the JPEG library
-proper.  Those modules are not really intended to be used in other
-applications.
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/filelist.doc ./Shared/jpeg-6b/filelist.doc
--- ../Tekkotsu_2.3/Shared/jpeg-6b/filelist.doc	Mon Dec  1 12:30:32 2003
+++ ./Shared/jpeg-6b/filelist.doc	Wed Dec 31 19:00:00 1969
@@ -1,210 +0,0 @@
-IJG JPEG LIBRARY:  FILE LIST
-
-Copyright (C) 1994-1998, Thomas G. Lane.
-This file is part of the Independent JPEG Group's software.
-For conditions of distribution and use, see the accompanying README file.
-
-
-Here is a road map to the files in the IJG JPEG distribution.  The
-distribution includes the JPEG library proper, plus two application
-programs ("cjpeg" and "djpeg") which use the library to convert JPEG
-files to and from some other popular image formats.  A third application
-"jpegtran" uses the library to do lossless conversion between different
-variants of JPEG.  There are also two stand-alone applications,
-"rdjpgcom" and "wrjpgcom".
-
-
-THE JPEG LIBRARY
-================
-
-Include files:
-
-jpeglib.h	JPEG library's exported data and function declarations.
-jconfig.h	Configuration declarations.  Note: this file is not present
-		in the distribution; it is generated during installation.
-jmorecfg.h	Additional configuration declarations; need not be changed
-		for a standard installation.
-jerror.h	Declares JPEG library's error and trace message codes.
-jinclude.h	Central include file used by all IJG .c files to reference
-		system include files.
-jpegint.h	JPEG library's internal data structures.
-jchuff.h	Private declarations for Huffman encoder modules.
-jdhuff.h	Private declarations for Huffman decoder modules.
-jdct.h		Private declarations for forward & reverse DCT subsystems.
-jmemsys.h	Private declarations for memory management subsystem.
-jversion.h	Version information.
-
-Applications using the library should include jpeglib.h (which in turn
-includes jconfig.h and jmorecfg.h).  Optionally, jerror.h may be included
-if the application needs to reference individual JPEG error codes.  The
-other include files are intended for internal use and would not normally
-be included by an application program.  (cjpeg/djpeg/etc do use jinclude.h,
-since its function is to improve portability of the whole IJG distribution.
-Most other applications will directly include the system include files they
-want, and hence won't need jinclude.h.)
-
-
-C source code files:
-
-These files contain most of the functions intended to be called directly by
-an application program:
-
-jcapimin.c	Application program interface: core routines for compression.
-jcapistd.c	Application program interface: standard compression.
-jdapimin.c	Application program interface: core routines for decompression.
-jdapistd.c	Application program interface: standard decompression.
-jcomapi.c	Application program interface routines common to compression
-		and decompression.
-jcparam.c	Compression parameter setting helper routines.
-jctrans.c	API and library routines for transcoding compression.
-jdtrans.c	API and library routines for transcoding decompression.
-
-Compression side of the library:
-
-jcinit.c	Initialization: determines which other modules to use.
-jcmaster.c	Master control: setup and inter-pass sequencing logic.
-jcmainct.c	Main buffer controller (preprocessor => JPEG compressor).
-jcprepct.c	Preprocessor buffer controller.
-jccoefct.c	Buffer controller for DCT coefficient buffer.
-jccolor.c	Color space conversion.
-jcsample.c	Downsampling.
-jcdctmgr.c	DCT manager (DCT implementation selection & control).
-jfdctint.c	Forward DCT using slow-but-accurate integer method.
-jfdctfst.c	Forward DCT using faster, less accurate integer method.
-jfdctflt.c	Forward DCT using floating-point arithmetic.
-jchuff.c	Huffman entropy coding for sequential JPEG.
-jcphuff.c	Huffman entropy coding for progressive JPEG.
-jcmarker.c	JPEG marker writing.
-jdatadst.c	Data destination manager for stdio output.
-
-Decompression side of the library:
-
-jdmaster.c	Master control: determines which other modules to use.
-jdinput.c	Input controller: controls input processing modules.
-jdmainct.c	Main buffer controller (JPEG decompressor => postprocessor).
-jdcoefct.c	Buffer controller for DCT coefficient buffer.
-jdpostct.c	Postprocessor buffer controller.
-jdmarker.c	JPEG marker reading.
-jdhuff.c	Huffman entropy decoding for sequential JPEG.
-jdphuff.c	Huffman entropy decoding for progressive JPEG.
-jddctmgr.c	IDCT manager (IDCT implementation selection & control).
-jidctint.c	Inverse DCT using slow-but-accurate integer method.
-jidctfst.c	Inverse DCT using faster, less accurate integer method.
-jidctflt.c	Inverse DCT using floating-point arithmetic.
-jidctred.c	Inverse DCTs with reduced-size outputs.
-jdsample.c	Upsampling.
-jdcolor.c	Color space conversion.
-jdmerge.c	Merged upsampling/color conversion (faster, lower quality).
-jquant1.c	One-pass color quantization using a fixed-spacing colormap.
-jquant2.c	Two-pass color quantization using a custom-generated colormap.
-		Also handles one-pass quantization to an externally given map.
-jdatasrc.c	Data source manager for stdio input.
-
-Support files for both compression and decompression:
-
-jerror.c	Standard error handling routines (application replaceable).
-jmemmgr.c	System-independent (more or less) memory management code.
-jutils.c	Miscellaneous utility routines.
-
-jmemmgr.c relies on a system-dependent memory management module.  The IJG
-distribution includes the following implementations of the system-dependent
-module:
-
-jmemnobs.c	"No backing store": assumes adequate virtual memory exists.
-jmemansi.c	Makes temporary files with ANSI-standard routine tmpfile().
-jmemname.c	Makes temporary files with program-generated file names.
-jmemdos.c	Custom implementation for MS-DOS (16-bit environment only):
-		can use extended and expanded memory as well as temp files.
-jmemmac.c	Custom implementation for Apple Macintosh.
-
-Exactly one of the system-dependent modules should be configured into an
-installed JPEG library (see install.doc for hints about which one to use).
-On unusual systems you may find it worthwhile to make a special
-system-dependent memory manager.
-
-
-Non-C source code files:
-
-jmemdosa.asm	80x86 assembly code support for jmemdos.c; used only in
-		MS-DOS-specific configurations of the JPEG library.
-
-
-CJPEG/DJPEG/JPEGTRAN
-====================
-
-Include files:
-
-cdjpeg.h	Declarations shared by cjpeg/djpeg/jpegtran modules.
-cderror.h	Additional error and trace message codes for cjpeg et al.
-transupp.h	Declarations for jpegtran support routines in transupp.c.
-
-C source code files:
-
-cjpeg.c		Main program for cjpeg.
-djpeg.c		Main program for djpeg.
-jpegtran.c	Main program for jpegtran.
-cdjpeg.c	Utility routines used by all three programs.
-rdcolmap.c	Code to read a colormap file for djpeg's "-map" switch.
-rdswitch.c	Code to process some of cjpeg's more complex switches.
-		Also used by jpegtran.
-transupp.c	Support code for jpegtran: lossless image manipulations.
-
-Image file reader modules for cjpeg:
-
-rdbmp.c		BMP file input.
-rdgif.c		GIF file input (now just a stub).
-rdppm.c		PPM/PGM file input.
-rdrle.c		Utah RLE file input.
-rdtarga.c	Targa file input.
-
-Image file writer modules for djpeg:
-
-wrbmp.c		BMP file output.
-wrgif.c		GIF file output (a mere shadow of its former self).
-wrppm.c		PPM/PGM file output.
-wrrle.c		Utah RLE file output.
-wrtarga.c	Targa file output.
-
-
-RDJPGCOM/WRJPGCOM
-=================
-
-C source code files:
-
-rdjpgcom.c	Stand-alone rdjpgcom application.
-wrjpgcom.c	Stand-alone wrjpgcom application.
-
-These programs do not depend on the IJG library.  They do use
-jconfig.h and jinclude.h, only to improve portability.
-
-
-ADDITIONAL FILES
-================
-
-Documentation (see README for a guide to the documentation files):
-
-README		Master documentation file.
-*.doc		Other documentation files.
-*.1		Documentation in Unix man page format.
-change.log	Version-to-version change highlights.
-example.c	Sample code for calling JPEG library.
-
-Configuration/installation files and programs (see install.doc for more info):
-
-configure	Unix shell script to perform automatic configuration.
-ltconfig	Support scripts for configure (from GNU libtool).
-ltmain.sh
-config.guess
-config.sub
-install-sh	Install shell script for those Unix systems lacking one.
-ckconfig.c	Program to generate jconfig.h on non-Unix systems.
-jconfig.doc	Template for making jconfig.h by hand.
-makefile.*	Sample makefiles for particular systems.
-jconfig.*	Sample jconfig.h for particular systems.
-ansi2knr.c	De-ANSIfier for pre-ANSI C compilers (courtesy of
-		L. Peter Deutsch and Aladdin Enterprises).
-
-Test files (see install.doc for test procedure):
-
-test*.*		Source and comparison files for confidence test.
-		These are binary image files, NOT text files.
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcapimin.c ./Shared/jpeg-6b/jcapimin.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcapimin.c	Mon Dec  1 12:30:32 2003
+++ ./Shared/jpeg-6b/jcapimin.c	Wed Dec 31 19:00:00 1969
@@ -1,280 +0,0 @@
-/*
- * jcapimin.c
- *
- * Copyright (C) 1994-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains application interface code for the compression half
- * of the JPEG library.  These are the "minimum" API routines that may be
- * needed in either the normal full-compression case or the transcoding-only
- * case.
- *
- * Most of the routines intended to be called directly by an application
- * are in this file or in jcapistd.c.  But also see jcparam.c for
- * parameter-setup helper routines, jcomapi.c for routines shared by
- * compression and decompression, and jctrans.c for the transcoding case.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * Initialization of a JPEG compression object.
- * The error manager must already be set up (in case memory manager fails).
- */
-
-GLOBAL(void)
-jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
-{
-  int i;
-
-  /* Guard against version mismatches between library and caller. */
-  cinfo->mem = NULL;		/* so jpeg_destroy knows mem mgr not called */
-  if (version != JPEG_LIB_VERSION)
-    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
-  if (structsize != SIZEOF(struct jpeg_compress_struct))
-    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, 
-	     (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
-
-  /* For debugging purposes, we zero the whole master structure.
-   * But the application has already set the err pointer, and may have set
-   * client_data, so we have to save and restore those fields.
-   * Note: if application hasn't set client_data, tools like Purify may
-   * complain here.
-   */
-  {
-    struct jpeg_error_mgr * err = cinfo->err;
-    void * client_data = cinfo->client_data; /* ignore Purify complaint here */
-    MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
-    cinfo->err = err;
-    cinfo->client_data = client_data;
-  }
-  cinfo->is_decompressor = FALSE;
-
-  /* Initialize a memory manager instance for this object */
-  jinit_memory_mgr((j_common_ptr) cinfo);
-
-  /* Zero out pointers to permanent structures. */
-  cinfo->progress = NULL;
-  cinfo->dest = NULL;
-
-  cinfo->comp_info = NULL;
-
-  for (i = 0; i < NUM_QUANT_TBLS; i++)
-    cinfo->quant_tbl_ptrs[i] = NULL;
-
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    cinfo->dc_huff_tbl_ptrs[i] = NULL;
-    cinfo->ac_huff_tbl_ptrs[i] = NULL;
-  }
-
-  cinfo->script_space = NULL;
-
-  cinfo->input_gamma = 1.0;	/* in case application forgets */
-
-  /* OK, I'm ready */
-  cinfo->global_state = CSTATE_START;
-}
-
-
-/*
- * Destruction of a JPEG compression object
- */
-
-GLOBAL(void)
-jpeg_destroy_compress (j_compress_ptr cinfo)
-{
-  jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
-}
-
-
-/*
- * Abort processing of a JPEG compression operation,
- * but don't destroy the object itself.
- */
-
-GLOBAL(void)
-jpeg_abort_compress (j_compress_ptr cinfo)
-{
-  jpeg_abort((j_common_ptr) cinfo); /* use common routine */
-}
-
-
-/*
- * Forcibly suppress or un-suppress all quantization and Huffman tables.
- * Marks all currently defined tables as already written (if suppress)
- * or not written (if !suppress).  This will control whether they get emitted
- * by a subsequent jpeg_start_compress call.
- *
- * This routine is exported for use by applications that want to produce
- * abbreviated JPEG datastreams.  It logically belongs in jcparam.c, but
- * since it is called by jpeg_start_compress, we put it here --- otherwise
- * jcparam.o would be linked whether the application used it or not.
- */
-
-GLOBAL(void)
-jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
-{
-  int i;
-  JQUANT_TBL * qtbl;
-  JHUFF_TBL * htbl;
-
-  for (i = 0; i < NUM_QUANT_TBLS; i++) {
-    if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
-      qtbl->sent_table = suppress;
-  }
-
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
-      htbl->sent_table = suppress;
-    if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
-      htbl->sent_table = suppress;
-  }
-}
-
-
-/*
- * Finish JPEG compression.
- *
- * If a multipass operating mode was selected, this may do a great deal of
- * work including most of the actual output.
- */
-
-GLOBAL(void)
-jpeg_finish_compress (j_compress_ptr cinfo)
-{
-  JDIMENSION iMCU_row;
-
-  if (cinfo->global_state == CSTATE_SCANNING ||
-      cinfo->global_state == CSTATE_RAW_OK) {
-    /* Terminate first pass */
-    if (cinfo->next_scanline < cinfo->image_height)
-      ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
-    (*cinfo->master->finish_pass) (cinfo);
-  } else if (cinfo->global_state != CSTATE_WRCOEFS)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  /* Perform any remaining passes */
-  while (! cinfo->master->is_last_pass) {
-    (*cinfo->master->prepare_for_pass) (cinfo);
-    for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
-      if (cinfo->progress != NULL) {
-	cinfo->progress->pass_counter = (long) iMCU_row;
-	cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
-	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-      }
-      /* We bypass the main controller and invoke coef controller directly;
-       * all work is being done from the coefficient buffer.
-       */
-      if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
-	ERREXIT(cinfo, JERR_CANT_SUSPEND);
-    }
-    (*cinfo->master->finish_pass) (cinfo);
-  }
-  /* Write EOI, do final cleanup */
-  (*cinfo->marker->write_file_trailer) (cinfo);
-  (*cinfo->dest->term_destination) (cinfo);
-  /* We can use jpeg_abort to release memory and reset global_state */
-  jpeg_abort((j_common_ptr) cinfo);
-}
-
-
-/*
- * Write a special marker.
- * This is only recommended for writing COM or APPn markers.
- * Must be called after jpeg_start_compress() and before
- * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
- */
-
-GLOBAL(void)
-jpeg_write_marker (j_compress_ptr cinfo, int marker,
-		   const JOCTET *dataptr, unsigned int datalen)
-{
-  JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
-
-  if (cinfo->next_scanline != 0 ||
-      (cinfo->global_state != CSTATE_SCANNING &&
-       cinfo->global_state != CSTATE_RAW_OK &&
-       cinfo->global_state != CSTATE_WRCOEFS))
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
-  write_marker_byte = cinfo->marker->write_marker_byte;	/* copy for speed */
-  while (datalen--) {
-    (*write_marker_byte) (cinfo, *dataptr);
-    dataptr++;
-  }
-}
-
-/* Same, but piecemeal. */
-
-GLOBAL(void)
-jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
-{
-  if (cinfo->next_scanline != 0 ||
-      (cinfo->global_state != CSTATE_SCANNING &&
-       cinfo->global_state != CSTATE_RAW_OK &&
-       cinfo->global_state != CSTATE_WRCOEFS))
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
-}
-
-GLOBAL(void)
-jpeg_write_m_byte (j_compress_ptr cinfo, int val)
-{
-  (*cinfo->marker->write_marker_byte) (cinfo, val);
-}
-
-
-/*
- * Alternate compression function: just write an abbreviated table file.
- * Before calling this, all parameters and a data destination must be set up.
- *
- * To produce a pair of files containing abbreviated tables and abbreviated
- * image data, one would proceed as follows:
- *
- *		initialize JPEG object
- *		set JPEG parameters
- *		set destination to table file
- *		jpeg_write_tables(cinfo);
- *		set destination to image file
- *		jpeg_start_compress(cinfo, FALSE);
- *		write data...
- *		jpeg_finish_compress(cinfo);
- *
- * jpeg_write_tables has the side effect of marking all tables written
- * (same as jpeg_suppress_tables(..., TRUE)).  Thus a subsequent start_compress
- * will not re-emit the tables unless it is passed write_all_tables=TRUE.
- */
-
-GLOBAL(void)
-jpeg_write_tables (j_compress_ptr cinfo)
-{
-  if (cinfo->global_state != CSTATE_START)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  /* (Re)initialize error mgr and destination modules */
-  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
-  (*cinfo->dest->init_destination) (cinfo);
-  /* Initialize the marker writer ... bit of a crock to do it here. */
-  jinit_marker_writer(cinfo);
-  /* Write them tables! */
-  (*cinfo->marker->write_tables_only) (cinfo);
-  /* And clean up. */
-  (*cinfo->dest->term_destination) (cinfo);
-  /*
-   * In library releases up through v6a, we called jpeg_abort() here to free
-   * any working memory allocated by the destination manager and marker
-   * writer.  Some applications had a problem with that: they allocated space
-   * of their own from the library memory manager, and didn't want it to go
-   * away during write_tables.  So now we do nothing.  This will cause a
-   * memory leak if an app calls write_tables repeatedly without doing a full
-   * compression cycle or otherwise resetting the JPEG object.  However, that
-   * seems less bad than unexpectedly freeing memory in the normal case.
-   * An app that prefers the old behavior can call jpeg_abort for itself after
-   * each call to jpeg_write_tables().
-   */
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcapistd.c ./Shared/jpeg-6b/jcapistd.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcapistd.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jcapistd.c	Wed Dec 31 19:00:00 1969
@@ -1,161 +0,0 @@
-/*
- * jcapistd.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains application interface code for the compression half
- * of the JPEG library.  These are the "standard" API routines that are
- * used in the normal full-compression case.  They are not used by a
- * transcoding-only application.  Note that if an application links in
- * jpeg_start_compress, it will end up linking in the entire compressor.
- * We thus must separate this file from jcapimin.c to avoid linking the
- * whole compression library into a transcoder.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * Compression initialization.
- * Before calling this, all parameters and a data destination must be set up.
- *
- * We require a write_all_tables parameter as a failsafe check when writing
- * multiple datastreams from the same compression object.  Since prior runs
- * will have left all the tables marked sent_table=TRUE, a subsequent run
- * would emit an abbreviated stream (no tables) by default.  This may be what
- * is wanted, but for safety's sake it should not be the default behavior:
- * programmers should have to make a deliberate choice to emit abbreviated
- * images.  Therefore the documentation and examples should encourage people
- * to pass write_all_tables=TRUE; then it will take active thought to do the
- * wrong thing.
- */
-
-GLOBAL(void)
-jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
-{
-  if (cinfo->global_state != CSTATE_START)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  if (write_all_tables)
-    jpeg_suppress_tables(cinfo, FALSE);	/* mark all tables to be written */
-
-  /* (Re)initialize error mgr and destination modules */
-  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
-  (*cinfo->dest->init_destination) (cinfo);
-  /* Perform master selection of active modules */
-  jinit_compress_master(cinfo);
-  /* Set up for the first pass */
-  (*cinfo->master->prepare_for_pass) (cinfo);
-  /* Ready for application to drive first pass through jpeg_write_scanlines
-   * or jpeg_write_raw_data.
-   */
-  cinfo->next_scanline = 0;
-  cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
-}
-
-
-/*
- * Write some scanlines of data to the JPEG compressor.
- *
- * The return value will be the number of lines actually written.
- * This should be less than the supplied num_lines only in case that
- * the data destination module has requested suspension of the compressor,
- * or if more than image_height scanlines are passed in.
- *
- * Note: we warn about excess calls to jpeg_write_scanlines() since
- * this likely signals an application programmer error.  However,
- * excess scanlines passed in the last valid call are *silently* ignored,
- * so that the application need not adjust num_lines for end-of-image
- * when using a multiple-scanline buffer.
- */
-
-GLOBAL(JDIMENSION)
-jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
-		      JDIMENSION num_lines)
-{
-  JDIMENSION row_ctr, rows_left;
-
-  if (cinfo->global_state != CSTATE_SCANNING)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  if (cinfo->next_scanline >= cinfo->image_height)
-    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
-
-  /* Call progress monitor hook if present */
-  if (cinfo->progress != NULL) {
-    cinfo->progress->pass_counter = (long) cinfo->next_scanline;
-    cinfo->progress->pass_limit = (long) cinfo->image_height;
-    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-  }
-
-  /* Give master control module another chance if this is first call to
-   * jpeg_write_scanlines.  This lets output of the frame/scan headers be
-   * delayed so that application can write COM, etc, markers between
-   * jpeg_start_compress and jpeg_write_scanlines.
-   */
-  if (cinfo->master->call_pass_startup)
-    (*cinfo->master->pass_startup) (cinfo);
-
-  /* Ignore any extra scanlines at bottom of image. */
-  rows_left = cinfo->image_height - cinfo->next_scanline;
-  if (num_lines > rows_left)
-    num_lines = rows_left;
-
-  row_ctr = 0;
-  (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
-  cinfo->next_scanline += row_ctr;
-  return row_ctr;
-}
-
-
-/*
- * Alternate entry point to write raw data.
- * Processes exactly one iMCU row per call, unless suspended.
- */
-
-GLOBAL(JDIMENSION)
-jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
-		     JDIMENSION num_lines)
-{
-  JDIMENSION lines_per_iMCU_row;
-
-  if (cinfo->global_state != CSTATE_RAW_OK)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  if (cinfo->next_scanline >= cinfo->image_height) {
-    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
-    return 0;
-  }
-
-  /* Call progress monitor hook if present */
-  if (cinfo->progress != NULL) {
-    cinfo->progress->pass_counter = (long) cinfo->next_scanline;
-    cinfo->progress->pass_limit = (long) cinfo->image_height;
-    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-  }
-
-  /* Give master control module another chance if this is first call to
-   * jpeg_write_raw_data.  This lets output of the frame/scan headers be
-   * delayed so that application can write COM, etc, markers between
-   * jpeg_start_compress and jpeg_write_raw_data.
-   */
-  if (cinfo->master->call_pass_startup)
-    (*cinfo->master->pass_startup) (cinfo);
-
-  /* Verify that at least one iMCU row has been passed. */
-  lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
-  if (num_lines < lines_per_iMCU_row)
-    ERREXIT(cinfo, JERR_BUFFER_SIZE);
-
-  /* Directly compress the row. */
-  if (! (*cinfo->coef->compress_data) (cinfo, data)) {
-    /* If compressor did not consume the whole row, suspend processing. */
-    return 0;
-  }
-
-  /* OK, we processed one iMCU row. */
-  cinfo->next_scanline += lines_per_iMCU_row;
-  return lines_per_iMCU_row;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jccoefct.c ./Shared/jpeg-6b/jccoefct.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jccoefct.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jccoefct.c	Wed Dec 31 19:00:00 1969
@@ -1,449 +0,0 @@
-/*
- * jccoefct.c
- *
- * Copyright (C) 1994-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the coefficient buffer controller for compression.
- * This controller is the top level of the JPEG compressor proper.
- * The coefficient buffer lies between forward-DCT and entropy encoding steps.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* We use a full-image coefficient buffer when doing Huffman optimization,
- * and also for writing multiple-scan JPEG files.  In all cases, the DCT
- * step is run during the first pass, and subsequent passes need only read
- * the buffered coefficients.
- */
-#ifdef ENTROPY_OPT_SUPPORTED
-#define FULL_COEF_BUFFER_SUPPORTED
-#else
-#ifdef C_MULTISCAN_FILES_SUPPORTED
-#define FULL_COEF_BUFFER_SUPPORTED
-#endif
-#endif
-
-
-/* Private buffer controller object */
-
-typedef struct {
-  struct jpeg_c_coef_controller pub; /* public fields */
-
-  JDIMENSION iMCU_row_num;	/* iMCU row # within image */
-  JDIMENSION mcu_ctr;		/* counts MCUs processed in current row */
-  int MCU_vert_offset;		/* counts MCU rows within iMCU row */
-  int MCU_rows_per_iMCU_row;	/* number of such rows needed */
-
-  /* For single-pass compression, it's sufficient to buffer just one MCU
-   * (although this may prove a bit slow in practice).  We allocate a
-   * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
-   * MCU constructed and sent.  (On 80x86, the workspace is FAR even though
-   * it's not really very big; this is to keep the module interfaces unchanged
-   * when a large coefficient buffer is necessary.)
-   * In multi-pass modes, this array points to the current MCU's blocks
-   * within the virtual arrays.
-   */
-  JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
-
-  /* In multi-pass modes, we need a virtual block array for each component. */
-  jvirt_barray_ptr whole_image[MAX_COMPONENTS];
-} my_coef_controller;
-
-typedef my_coef_controller * my_coef_ptr;
-
-
-/* Forward declarations */
-METHODDEF(boolean) compress_data
-    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
-#ifdef FULL_COEF_BUFFER_SUPPORTED
-METHODDEF(boolean) compress_first_pass
-    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
-METHODDEF(boolean) compress_output
-    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
-#endif
-
-
-LOCAL(void)
-start_iMCU_row (j_compress_ptr cinfo)
-/* Reset within-iMCU-row counters for a new row */
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-
-  /* In an interleaved scan, an MCU row is the same as an iMCU row.
-   * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
-   * But at the bottom of the image, process only what's left.
-   */
-  if (cinfo->comps_in_scan > 1) {
-    coef->MCU_rows_per_iMCU_row = 1;
-  } else {
-    if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
-      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
-    else
-      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
-  }
-
-  coef->mcu_ctr = 0;
-  coef->MCU_vert_offset = 0;
-}
-
-
-/*
- * Initialize for a processing pass.
- */
-
-METHODDEF(void)
-start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-
-  coef->iMCU_row_num = 0;
-  start_iMCU_row(cinfo);
-
-  switch (pass_mode) {
-  case JBUF_PASS_THRU:
-    if (coef->whole_image[0] != NULL)
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    coef->pub.compress_data = compress_data;
-    break;
-#ifdef FULL_COEF_BUFFER_SUPPORTED
-  case JBUF_SAVE_AND_PASS:
-    if (coef->whole_image[0] == NULL)
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    coef->pub.compress_data = compress_first_pass;
-    break;
-  case JBUF_CRANK_DEST:
-    if (coef->whole_image[0] == NULL)
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    coef->pub.compress_data = compress_output;
-    break;
-#endif
-  default:
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    break;
-  }
-}
-
-
-/*
- * Process some data in the single-pass case.
- * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
- * per call, ie, v_samp_factor block rows for each component in the image.
- * Returns TRUE if the iMCU row is completed, FALSE if suspended.
- *
- * NB: input_buf contains a plane for each component in image,
- * which we index according to the component's SOF position.
- */
-
-METHODDEF(boolean)
-compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION MCU_col_num;	/* index of current MCU within row */
-  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
-  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
-  int blkn, bi, ci, yindex, yoffset, blockcnt;
-  JDIMENSION ypos, xpos;
-  jpeg_component_info *compptr;
-
-  /* Loop to write as much as one whole iMCU row */
-  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
-       yoffset++) {
-    for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
-	 MCU_col_num++) {
-      /* Determine where data comes from in input_buf and do the DCT thing.
-       * Each call on forward_DCT processes a horizontal row of DCT blocks
-       * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
-       * sequentially.  Dummy blocks at the right or bottom edge are filled in
-       * specially.  The data in them does not matter for image reconstruction,
-       * so we fill them with values that will encode to the smallest amount of
-       * data, viz: all zeroes in the AC entries, DC entries equal to previous
-       * block's DC value.  (Thanks to Thomas Kinsman for this idea.)
-       */
-      blkn = 0;
-      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-	compptr = cinfo->cur_comp_info[ci];
-	blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
-						: compptr->last_col_width;
-	xpos = MCU_col_num * compptr->MCU_sample_width;
-	ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
-	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
-	  if (coef->iMCU_row_num < last_iMCU_row ||
-	      yoffset+yindex < compptr->last_row_height) {
-	    (*cinfo->fdct->forward_DCT) (cinfo, compptr,
-					 input_buf[compptr->component_index],
-					 coef->MCU_buffer[blkn],
-					 ypos, xpos, (JDIMENSION) blockcnt);
-	    if (blockcnt < compptr->MCU_width) {
-	      /* Create some dummy blocks at the right edge of the image. */
-	      jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
-			(compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
-	      for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
-		coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
-	      }
-	    }
-	  } else {
-	    /* Create a row of dummy blocks at the bottom of the image. */
-	    jzero_far((void FAR *) coef->MCU_buffer[blkn],
-		      compptr->MCU_width * SIZEOF(JBLOCK));
-	    for (bi = 0; bi < compptr->MCU_width; bi++) {
-	      coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
-	    }
-	  }
-	  blkn += compptr->MCU_width;
-	  ypos += DCTSIZE;
-	}
-      }
-      /* Try to write the MCU.  In event of a suspension failure, we will
-       * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
-       */
-      if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
-	/* Suspension forced; update state counters and exit */
-	coef->MCU_vert_offset = yoffset;
-	coef->mcu_ctr = MCU_col_num;
-	return FALSE;
-      }
-    }
-    /* Completed an MCU row, but perhaps not an iMCU row */
-    coef->mcu_ctr = 0;
-  }
-  /* Completed the iMCU row, advance counters for next one */
-  coef->iMCU_row_num++;
-  start_iMCU_row(cinfo);
-  return TRUE;
-}
-
-
-#ifdef FULL_COEF_BUFFER_SUPPORTED
-
-/*
- * Process some data in the first pass of a multi-pass case.
- * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
- * per call, ie, v_samp_factor block rows for each component in the image.
- * This amount of data is read from the source buffer, DCT'd and quantized,
- * and saved into the virtual arrays.  We also generate suitable dummy blocks
- * as needed at the right and lower edges.  (The dummy blocks are constructed
- * in the virtual arrays, which have been padded appropriately.)  This makes
- * it possible for subsequent passes not to worry about real vs. dummy blocks.
- *
- * We must also emit the data to the entropy encoder.  This is conveniently
- * done by calling compress_output() after we've loaded the current strip
- * of the virtual arrays.
- *
- * NB: input_buf contains a plane for each component in image.  All
- * components are DCT'd and loaded into the virtual arrays in this pass.
- * However, it may be that only a subset of the components are emitted to
- * the entropy encoder during this first pass; be careful about looking
- * at the scan-dependent variables (MCU dimensions, etc).
- */
-
-METHODDEF(boolean)
-compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
-  JDIMENSION blocks_across, MCUs_across, MCUindex;
-  int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
-  JCOEF lastDC;
-  jpeg_component_info *compptr;
-  JBLOCKARRAY buffer;
-  JBLOCKROW thisblockrow, lastblockrow;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Align the virtual buffer for this component. */
-    buffer = (*cinfo->mem->access_virt_barray)
-      ((j_common_ptr) cinfo, coef->whole_image[ci],
-       coef->iMCU_row_num * compptr->v_samp_factor,
-       (JDIMENSION) compptr->v_samp_factor, TRUE);
-    /* Count non-dummy DCT block rows in this iMCU row. */
-    if (coef->iMCU_row_num < last_iMCU_row)
-      block_rows = compptr->v_samp_factor;
-    else {
-      /* NB: can't use last_row_height here, since may not be set! */
-      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
-      if (block_rows == 0) block_rows = compptr->v_samp_factor;
-    }
-    blocks_across = compptr->width_in_blocks;
-    h_samp_factor = compptr->h_samp_factor;
-    /* Count number of dummy blocks to be added at the right margin. */
-    ndummy = (int) (blocks_across % h_samp_factor);
-    if (ndummy > 0)
-      ndummy = h_samp_factor - ndummy;
-    /* Perform DCT for all non-dummy blocks in this iMCU row.  Each call
-     * on forward_DCT processes a complete horizontal row of DCT blocks.
-     */
-    for (block_row = 0; block_row < block_rows; block_row++) {
-      thisblockrow = buffer[block_row];
-      (*cinfo->fdct->forward_DCT) (cinfo, compptr,
-				   input_buf[ci], thisblockrow,
-				   (JDIMENSION) (block_row * DCTSIZE),
-				   (JDIMENSION) 0, blocks_across);
-      if (ndummy > 0) {
-	/* Create dummy blocks at the right edge of the image. */
-	thisblockrow += blocks_across; /* => first dummy block */
-	jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
-	lastDC = thisblockrow[-1][0];
-	for (bi = 0; bi < ndummy; bi++) {
-	  thisblockrow[bi][0] = lastDC;
-	}
-      }
-    }
-    /* If at end of image, create dummy block rows as needed.
-     * The tricky part here is that within each MCU, we want the DC values
-     * of the dummy blocks to match the last real block's DC value.
-     * This squeezes a few more bytes out of the resulting file...
-     */
-    if (coef->iMCU_row_num == last_iMCU_row) {
-      blocks_across += ndummy;	/* include lower right corner */
-      MCUs_across = blocks_across / h_samp_factor;
-      for (block_row = block_rows; block_row < compptr->v_samp_factor;
-	   block_row++) {
-	thisblockrow = buffer[block_row];
-	lastblockrow = buffer[block_row-1];
-	jzero_far((void FAR *) thisblockrow,
-		  (size_t) (blocks_across * SIZEOF(JBLOCK)));
-	for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
-	  lastDC = lastblockrow[h_samp_factor-1][0];
-	  for (bi = 0; bi < h_samp_factor; bi++) {
-	    thisblockrow[bi][0] = lastDC;
-	  }
-	  thisblockrow += h_samp_factor; /* advance to next MCU in row */
-	  lastblockrow += h_samp_factor;
-	}
-      }
-    }
-  }
-  /* NB: compress_output will increment iMCU_row_num if successful.
-   * A suspension return will result in redoing all the work above next time.
-   */
-
-  /* Emit data to the entropy encoder, sharing code with subsequent passes */
-  return compress_output(cinfo, input_buf);
-}
-
-
-/*
- * Process some data in subsequent passes of a multi-pass case.
- * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
- * per call, ie, v_samp_factor block rows for each component in the scan.
- * The data is obtained from the virtual arrays and fed to the entropy coder.
- * Returns TRUE if the iMCU row is completed, FALSE if suspended.
- *
- * NB: input_buf is ignored; it is likely to be a NULL pointer.
- */
-
-METHODDEF(boolean)
-compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION MCU_col_num;	/* index of current MCU within row */
-  int blkn, ci, xindex, yindex, yoffset;
-  JDIMENSION start_col;
-  JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
-  JBLOCKROW buffer_ptr;
-  jpeg_component_info *compptr;
-
-  /* Align the virtual buffers for the components used in this scan.
-   * NB: during first pass, this is safe only because the buffers will
-   * already be aligned properly, so jmemmgr.c won't need to do any I/O.
-   */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    buffer[ci] = (*cinfo->mem->access_virt_barray)
-      ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
-       coef->iMCU_row_num * compptr->v_samp_factor,
-       (JDIMENSION) compptr->v_samp_factor, FALSE);
-  }
-
-  /* Loop to process one whole iMCU row */
-  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
-       yoffset++) {
-    for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
-	 MCU_col_num++) {
-      /* Construct list of pointers to DCT blocks belonging to this MCU */
-      blkn = 0;			/* index of current DCT block within MCU */
-      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-	compptr = cinfo->cur_comp_info[ci];
-	start_col = MCU_col_num * compptr->MCU_width;
-	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
-	  buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
-	  for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
-	    coef->MCU_buffer[blkn++] = buffer_ptr++;
-	  }
-	}
-      }
-      /* Try to write the MCU. */
-      if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
-	/* Suspension forced; update state counters and exit */
-	coef->MCU_vert_offset = yoffset;
-	coef->mcu_ctr = MCU_col_num;
-	return FALSE;
-      }
-    }
-    /* Completed an MCU row, but perhaps not an iMCU row */
-    coef->mcu_ctr = 0;
-  }
-  /* Completed the iMCU row, advance counters for next one */
-  coef->iMCU_row_num++;
-  start_iMCU_row(cinfo);
-  return TRUE;
-}
-
-#endif /* FULL_COEF_BUFFER_SUPPORTED */
-
-
-/*
- * Initialize coefficient buffer controller.
- */
-
-GLOBAL(void)
-jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
-{
-  my_coef_ptr coef;
-
-  coef = (my_coef_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_coef_controller));
-  cinfo->coef = (struct jpeg_c_coef_controller *) coef;
-  coef->pub.start_pass = start_pass_coef;
-
-  /* Create the coefficient buffer. */
-  if (need_full_buffer) {
-#ifdef FULL_COEF_BUFFER_SUPPORTED
-    /* Allocate a full-image virtual array for each component, */
-    /* padded to a multiple of samp_factor DCT blocks in each direction. */
-    int ci;
-    jpeg_component_info *compptr;
-
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-	 (JDIMENSION) jround_up((long) compptr->width_in_blocks,
-				(long) compptr->h_samp_factor),
-	 (JDIMENSION) jround_up((long) compptr->height_in_blocks,
-				(long) compptr->v_samp_factor),
-	 (JDIMENSION) compptr->v_samp_factor);
-    }
-#else
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-#endif
-  } else {
-    /* We only need a single-MCU buffer. */
-    JBLOCKROW buffer;
-    int i;
-
-    buffer = (JBLOCKROW)
-      (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
-    for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
-      coef->MCU_buffer[i] = buffer + i;
-    }
-    coef->whole_image[0] = NULL; /* flag for no virtual arrays */
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jccolor.c ./Shared/jpeg-6b/jccolor.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jccolor.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jccolor.c	Wed Dec 31 19:00:00 1969
@@ -1,459 +0,0 @@
-/*
- * jccolor.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains input colorspace conversion routines.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Private subobject */
-
-typedef struct {
-  struct jpeg_color_converter pub; /* public fields */
-
-  /* Private state for RGB->YCC conversion */
-  INT32 * rgb_ycc_tab;		/* => table for RGB to YCbCr conversion */
-} my_color_converter;
-
-typedef my_color_converter * my_cconvert_ptr;
-
-
-/**************** RGB -> YCbCr conversion: most common case **************/
-
-/*
- * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
- * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
- * The conversion equations to be implemented are therefore
- *	Y  =  0.29900 * R + 0.58700 * G + 0.11400 * B
- *	Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B  + CENTERJSAMPLE
- *	Cr =  0.50000 * R - 0.41869 * G - 0.08131 * B  + CENTERJSAMPLE
- * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
- * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
- * rather than CENTERJSAMPLE, for Cb and Cr.  This gave equal positive and
- * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
- * were not represented exactly.  Now we sacrifice exact representation of
- * maximum red and maximum blue in order to get exact grayscales.
- *
- * To avoid floating-point arithmetic, we represent the fractional constants
- * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
- * the products by 2^16, with appropriate rounding, to get the correct answer.
- *
- * For even more speed, we avoid doing any multiplications in the inner loop
- * by precalculating the constants times R,G,B for all possible values.
- * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
- * for 12-bit samples it is still acceptable.  It's not very reasonable for
- * 16-bit samples, but if you want lossless storage you shouldn't be changing
- * colorspace anyway.
- * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
- * in the tables to save adding them separately in the inner loop.
- */
-
-#define SCALEBITS	16	/* speediest right-shift on some machines */
-#define CBCR_OFFSET	((INT32) CENTERJSAMPLE << SCALEBITS)
-#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
-#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
-
-/* We allocate one big table and divide it up into eight parts, instead of
- * doing eight alloc_small requests.  This lets us use a single table base
- * address, which can be held in a register in the inner loops on many
- * machines (more than can hold all eight addresses, anyway).
- */
-
-#define R_Y_OFF		0			/* offset to R => Y section */
-#define G_Y_OFF		(1*(MAXJSAMPLE+1))	/* offset to G => Y section */
-#define B_Y_OFF		(2*(MAXJSAMPLE+1))	/* etc. */
-#define R_CB_OFF	(3*(MAXJSAMPLE+1))
-#define G_CB_OFF	(4*(MAXJSAMPLE+1))
-#define B_CB_OFF	(5*(MAXJSAMPLE+1))
-#define R_CR_OFF	B_CB_OFF		/* B=>Cb, R=>Cr are the same */
-#define G_CR_OFF	(6*(MAXJSAMPLE+1))
-#define B_CR_OFF	(7*(MAXJSAMPLE+1))
-#define TABLE_SIZE	(8*(MAXJSAMPLE+1))
-
-
-/*
- * Initialize for RGB->YCC colorspace conversion.
- */
-
-METHODDEF(void)
-rgb_ycc_start (j_compress_ptr cinfo)
-{
-  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
-  INT32 * rgb_ycc_tab;
-  INT32 i;
-
-  /* Allocate and fill in the conversion tables. */
-  cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(TABLE_SIZE * SIZEOF(INT32)));
-
-  for (i = 0; i <= MAXJSAMPLE; i++) {
-    rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
-    rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
-    rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i     + ONE_HALF;
-    rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
-    rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
-    /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
-     * This ensures that the maximum output will round to MAXJSAMPLE
-     * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
-     */
-    rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i    + CBCR_OFFSET + ONE_HALF-1;
-/*  B=>Cb and R=>Cr tables are the same
-    rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i    + CBCR_OFFSET + ONE_HALF-1;
-*/
-    rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
-    rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
-  }
-}
-
-
-/*
- * Convert some rows of samples to the JPEG colorspace.
- *
- * Note that we change from the application's interleaved-pixel format
- * to our internal noninterleaved, one-plane-per-component format.
- * The input buffer is therefore three times as wide as the output buffer.
- *
- * A starting row offset is provided only for the output buffer.  The caller
- * can easily adjust the passed input_buf value to accommodate any row
- * offset required on that side.
- */
-
-METHODDEF(void)
-rgb_ycc_convert (j_compress_ptr cinfo,
-		 JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		 JDIMENSION output_row, int num_rows)
-{
-  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
-  register int r, g, b;
-  register INT32 * ctab = cconvert->rgb_ycc_tab;
-  register JSAMPROW inptr;
-  register JSAMPROW outptr0, outptr1, outptr2;
-  register JDIMENSION col;
-  JDIMENSION num_cols = cinfo->image_width;
-
-  while (--num_rows >= 0) {
-    inptr = *input_buf++;
-    outptr0 = output_buf[0][output_row];
-    outptr1 = output_buf[1][output_row];
-    outptr2 = output_buf[2][output_row];
-    output_row++;
-    for (col = 0; col < num_cols; col++) {
-      r = GETJSAMPLE(inptr[RGB_RED]);
-      g = GETJSAMPLE(inptr[RGB_GREEN]);
-      b = GETJSAMPLE(inptr[RGB_BLUE]);
-      inptr += RGB_PIXELSIZE;
-      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
-       * must be too; we do not need an explicit range-limiting operation.
-       * Hence the value being shifted is never negative, and we don't
-       * need the general RIGHT_SHIFT macro.
-       */
-      /* Y */
-      outptr0[col] = (JSAMPLE)
-		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
-		 >> SCALEBITS);
-      /* Cb */
-      outptr1[col] = (JSAMPLE)
-		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
-		 >> SCALEBITS);
-      /* Cr */
-      outptr2[col] = (JSAMPLE)
-		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
-		 >> SCALEBITS);
-    }
-  }
-}
-
-
-/**************** Cases other than RGB -> YCbCr **************/
-
-
-/*
- * Convert some rows of samples to the JPEG colorspace.
- * This version handles RGB->grayscale conversion, which is the same
- * as the RGB->Y portion of RGB->YCbCr.
- * We assume rgb_ycc_start has been called (we only use the Y tables).
- */
-
-METHODDEF(void)
-rgb_gray_convert (j_compress_ptr cinfo,
-		  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		  JDIMENSION output_row, int num_rows)
-{
-  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
-  register int r, g, b;
-  register INT32 * ctab = cconvert->rgb_ycc_tab;
-  register JSAMPROW inptr;
-  register JSAMPROW outptr;
-  register JDIMENSION col;
-  JDIMENSION num_cols = cinfo->image_width;
-
-  while (--num_rows >= 0) {
-    inptr = *input_buf++;
-    outptr = output_buf[0][output_row];
-    output_row++;
-    for (col = 0; col < num_cols; col++) {
-      r = GETJSAMPLE(inptr[RGB_RED]);
-      g = GETJSAMPLE(inptr[RGB_GREEN]);
-      b = GETJSAMPLE(inptr[RGB_BLUE]);
-      inptr += RGB_PIXELSIZE;
-      /* Y */
-      outptr[col] = (JSAMPLE)
-		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
-		 >> SCALEBITS);
-    }
-  }
-}
-
-
-/*
- * Convert some rows of samples to the JPEG colorspace.
- * This version handles Adobe-style CMYK->YCCK conversion,
- * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
- * conversion as above, while passing K (black) unchanged.
- * We assume rgb_ycc_start has been called.
- */
-
-METHODDEF(void)
-cmyk_ycck_convert (j_compress_ptr cinfo,
-		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		   JDIMENSION output_row, int num_rows)
-{
-  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
-  register int r, g, b;
-  register INT32 * ctab = cconvert->rgb_ycc_tab;
-  register JSAMPROW inptr;
-  register JSAMPROW outptr0, outptr1, outptr2, outptr3;
-  register JDIMENSION col;
-  JDIMENSION num_cols = cinfo->image_width;
-
-  while (--num_rows >= 0) {
-    inptr = *input_buf++;
-    outptr0 = output_buf[0][output_row];
-    outptr1 = output_buf[1][output_row];
-    outptr2 = output_buf[2][output_row];
-    outptr3 = output_buf[3][output_row];
-    output_row++;
-    for (col = 0; col < num_cols; col++) {
-      r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
-      g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
-      b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
-      /* K passes through as-is */
-      outptr3[col] = inptr[3];	/* don't need GETJSAMPLE here */
-      inptr += 4;
-      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
-       * must be too; we do not need an explicit range-limiting operation.
-       * Hence the value being shifted is never negative, and we don't
-       * need the general RIGHT_SHIFT macro.
-       */
-      /* Y */
-      outptr0[col] = (JSAMPLE)
-		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
-		 >> SCALEBITS);
-      /* Cb */
-      outptr1[col] = (JSAMPLE)
-		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
-		 >> SCALEBITS);
-      /* Cr */
-      outptr2[col] = (JSAMPLE)
-		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
-		 >> SCALEBITS);
-    }
-  }
-}
-
-
-/*
- * Convert some rows of samples to the JPEG colorspace.
- * This version handles grayscale output with no conversion.
- * The source can be either plain grayscale or YCbCr (since Y == gray).
- */
-
-METHODDEF(void)
-grayscale_convert (j_compress_ptr cinfo,
-		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-		   JDIMENSION output_row, int num_rows)
-{
-  register JSAMPROW inptr;
-  register JSAMPROW outptr;
-  register JDIMENSION col;
-  JDIMENSION num_cols = cinfo->image_width;
-  int instride = cinfo->input_components;
-
-  while (--num_rows >= 0) {
-    inptr = *input_buf++;
-    outptr = output_buf[0][output_row];
-    output_row++;
-    for (col = 0; col < num_cols; col++) {
-      outptr[col] = inptr[0];	/* don't need GETJSAMPLE() here */
-      inptr += instride;
-    }
-  }
-}
-
-
-/*
- * Convert some rows of samples to the JPEG colorspace.
- * This version handles multi-component colorspaces without conversion.
- * We assume input_components == num_components.
- */
-
-METHODDEF(void)
-null_convert (j_compress_ptr cinfo,
-	      JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-	      JDIMENSION output_row, int num_rows)
-{
-  register JSAMPROW inptr;
-  register JSAMPROW outptr;
-  register JDIMENSION col;
-  register int ci;
-  int nc = cinfo->num_components;
-  JDIMENSION num_cols = cinfo->image_width;
-
-  while (--num_rows >= 0) {
-    /* It seems fastest to make a separate pass for each component. */
-    for (ci = 0; ci < nc; ci++) {
-      inptr = *input_buf;
-      outptr = output_buf[ci][output_row];
-      for (col = 0; col < num_cols; col++) {
-	outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
-	inptr += nc;
-      }
-    }
-    input_buf++;
-    output_row++;
-  }
-}
-
-
-/*
- * Empty method for start_pass.
- */
-
-METHODDEF(void)
-null_method (j_compress_ptr cinfo)
-{
-  /* no work needed */
-}
-
-
-/*
- * Module initialization routine for input colorspace conversion.
- */
-
-GLOBAL(void)
-jinit_color_converter (j_compress_ptr cinfo)
-{
-  my_cconvert_ptr cconvert;
-
-  cconvert = (my_cconvert_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_color_converter));
-  cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
-  /* set start_pass to null method until we find out differently */
-  cconvert->pub.start_pass = null_method;
-
-  /* Make sure input_components agrees with in_color_space */
-  switch (cinfo->in_color_space) {
-  case JCS_GRAYSCALE:
-    if (cinfo->input_components != 1)
-      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
-    break;
-
-  case JCS_RGB:
-#if RGB_PIXELSIZE != 3
-    if (cinfo->input_components != RGB_PIXELSIZE)
-      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
-    break;
-#endif /* else share code with YCbCr */
-
-  case JCS_YCbCr:
-    if (cinfo->input_components != 3)
-      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
-    break;
-
-  case JCS_CMYK:
-  case JCS_YCCK:
-    if (cinfo->input_components != 4)
-      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
-    break;
-
-  default:			/* JCS_UNKNOWN can be anything */
-    if (cinfo->input_components < 1)
-      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
-    break;
-  }
-
-  /* Check num_components, set conversion method based on requested space */
-  switch (cinfo->jpeg_color_space) {
-  case JCS_GRAYSCALE:
-    if (cinfo->num_components != 1)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    if (cinfo->in_color_space == JCS_GRAYSCALE)
-      cconvert->pub.color_convert = grayscale_convert;
-    else if (cinfo->in_color_space == JCS_RGB) {
-      cconvert->pub.start_pass = rgb_ycc_start;
-      cconvert->pub.color_convert = rgb_gray_convert;
-    } else if (cinfo->in_color_space == JCS_YCbCr)
-      cconvert->pub.color_convert = grayscale_convert;
-    else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  case JCS_RGB:
-    if (cinfo->num_components != 3)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
-      cconvert->pub.color_convert = null_convert;
-    else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  case JCS_YCbCr:
-    if (cinfo->num_components != 3)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    if (cinfo->in_color_space == JCS_RGB) {
-      cconvert->pub.start_pass = rgb_ycc_start;
-      cconvert->pub.color_convert = rgb_ycc_convert;
-    } else if (cinfo->in_color_space == JCS_YCbCr)
-      cconvert->pub.color_convert = null_convert;
-    else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  case JCS_CMYK:
-    if (cinfo->num_components != 4)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    if (cinfo->in_color_space == JCS_CMYK)
-      cconvert->pub.color_convert = null_convert;
-    else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  case JCS_YCCK:
-    if (cinfo->num_components != 4)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    if (cinfo->in_color_space == JCS_CMYK) {
-      cconvert->pub.start_pass = rgb_ycc_start;
-      cconvert->pub.color_convert = cmyk_ycck_convert;
-    } else if (cinfo->in_color_space == JCS_YCCK)
-      cconvert->pub.color_convert = null_convert;
-    else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  default:			/* allow null conversion of JCS_UNKNOWN */
-    if (cinfo->jpeg_color_space != cinfo->in_color_space ||
-	cinfo->num_components != cinfo->input_components)
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    cconvert->pub.color_convert = null_convert;
-    break;
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcdctmgr.c ./Shared/jpeg-6b/jcdctmgr.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcdctmgr.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jcdctmgr.c	Wed Dec 31 19:00:00 1969
@@ -1,387 +0,0 @@
-/*
- * jcdctmgr.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the forward-DCT management logic.
- * This code selects a particular DCT implementation to be used,
- * and it performs related housekeeping chores including coefficient
- * quantization.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-
-/* Private subobject for this module */
-
-typedef struct {
-  struct jpeg_forward_dct pub;	/* public fields */
-
-  /* Pointer to the DCT routine actually in use */
-  forward_DCT_method_ptr do_dct;
-
-  /* The actual post-DCT divisors --- not identical to the quant table
-   * entries, because of scaling (especially for an unnormalized DCT).
-   * Each table is given in normal array order.
-   */
-  DCTELEM * divisors[NUM_QUANT_TBLS];
-
-#ifdef DCT_FLOAT_SUPPORTED
-  /* Same as above for the floating-point case. */
-  float_DCT_method_ptr do_float_dct;
-  FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
-#endif
-} my_fdct_controller;
-
-typedef my_fdct_controller * my_fdct_ptr;
-
-
-/*
- * Initialize for a processing pass.
- * Verify that all referenced Q-tables are present, and set up
- * the divisor table for each one.
- * In the current implementation, DCT of all components is done during
- * the first pass, even if only some components will be output in the
- * first scan.  Hence all components should be examined here.
- */
-
-METHODDEF(void)
-start_pass_fdctmgr (j_compress_ptr cinfo)
-{
-  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
-  int ci, qtblno, i;
-  jpeg_component_info *compptr;
-  JQUANT_TBL * qtbl;
-  DCTELEM * dtbl;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    qtblno = compptr->quant_tbl_no;
-    /* Make sure specified quantization table is present */
-    if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
-	cinfo->quant_tbl_ptrs[qtblno] == NULL)
-      ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
-    qtbl = cinfo->quant_tbl_ptrs[qtblno];
-    /* Compute divisors for this quant table */
-    /* We may do this more than once for same table, but it's not a big deal */
-    switch (cinfo->dct_method) {
-#ifdef DCT_ISLOW_SUPPORTED
-    case JDCT_ISLOW:
-      /* For LL&M IDCT method, divisors are equal to raw quantization
-       * coefficients multiplied by 8 (to counteract scaling).
-       */
-      if (fdct->divisors[qtblno] == NULL) {
-	fdct->divisors[qtblno] = (DCTELEM *)
-	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				      DCTSIZE2 * SIZEOF(DCTELEM));
-      }
-      dtbl = fdct->divisors[qtblno];
-      for (i = 0; i < DCTSIZE2; i++) {
-	dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
-      }
-      break;
-#endif
-#ifdef DCT_IFAST_SUPPORTED
-    case JDCT_IFAST:
-      {
-	/* For AA&N IDCT method, divisors are equal to quantization
-	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
-	 *   scalefactor[0] = 1
-	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
-	 * We apply a further scale factor of 8.
-	 */
-#define CONST_BITS 14
-	static const INT16 aanscales[DCTSIZE2] = {
-	  /* precomputed values scaled up by 14 bits */
-	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
-	  22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
-	  21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
-	  19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
-	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
-	  12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
-	   8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
-	   4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
-	};
-	SHIFT_TEMPS
-
-	if (fdct->divisors[qtblno] == NULL) {
-	  fdct->divisors[qtblno] = (DCTELEM *)
-	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-					DCTSIZE2 * SIZEOF(DCTELEM));
-	}
-	dtbl = fdct->divisors[qtblno];
-	for (i = 0; i < DCTSIZE2; i++) {
-	  dtbl[i] = (DCTELEM)
-	    DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
-				  (INT32) aanscales[i]),
-		    CONST_BITS-3);
-	}
-      }
-      break;
-#endif
-#ifdef DCT_FLOAT_SUPPORTED
-    case JDCT_FLOAT:
-      {
-	/* For float AA&N IDCT method, divisors are equal to quantization
-	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
-	 *   scalefactor[0] = 1
-	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
-	 * We apply a further scale factor of 8.
-	 * What's actually stored is 1/divisor so that the inner loop can
-	 * use a multiplication rather than a division.
-	 */
-	FAST_FLOAT * fdtbl;
-	int row, col;
-	static const double aanscalefactor[DCTSIZE] = {
-	  1.0, 1.387039845, 1.306562965, 1.175875602,
-	  1.0, 0.785694958, 0.541196100, 0.275899379
-	};
-
-	if (fdct->float_divisors[qtblno] == NULL) {
-	  fdct->float_divisors[qtblno] = (FAST_FLOAT *)
-	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-					DCTSIZE2 * SIZEOF(FAST_FLOAT));
-	}
-	fdtbl = fdct->float_divisors[qtblno];
-	i = 0;
-	for (row = 0; row < DCTSIZE; row++) {
-	  for (col = 0; col < DCTSIZE; col++) {
-	    fdtbl[i] = (FAST_FLOAT)
-	      (1.0 / (((double) qtbl->quantval[i] *
-		       aanscalefactor[row] * aanscalefactor[col] * 8.0)));
-	    i++;
-	  }
-	}
-      }
-      break;
-#endif
-    default:
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-      break;
-    }
-  }
-}
-
-
-/*
- * Perform forward DCT on one or more blocks of a component.
- *
- * The input samples are taken from the sample_data[] array starting at
- * position start_row/start_col, and moving to the right for any additional
- * blocks. The quantized coefficients are returned in coef_blocks[].
- */
-
-METHODDEF(void)
-forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
-	     JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
-	     JDIMENSION start_row, JDIMENSION start_col,
-	     JDIMENSION num_blocks)
-/* This version is used for integer DCT implementations. */
-{
-  /* This routine is heavily used, so it's worth coding it tightly. */
-  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
-  forward_DCT_method_ptr do_dct = fdct->do_dct;
-  DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
-  DCTELEM workspace[DCTSIZE2];	/* work area for FDCT subroutine */
-  JDIMENSION bi;
-
-  sample_data += start_row;	/* fold in the vertical offset once */
-
-  for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
-    /* Load data into workspace, applying unsigned->signed conversion */
-    { register DCTELEM *workspaceptr;
-      register JSAMPROW elemptr;
-      register int elemr;
-
-      workspaceptr = workspace;
-      for (elemr = 0; elemr < DCTSIZE; elemr++) {
-	elemptr = sample_data[elemr] + start_col;
-#if DCTSIZE == 8		/* unroll the inner loop */
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-#else
-	{ register int elemc;
-	  for (elemc = DCTSIZE; elemc > 0; elemc--) {
-	    *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
-	  }
-	}
-#endif
-      }
-    }
-
-    /* Perform the DCT */
-    (*do_dct) (workspace);
-
-    /* Quantize/descale the coefficients, and store into coef_blocks[] */
-    { register DCTELEM temp, qval;
-      register int i;
-      register JCOEFPTR output_ptr = coef_blocks[bi];
-
-      for (i = 0; i < DCTSIZE2; i++) {
-	qval = divisors[i];
-	temp = workspace[i];
-	/* Divide the coefficient value by qval, ensuring proper rounding.
-	 * Since C does not specify the direction of rounding for negative
-	 * quotients, we have to force the dividend positive for portability.
-	 *
-	 * In most files, at least half of the output values will be zero
-	 * (at default quantization settings, more like three-quarters...)
-	 * so we should ensure that this case is fast.  On many machines,
-	 * a comparison is enough cheaper than a divide to make a special test
-	 * a win.  Since both inputs will be nonnegative, we need only test
-	 * for a < b to discover whether a/b is 0.
-	 * If your machine's division is fast enough, define FAST_DIVIDE.
-	 */
-#ifdef FAST_DIVIDE
-#define DIVIDE_BY(a,b)	a /= b
-#else
-#define DIVIDE_BY(a,b)	if (a >= b) a /= b; else a = 0
-#endif
-	if (temp < 0) {
-	  temp = -temp;
-	  temp += qval>>1;	/* for rounding */
-	  DIVIDE_BY(temp, qval);
-	  temp = -temp;
-	} else {
-	  temp += qval>>1;	/* for rounding */
-	  DIVIDE_BY(temp, qval);
-	}
-	output_ptr[i] = (JCOEF) temp;
-      }
-    }
-  }
-}
-
-
-#ifdef DCT_FLOAT_SUPPORTED
-
-METHODDEF(void)
-forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
-		   JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
-		   JDIMENSION start_row, JDIMENSION start_col,
-		   JDIMENSION num_blocks)
-/* This version is used for floating-point DCT implementations. */
-{
-  /* This routine is heavily used, so it's worth coding it tightly. */
-  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
-  float_DCT_method_ptr do_dct = fdct->do_float_dct;
-  FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
-  FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
-  JDIMENSION bi;
-
-  sample_data += start_row;	/* fold in the vertical offset once */
-
-  for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
-    /* Load data into workspace, applying unsigned->signed conversion */
-    { register FAST_FLOAT *workspaceptr;
-      register JSAMPROW elemptr;
-      register int elemr;
-
-      workspaceptr = workspace;
-      for (elemr = 0; elemr < DCTSIZE; elemr++) {
-	elemptr = sample_data[elemr] + start_col;
-#if DCTSIZE == 8		/* unroll the inner loop */
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	*workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-#else
-	{ register int elemc;
-	  for (elemc = DCTSIZE; elemc > 0; elemc--) {
-	    *workspaceptr++ = (FAST_FLOAT)
-	      (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
-	  }
-	}
-#endif
-      }
-    }
-
-    /* Perform the DCT */
-    (*do_dct) (workspace);
-
-    /* Quantize/descale the coefficients, and store into coef_blocks[] */
-    { register FAST_FLOAT temp;
-      register int i;
-      register JCOEFPTR output_ptr = coef_blocks[bi];
-
-      for (i = 0; i < DCTSIZE2; i++) {
-	/* Apply the quantization and scaling factor */
-	temp = workspace[i] * divisors[i];
-	/* Round to nearest integer.
-	 * Since C does not specify the direction of rounding for negative
-	 * quotients, we have to force the dividend positive for portability.
-	 * The maximum coefficient size is +-16K (for 12-bit data), so this
-	 * code should work for either 16-bit or 32-bit ints.
-	 */
-	output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
-      }
-    }
-  }
-}
-
-#endif /* DCT_FLOAT_SUPPORTED */
-
-
-/*
- * Initialize FDCT manager.
- */
-
-GLOBAL(void)
-jinit_forward_dct (j_compress_ptr cinfo)
-{
-  my_fdct_ptr fdct;
-  int i;
-
-  fdct = (my_fdct_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_fdct_controller));
-  cinfo->fdct = (struct jpeg_forward_dct *) fdct;
-  fdct->pub.start_pass = start_pass_fdctmgr;
-
-  switch (cinfo->dct_method) {
-#ifdef DCT_ISLOW_SUPPORTED
-  case JDCT_ISLOW:
-    fdct->pub.forward_DCT = forward_DCT;
-    fdct->do_dct = jpeg_fdct_islow;
-    break;
-#endif
-#ifdef DCT_IFAST_SUPPORTED
-  case JDCT_IFAST:
-    fdct->pub.forward_DCT = forward_DCT;
-    fdct->do_dct = jpeg_fdct_ifast;
-    break;
-#endif
-#ifdef DCT_FLOAT_SUPPORTED
-  case JDCT_FLOAT:
-    fdct->pub.forward_DCT = forward_DCT_float;
-    fdct->do_float_dct = jpeg_fdct_float;
-    break;
-#endif
-  default:
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-    break;
-  }
-
-  /* Mark divisor tables unallocated */
-  for (i = 0; i < NUM_QUANT_TBLS; i++) {
-    fdct->divisors[i] = NULL;
-#ifdef DCT_FLOAT_SUPPORTED
-    fdct->float_divisors[i] = NULL;
-#endif
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jchuff.c ./Shared/jpeg-6b/jchuff.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jchuff.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jchuff.c	Wed Dec 31 19:00:00 1969
@@ -1,909 +0,0 @@
-/*
- * jchuff.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains Huffman entropy encoding routines.
- *
- * Much of the complexity here has to do with supporting output suspension.
- * If the data destination module demands suspension, we want to be able to
- * back up to the start of the current MCU.  To do this, we copy state
- * variables into local working storage, and update them back to the
- * permanent JPEG objects only upon successful completion of an MCU.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jchuff.h"		/* Declarations shared with jcphuff.c */
-
-
-/* Expanded entropy encoder object for Huffman encoding.
- *
- * The savable_state subrecord contains fields that change within an MCU,
- * but must not be updated permanently until we complete the MCU.
- */
-
-typedef struct {
-  INT32 put_buffer;		/* current bit-accumulation buffer */
-  int put_bits;			/* # of bits now in it */
-  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
-} savable_state;
-
-/* This macro is to work around compilers with missing or broken
- * structure assignment.  You'll need to fix this code if you have
- * such a compiler and you change MAX_COMPS_IN_SCAN.
- */
-
-#ifndef NO_STRUCT_ASSIGN
-#define ASSIGN_STATE(dest,src)  ((dest) = (src))
-#else
-#if MAX_COMPS_IN_SCAN == 4
-#define ASSIGN_STATE(dest,src)  \
-	((dest).put_buffer = (src).put_buffer, \
-	 (dest).put_bits = (src).put_bits, \
-	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
-	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
-	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
-	 (dest).last_dc_val[3] = (src).last_dc_val[3])
-#endif
-#endif
-
-
-typedef struct {
-  struct jpeg_entropy_encoder pub; /* public fields */
-
-  savable_state saved;		/* Bit buffer & DC state at start of MCU */
-
-  /* These fields are NOT loaded into local working state. */
-  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
-  int next_restart_num;		/* next restart number to write (0-7) */
-
-  /* Pointers to derived tables (these workspaces have image lifespan) */
-  c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
-  c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
-
-#ifdef ENTROPY_OPT_SUPPORTED	/* Statistics tables for optimization */
-  long * dc_count_ptrs[NUM_HUFF_TBLS];
-  long * ac_count_ptrs[NUM_HUFF_TBLS];
-#endif
-} huff_entropy_encoder;
-
-typedef huff_entropy_encoder * huff_entropy_ptr;
-
-/* Working state while writing an MCU.
- * This struct contains all the fields that are needed by subroutines.
- */
-
-typedef struct {
-  JOCTET * next_output_byte;	/* => next byte to write in buffer */
-  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
-  savable_state cur;		/* Current bit buffer & DC state */
-  j_compress_ptr cinfo;		/* dump_buffer needs access to this */
-} working_state;
-
-
-/* Forward declarations */
-METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
-					JBLOCKROW *MCU_data));
-METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
-#ifdef ENTROPY_OPT_SUPPORTED
-METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
-					  JBLOCKROW *MCU_data));
-METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
-#endif
-
-
-/*
- * Initialize for a Huffman-compressed scan.
- * If gather_statistics is TRUE, we do not output anything during the scan,
- * just count the Huffman symbols used and generate Huffman code tables.
- */
-
-METHODDEF(void)
-start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  int ci, dctbl, actbl;
-  jpeg_component_info * compptr;
-
-  if (gather_statistics) {
-#ifdef ENTROPY_OPT_SUPPORTED
-    entropy->pub.encode_mcu = encode_mcu_gather;
-    entropy->pub.finish_pass = finish_pass_gather;
-#else
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-  } else {
-    entropy->pub.encode_mcu = encode_mcu_huff;
-    entropy->pub.finish_pass = finish_pass_huff;
-  }
-
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    dctbl = compptr->dc_tbl_no;
-    actbl = compptr->ac_tbl_no;
-    if (gather_statistics) {
-#ifdef ENTROPY_OPT_SUPPORTED
-      /* Check for invalid table indexes */
-      /* (make_c_derived_tbl does this in the other path) */
-      if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
-	ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
-      if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
-	ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
-      /* Allocate and zero the statistics tables */
-      /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
-      if (entropy->dc_count_ptrs[dctbl] == NULL)
-	entropy->dc_count_ptrs[dctbl] = (long *)
-	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				      257 * SIZEOF(long));
-      MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
-      if (entropy->ac_count_ptrs[actbl] == NULL)
-	entropy->ac_count_ptrs[actbl] = (long *)
-	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				      257 * SIZEOF(long));
-      MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
-#endif
-    } else {
-      /* Compute derived values for Huffman tables */
-      /* We may do this more than once for a table, but it's not expensive */
-      jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
-			      & entropy->dc_derived_tbls[dctbl]);
-      jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
-			      & entropy->ac_derived_tbls[actbl]);
-    }
-    /* Initialize DC predictions to 0 */
-    entropy->saved.last_dc_val[ci] = 0;
-  }
-
-  /* Initialize bit buffer to empty */
-  entropy->saved.put_buffer = 0;
-  entropy->saved.put_bits = 0;
-
-  /* Initialize restart stuff */
-  entropy->restarts_to_go = cinfo->restart_interval;
-  entropy->next_restart_num = 0;
-}
-
-
-/*
- * Compute the derived values for a Huffman table.
- * This routine also performs some validation checks on the table.
- *
- * Note this is also used by jcphuff.c.
- */
-
-GLOBAL(void)
-jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
-			 c_derived_tbl ** pdtbl)
-{
-  JHUFF_TBL *htbl;
-  c_derived_tbl *dtbl;
-  int p, i, l, lastp, si, maxsymbol;
-  char huffsize[257];
-  unsigned int huffcode[257];
-  unsigned int code;
-
-  /* Note that huffsize[] and huffcode[] are filled in code-length order,
-   * paralleling the order of the symbols themselves in htbl->huffval[].
-   */
-
-  /* Find the input Huffman table */
-  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
-    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
-  htbl =
-    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
-  if (htbl == NULL)
-    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
-
-  /* Allocate a workspace if we haven't already done so. */
-  if (*pdtbl == NULL)
-    *pdtbl = (c_derived_tbl *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(c_derived_tbl));
-  dtbl = *pdtbl;
-  
-  /* Figure C.1: make table of Huffman code length for each symbol */
-
-  p = 0;
-  for (l = 1; l <= 16; l++) {
-    i = (int) htbl->bits[l];
-    if (i < 0 || p + i > 256)	/* protect against table overrun */
-      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-    while (i--)
-      huffsize[p++] = (char) l;
-  }
-  huffsize[p] = 0;
-  lastp = p;
-  
-  /* Figure C.2: generate the codes themselves */
-  /* We also validate that the counts represent a legal Huffman code tree. */
-
-  code = 0;
-  si = huffsize[0];
-  p = 0;
-  while (huffsize[p]) {
-    while (((int) huffsize[p]) == si) {
-      huffcode[p++] = code;
-      code++;
-    }
-    /* code is now 1 more than the last code used for codelength si; but
-     * it must still fit in si bits, since no code is allowed to be all ones.
-     */
-    if (((INT32) code) >= (((INT32) 1) << si))
-      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-    code <<= 1;
-    si++;
-  }
-  
-  /* Figure C.3: generate encoding tables */
-  /* These are code and size indexed by symbol value */
-
-  /* Set all codeless symbols to have code length 0;
-   * this lets us detect duplicate VAL entries here, and later
-   * allows emit_bits to detect any attempt to emit such symbols.
-   */
-  MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
-
-  /* This is also a convenient place to check for out-of-range
-   * and duplicated VAL entries.  We allow 0..255 for AC symbols
-   * but only 0..15 for DC.  (We could constrain them further
-   * based on data depth and mode, but this seems enough.)
-   */
-  maxsymbol = isDC ? 15 : 255;
-
-  for (p = 0; p < lastp; p++) {
-    i = htbl->huffval[p];
-    if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
-      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-    dtbl->ehufco[i] = huffcode[p];
-    dtbl->ehufsi[i] = huffsize[p];
-  }
-}
-
-
-/* Outputting bytes to the file */
-
-/* Emit a byte, taking 'action' if must suspend. */
-#define emit_byte(state,val,action)  \
-	{ *(state)->next_output_byte++ = (JOCTET) (val);  \
-	  if (--(state)->free_in_buffer == 0)  \
-	    if (! dump_buffer(state))  \
-	      { action; } }
-
-
-LOCAL(boolean)
-dump_buffer (working_state * state)
-/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
-{
-  struct jpeg_destination_mgr * dest = state->cinfo->dest;
-
-  if (! (*dest->empty_output_buffer) (state->cinfo))
-    return FALSE;
-  /* After a successful buffer dump, must reset buffer pointers */
-  state->next_output_byte = dest->next_output_byte;
-  state->free_in_buffer = dest->free_in_buffer;
-  return TRUE;
-}
-
-
-/* Outputting bits to the file */
-
-/* Only the right 24 bits of put_buffer are used; the valid bits are
- * left-justified in this part.  At most 16 bits can be passed to emit_bits
- * in one call, and we never retain more than 7 bits in put_buffer
- * between calls, so 24 bits are sufficient.
- */
-
-INLINE
-LOCAL(boolean)
-emit_bits (working_state * state, unsigned int code, int size)
-/* Emit some bits; return TRUE if successful, FALSE if must suspend */
-{
-  /* This routine is heavily used, so it's worth coding tightly. */
-  register INT32 put_buffer = (INT32) code;
-  register int put_bits = state->cur.put_bits;
-
-  /* if size is 0, caller used an invalid Huffman table entry */
-  if (size == 0)
-    ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
-
-  put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
-  
-  put_bits += size;		/* new number of bits in buffer */
-  
-  put_buffer <<= 24 - put_bits; /* align incoming bits */
-
-  put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
-  
-  while (put_bits >= 8) {
-    int c = (int) ((put_buffer >> 16) & 0xFF);
-    
-    emit_byte(state, c, return FALSE);
-    if (c == 0xFF) {		/* need to stuff a zero byte? */
-      emit_byte(state, 0, return FALSE);
-    }
-    put_buffer <<= 8;
-    put_bits -= 8;
-  }
-
-  state->cur.put_buffer = put_buffer; /* update state variables */
-  state->cur.put_bits = put_bits;
-
-  return TRUE;
-}
-
-
-LOCAL(boolean)
-flush_bits (working_state * state)
-{
-  if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
-    return FALSE;
-  state->cur.put_buffer = 0;	/* and reset bit-buffer to empty */
-  state->cur.put_bits = 0;
-  return TRUE;
-}
-
-
-/* Encode a single block's worth of coefficients */
-
-LOCAL(boolean)
-encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
-		  c_derived_tbl *dctbl, c_derived_tbl *actbl)
-{
-  register int temp, temp2;
-  register int nbits;
-  register int k, r, i;
-  
-  /* Encode the DC coefficient difference per section F.1.2.1 */
-  
-  temp = temp2 = block[0] - last_dc_val;
-
-  if (temp < 0) {
-    temp = -temp;		/* temp is abs value of input */
-    /* For a negative input, want temp2 = bitwise complement of abs(input) */
-    /* This code assumes we are on a two's complement machine */
-    temp2--;
-  }
-  
-  /* Find the number of bits needed for the magnitude of the coefficient */
-  nbits = 0;
-  while (temp) {
-    nbits++;
-    temp >>= 1;
-  }
-  /* Check for out-of-range coefficient values.
-   * Since we're encoding a difference, the range limit is twice as much.
-   */
-  if (nbits > MAX_COEF_BITS+1)
-    ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
-  
-  /* Emit the Huffman-coded symbol for the number of bits */
-  if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
-    return FALSE;
-
-  /* Emit that number of bits of the value, if positive, */
-  /* or the complement of its magnitude, if negative. */
-  if (nbits)			/* emit_bits rejects calls with size 0 */
-    if (! emit_bits(state, (unsigned int) temp2, nbits))
-      return FALSE;
-
-  /* Encode the AC coefficients per section F.1.2.2 */
-  
-  r = 0;			/* r = run length of zeros */
-  
-  for (k = 1; k < DCTSIZE2; k++) {
-    if ((temp = block[jpeg_natural_order[k]]) == 0) {
-      r++;
-    } else {
-      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
-      while (r > 15) {
-	if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
-	  return FALSE;
-	r -= 16;
-      }
-
-      temp2 = temp;
-      if (temp < 0) {
-	temp = -temp;		/* temp is abs value of input */
-	/* This code assumes we are on a two's complement machine */
-	temp2--;
-      }
-      
-      /* Find the number of bits needed for the magnitude of the coefficient */
-      nbits = 1;		/* there must be at least one 1 bit */
-      while ((temp >>= 1))
-	nbits++;
-      /* Check for out-of-range coefficient values */
-      if (nbits > MAX_COEF_BITS)
-	ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
-      
-      /* Emit Huffman symbol for run length / number of bits */
-      i = (r << 4) + nbits;
-      if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
-	return FALSE;
-
-      /* Emit that number of bits of the value, if positive, */
-      /* or the complement of its magnitude, if negative. */
-      if (! emit_bits(state, (unsigned int) temp2, nbits))
-	return FALSE;
-      
-      r = 0;
-    }
-  }
-
-  /* If the last coef(s) were zero, emit an end-of-block code */
-  if (r > 0)
-    if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
-      return FALSE;
-
-  return TRUE;
-}
-
-
-/*
- * Emit a restart marker & resynchronize predictions.
- */
-
-LOCAL(boolean)
-emit_restart (working_state * state, int restart_num)
-{
-  int ci;
-
-  if (! flush_bits(state))
-    return FALSE;
-
-  emit_byte(state, 0xFF, return FALSE);
-  emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
-
-  /* Re-initialize DC predictions to 0 */
-  for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
-    state->cur.last_dc_val[ci] = 0;
-
-  /* The restart counter is not updated until we successfully write the MCU. */
-
-  return TRUE;
-}
-
-
-/*
- * Encode and output one MCU's worth of Huffman-compressed coefficients.
- */
-
-METHODDEF(boolean)
-encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  working_state state;
-  int blkn, ci;
-  jpeg_component_info * compptr;
-
-  /* Load up working state */
-  state.next_output_byte = cinfo->dest->next_output_byte;
-  state.free_in_buffer = cinfo->dest->free_in_buffer;
-  ASSIGN_STATE(state.cur, entropy->saved);
-  state.cinfo = cinfo;
-
-  /* Emit restart marker if needed */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0)
-      if (! emit_restart(&state, entropy->next_restart_num))
-	return FALSE;
-  }
-
-  /* Encode the MCU data blocks */
-  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-    ci = cinfo->MCU_membership[blkn];
-    compptr = cinfo->cur_comp_info[ci];
-    if (! encode_one_block(&state,
-			   MCU_data[blkn][0], state.cur.last_dc_val[ci],
-			   entropy->dc_derived_tbls[compptr->dc_tbl_no],
-			   entropy->ac_derived_tbls[compptr->ac_tbl_no]))
-      return FALSE;
-    /* Update last_dc_val */
-    state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
-  }
-
-  /* Completed MCU, so update state */
-  cinfo->dest->next_output_byte = state.next_output_byte;
-  cinfo->dest->free_in_buffer = state.free_in_buffer;
-  ASSIGN_STATE(entropy->saved, state.cur);
-
-  /* Update restart-interval state too */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0) {
-      entropy->restarts_to_go = cinfo->restart_interval;
-      entropy->next_restart_num++;
-      entropy->next_restart_num &= 7;
-    }
-    entropy->restarts_to_go--;
-  }
-
-  return TRUE;
-}
-
-
-/*
- * Finish up at the end of a Huffman-compressed scan.
- */
-
-METHODDEF(void)
-finish_pass_huff (j_compress_ptr cinfo)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  working_state state;
-
-  /* Load up working state ... flush_bits needs it */
-  state.next_output_byte = cinfo->dest->next_output_byte;
-  state.free_in_buffer = cinfo->dest->free_in_buffer;
-  ASSIGN_STATE(state.cur, entropy->saved);
-  state.cinfo = cinfo;
-
-  /* Flush out the last data */
-  if (! flush_bits(&state))
-    ERREXIT(cinfo, JERR_CANT_SUSPEND);
-
-  /* Update state */
-  cinfo->dest->next_output_byte = state.next_output_byte;
-  cinfo->dest->free_in_buffer = state.free_in_buffer;
-  ASSIGN_STATE(entropy->saved, state.cur);
-}
-
-
-/*
- * Huffman coding optimization.
- *
- * We first scan the supplied data and count the number of uses of each symbol
- * that is to be Huffman-coded. (This process MUST agree with the code above.)
- * Then we build a Huffman coding tree for the observed counts.
- * Symbols which are not needed at all for the particular image are not
- * assigned any code, which saves space in the DHT marker as well as in
- * the compressed data.
- */
-
-#ifdef ENTROPY_OPT_SUPPORTED
-
-
-/* Process a single block's worth of coefficients */
-
-LOCAL(void)
-htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
-		 long dc_counts[], long ac_counts[])
-{
-  register int temp;
-  register int nbits;
-  register int k, r;
-  
-  /* Encode the DC coefficient difference per section F.1.2.1 */
-  
-  temp = block[0] - last_dc_val;
-  if (temp < 0)
-    temp = -temp;
-  
-  /* Find the number of bits needed for the magnitude of the coefficient */
-  nbits = 0;
-  while (temp) {
-    nbits++;
-    temp >>= 1;
-  }
-  /* Check for out-of-range coefficient values.
-   * Since we're encoding a difference, the range limit is twice as much.
-   */
-  if (nbits > MAX_COEF_BITS+1)
-    ERREXIT(cinfo, JERR_BAD_DCT_COEF);
-
-  /* Count the Huffman symbol for the number of bits */
-  dc_counts[nbits]++;
-  
-  /* Encode the AC coefficients per section F.1.2.2 */
-  
-  r = 0;			/* r = run length of zeros */
-  
-  for (k = 1; k < DCTSIZE2; k++) {
-    if ((temp = block[jpeg_natural_order[k]]) == 0) {
-      r++;
-    } else {
-      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
-      while (r > 15) {
-	ac_counts[0xF0]++;
-	r -= 16;
-      }
-      
-      /* Find the number of bits needed for the magnitude of the coefficient */
-      if (temp < 0)
-	temp = -temp;
-      
-      /* Find the number of bits needed for the magnitude of the coefficient */
-      nbits = 1;		/* there must be at least one 1 bit */
-      while ((temp >>= 1))
-	nbits++;
-      /* Check for out-of-range coefficient values */
-      if (nbits > MAX_COEF_BITS)
-	ERREXIT(cinfo, JERR_BAD_DCT_COEF);
-      
-      /* Count Huffman symbol for run length / number of bits */
-      ac_counts[(r << 4) + nbits]++;
-      
-      r = 0;
-    }
-  }
-
-  /* If the last coef(s) were zero, emit an end-of-block code */
-  if (r > 0)
-    ac_counts[0]++;
-}
-
-
-/*
- * Trial-encode one MCU's worth of Huffman-compressed coefficients.
- * No data is actually output, so no suspension return is possible.
- */
-
-METHODDEF(boolean)
-encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  int blkn, ci;
-  jpeg_component_info * compptr;
-
-  /* Take care of restart intervals if needed */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0) {
-      /* Re-initialize DC predictions to 0 */
-      for (ci = 0; ci < cinfo->comps_in_scan; ci++)
-	entropy->saved.last_dc_val[ci] = 0;
-      /* Update restart state */
-      entropy->restarts_to_go = cinfo->restart_interval;
-    }
-    entropy->restarts_to_go--;
-  }
-
-  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-    ci = cinfo->MCU_membership[blkn];
-    compptr = cinfo->cur_comp_info[ci];
-    htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
-		    entropy->dc_count_ptrs[compptr->dc_tbl_no],
-		    entropy->ac_count_ptrs[compptr->ac_tbl_no]);
-    entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
-  }
-
-  return TRUE;
-}
-
-
-/*
- * Generate the best Huffman code table for the given counts, fill htbl.
- * Note this is also used by jcphuff.c.
- *
- * The JPEG standard requires that no symbol be assigned a codeword of all
- * one bits (so that padding bits added at the end of a compressed segment
- * can't look like a valid code).  Because of the canonical ordering of
- * codewords, this just means that there must be an unused slot in the
- * longest codeword length category.  Section K.2 of the JPEG spec suggests
- * reserving such a slot by pretending that symbol 256 is a valid symbol
- * with count 1.  In theory that's not optimal; giving it count zero but
- * including it in the symbol set anyway should give a better Huffman code.
- * But the theoretically better code actually seems to come out worse in
- * practice, because it produces more all-ones bytes (which incur stuffed
- * zero bytes in the final file).  In any case the difference is tiny.
- *
- * The JPEG standard requires Huffman codes to be no more than 16 bits long.
- * If some symbols have a very small but nonzero probability, the Huffman tree
- * must be adjusted to meet the code length restriction.  We currently use
- * the adjustment method suggested in JPEG section K.2.  This method is *not*
- * optimal; it may not choose the best possible limited-length code.  But
- * typically only very-low-frequency symbols will be given less-than-optimal
- * lengths, so the code is almost optimal.  Experimental comparisons against
- * an optimal limited-length-code algorithm indicate that the difference is
- * microscopic --- usually less than a hundredth of a percent of total size.
- * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
- */
-
-GLOBAL(void)
-jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
-{
-#define MAX_CLEN 32		/* assumed maximum initial code length */
-  UINT8 bits[MAX_CLEN+1];	/* bits[k] = # of symbols with code length k */
-  int codesize[257];		/* codesize[k] = code length of symbol k */
-  int others[257];		/* next symbol in current branch of tree */
-  int c1, c2;
-  int p, i, j;
-  long v;
-
-  /* This algorithm is explained in section K.2 of the JPEG standard */
-
-  MEMZERO(bits, SIZEOF(bits));
-  MEMZERO(codesize, SIZEOF(codesize));
-  for (i = 0; i < 257; i++)
-    others[i] = -1;		/* init links to empty */
-  
-  freq[256] = 1;		/* make sure 256 has a nonzero count */
-  /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
-   * that no real symbol is given code-value of all ones, because 256
-   * will be placed last in the largest codeword category.
-   */
-
-  /* Huffman's basic algorithm to assign optimal code lengths to symbols */
-
-  for (;;) {
-    /* Find the smallest nonzero frequency, set c1 = its symbol */
-    /* In case of ties, take the larger symbol number */
-    c1 = -1;
-    v = 1000000000L;
-    for (i = 0; i <= 256; i++) {
-      if (freq[i] && freq[i] <= v) {
-	v = freq[i];
-	c1 = i;
-      }
-    }
-
-    /* Find the next smallest nonzero frequency, set c2 = its symbol */
-    /* In case of ties, take the larger symbol number */
-    c2 = -1;
-    v = 1000000000L;
-    for (i = 0; i <= 256; i++) {
-      if (freq[i] && freq[i] <= v && i != c1) {
-	v = freq[i];
-	c2 = i;
-      }
-    }
-
-    /* Done if we've merged everything into one frequency */
-    if (c2 < 0)
-      break;
-    
-    /* Else merge the two counts/trees */
-    freq[c1] += freq[c2];
-    freq[c2] = 0;
-
-    /* Increment the codesize of everything in c1's tree branch */
-    codesize[c1]++;
-    while (others[c1] >= 0) {
-      c1 = others[c1];
-      codesize[c1]++;
-    }
-    
-    others[c1] = c2;		/* chain c2 onto c1's tree branch */
-    
-    /* Increment the codesize of everything in c2's tree branch */
-    codesize[c2]++;
-    while (others[c2] >= 0) {
-      c2 = others[c2];
-      codesize[c2]++;
-    }
-  }
-
-  /* Now count the number of symbols of each code length */
-  for (i = 0; i <= 256; i++) {
-    if (codesize[i]) {
-      /* The JPEG standard seems to think that this can't happen, */
-      /* but I'm paranoid... */
-      if (codesize[i] > MAX_CLEN)
-	ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
-
-      bits[codesize[i]]++;
-    }
-  }
-
-  /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
-   * Huffman procedure assigned any such lengths, we must adjust the coding.
-   * Here is what the JPEG spec says about how this next bit works:
-   * Since symbols are paired for the longest Huffman code, the symbols are
-   * removed from this length category two at a time.  The prefix for the pair
-   * (which is one bit shorter) is allocated to one of the pair; then,
-   * skipping the BITS entry for that prefix length, a code word from the next
-   * shortest nonzero BITS entry is converted into a prefix for two code words
-   * one bit longer.
-   */
-  
-  for (i = MAX_CLEN; i > 16; i--) {
-    while (bits[i] > 0) {
-      j = i - 2;		/* find length of new prefix to be used */
-      while (bits[j] == 0)
-	j--;
-      
-      bits[i] -= 2;		/* remove two symbols */
-      bits[i-1]++;		/* one goes in this length */
-      bits[j+1] += 2;		/* two new symbols in this length */
-      bits[j]--;		/* symbol of this length is now a prefix */
-    }
-  }
-
-  /* Remove the count for the pseudo-symbol 256 from the largest codelength */
-  while (bits[i] == 0)		/* find largest codelength still in use */
-    i--;
-  bits[i]--;
-  
-  /* Return final symbol counts (only for lengths 0..16) */
-  MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
-  
-  /* Return a list of the symbols sorted by code length */
-  /* It's not real clear to me why we don't need to consider the codelength
-   * changes made above, but the JPEG spec seems to think this works.
-   */
-  p = 0;
-  for (i = 1; i <= MAX_CLEN; i++) {
-    for (j = 0; j <= 255; j++) {
-      if (codesize[j] == i) {
-	htbl->huffval[p] = (UINT8) j;
-	p++;
-      }
-    }
-  }
-
-  /* Set sent_table FALSE so updated table will be written to JPEG file. */
-  htbl->sent_table = FALSE;
-}
-
-
-/*
- * Finish up a statistics-gathering pass and create the new Huffman tables.
- */
-
-METHODDEF(void)
-finish_pass_gather (j_compress_ptr cinfo)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  int ci, dctbl, actbl;
-  jpeg_component_info * compptr;
-  JHUFF_TBL **htblptr;
-  boolean did_dc[NUM_HUFF_TBLS];
-  boolean did_ac[NUM_HUFF_TBLS];
-
-  /* It's important not to apply jpeg_gen_optimal_table more than once
-   * per table, because it clobbers the input frequency counts!
-   */
-  MEMZERO(did_dc, SIZEOF(did_dc));
-  MEMZERO(did_ac, SIZEOF(did_ac));
-
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    dctbl = compptr->dc_tbl_no;
-    actbl = compptr->ac_tbl_no;
-    if (! did_dc[dctbl]) {
-      htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
-      if (*htblptr == NULL)
-	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
-      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
-      did_dc[dctbl] = TRUE;
-    }
-    if (! did_ac[actbl]) {
-      htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
-      if (*htblptr == NULL)
-	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
-      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
-      did_ac[actbl] = TRUE;
-    }
-  }
-}
-
-
-#endif /* ENTROPY_OPT_SUPPORTED */
-
-
-/*
- * Module initialization routine for Huffman entropy encoding.
- */
-
-GLOBAL(void)
-jinit_huff_encoder (j_compress_ptr cinfo)
-{
-  huff_entropy_ptr entropy;
-  int i;
-
-  entropy = (huff_entropy_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(huff_entropy_encoder));
-  cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
-  entropy->pub.start_pass = start_pass_huff;
-
-  /* Mark tables unallocated */
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
-#ifdef ENTROPY_OPT_SUPPORTED
-    entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
-#endif
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jchuff.h ./Shared/jpeg-6b/jchuff.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jchuff.h	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jchuff.h	Wed Dec 31 19:00:00 1969
@@ -1,47 +0,0 @@
-/*
- * jchuff.h
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains declarations for Huffman entropy encoding routines
- * that are shared between the sequential encoder (jchuff.c) and the
- * progressive encoder (jcphuff.c).  No other modules need to see these.
- */
-
-/* The legal range of a DCT coefficient is
- *  -1024 .. +1023  for 8-bit data;
- * -16384 .. +16383 for 12-bit data.
- * Hence the magnitude should always fit in 10 or 14 bits respectively.
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define MAX_COEF_BITS 10
-#else
-#define MAX_COEF_BITS 14
-#endif
-
-/* Derived data constructed for each Huffman table */
-
-typedef struct {
-  unsigned int ehufco[256];	/* code for each symbol */
-  char ehufsi[256];		/* length of code for each symbol */
-  /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
-} c_derived_tbl;
-
-/* Short forms of external names for systems with brain-damaged linkers. */
-
-#ifdef NEED_SHORT_EXTERNAL_NAMES
-#define jpeg_make_c_derived_tbl	jMkCDerived
-#define jpeg_gen_optimal_table	jGenOptTbl
-#endif /* NEED_SHORT_EXTERNAL_NAMES */
-
-/* Expand a Huffman table definition into the derived format */
-EXTERN(void) jpeg_make_c_derived_tbl
-	JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
-	     c_derived_tbl ** pdtbl));
-
-/* Generate an optimal table definition given the specified counts */
-EXTERN(void) jpeg_gen_optimal_table
-	JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcinit.c ./Shared/jpeg-6b/jcinit.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcinit.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jcinit.c	Wed Dec 31 19:00:00 1969
@@ -1,72 +0,0 @@
-/*
- * jcinit.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains initialization logic for the JPEG compressor.
- * This routine is in charge of selecting the modules to be executed and
- * making an initialization call to each one.
- *
- * Logically, this code belongs in jcmaster.c.  It's split out because
- * linking this routine implies linking the entire compression library.
- * For a transcoding-only application, we want to be able to use jcmaster.c
- * without linking in the whole library.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * Master selection of compression modules.
- * This is done once at the start of processing an image.  We determine
- * which modules will be used and give them appropriate initialization calls.
- */
-
-GLOBAL(void)
-jinit_compress_master (j_compress_ptr cinfo)
-{
-  /* Initialize master control (includes parameter checking/processing) */
-  jinit_c_master_control(cinfo, FALSE /* full compression */);
-
-  /* Preprocessing */
-  if (! cinfo->raw_data_in) {
-    jinit_color_converter(cinfo);
-    jinit_downsampler(cinfo);
-    jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
-  }
-  /* Forward DCT */
-  jinit_forward_dct(cinfo);
-  /* Entropy encoding: either Huffman or arithmetic coding. */
-  if (cinfo->arith_code) {
-    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
-  } else {
-    if (cinfo->progressive_mode) {
-#ifdef C_PROGRESSIVE_SUPPORTED
-      jinit_phuff_encoder(cinfo);
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-    } else
-      jinit_huff_encoder(cinfo);
-  }
-
-  /* Need a full-image coefficient buffer in any multi-pass mode. */
-  jinit_c_coef_controller(cinfo,
-		(boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
-  jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
-
-  jinit_marker_writer(cinfo);
-
-  /* We can now tell the memory manager to allocate virtual arrays. */
-  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
-
-  /* Write the datastream header (SOI) immediately.
-   * Frame and scan headers are postponed till later.
-   * This lets application insert special markers after the SOI.
-   */
-  (*cinfo->marker->write_file_header) (cinfo);
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcmainct.c ./Shared/jpeg-6b/jcmainct.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcmainct.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jcmainct.c	Wed Dec 31 19:00:00 1969
@@ -1,293 +0,0 @@
-/*
- * jcmainct.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the main buffer controller for compression.
- * The main buffer lies between the pre-processor and the JPEG
- * compressor proper; it holds downsampled data in the JPEG colorspace.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Note: currently, there is no operating mode in which a full-image buffer
- * is needed at this step.  If there were, that mode could not be used with
- * "raw data" input, since this module is bypassed in that case.  However,
- * we've left the code here for possible use in special applications.
- */
-#undef FULL_MAIN_BUFFER_SUPPORTED
-
-
-/* Private buffer controller object */
-
-typedef struct {
-  struct jpeg_c_main_controller pub; /* public fields */
-
-  JDIMENSION cur_iMCU_row;	/* number of current iMCU row */
-  JDIMENSION rowgroup_ctr;	/* counts row groups received in iMCU row */
-  boolean suspended;		/* remember if we suspended output */
-  J_BUF_MODE pass_mode;		/* current operating mode */
-
-  /* If using just a strip buffer, this points to the entire set of buffers
-   * (we allocate one for each component).  In the full-image case, this
-   * points to the currently accessible strips of the virtual arrays.
-   */
-  JSAMPARRAY buffer[MAX_COMPONENTS];
-
-#ifdef FULL_MAIN_BUFFER_SUPPORTED
-  /* If using full-image storage, this array holds pointers to virtual-array
-   * control blocks for each component.  Unused if not full-image storage.
-   */
-  jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
-#endif
-} my_main_controller;
-
-typedef my_main_controller * my_main_ptr;
-
-
-/* Forward declarations */
-METHODDEF(void) process_data_simple_main
-	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
-	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
-#ifdef FULL_MAIN_BUFFER_SUPPORTED
-METHODDEF(void) process_data_buffer_main
-	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
-	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
-#endif
-
-
-/*
- * Initialize for a processing pass.
- */
-
-METHODDEF(void)
-start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-
-  /* Do nothing in raw-data mode. */
-  if (cinfo->raw_data_in)
-    return;
-
-  main->cur_iMCU_row = 0;	/* initialize counters */
-  main->rowgroup_ctr = 0;
-  main->suspended = FALSE;
-  main->pass_mode = pass_mode;	/* save mode for use by process_data */
-
-  switch (pass_mode) {
-  case JBUF_PASS_THRU:
-#ifdef FULL_MAIN_BUFFER_SUPPORTED
-    if (main->whole_image[0] != NULL)
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-#endif
-    main->pub.process_data = process_data_simple_main;
-    break;
-#ifdef FULL_MAIN_BUFFER_SUPPORTED
-  case JBUF_SAVE_SOURCE:
-  case JBUF_CRANK_DEST:
-  case JBUF_SAVE_AND_PASS:
-    if (main->whole_image[0] == NULL)
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    main->pub.process_data = process_data_buffer_main;
-    break;
-#endif
-  default:
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    break;
-  }
-}
-
-
-/*
- * Process some data.
- * This routine handles the simple pass-through mode,
- * where we have only a strip buffer.
- */
-
-METHODDEF(void)
-process_data_simple_main (j_compress_ptr cinfo,
-			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
-			  JDIMENSION in_rows_avail)
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-
-  while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
-    /* Read input data if we haven't filled the main buffer yet */
-    if (main->rowgroup_ctr < DCTSIZE)
-      (*cinfo->prep->pre_process_data) (cinfo,
-					input_buf, in_row_ctr, in_rows_avail,
-					main->buffer, &main->rowgroup_ctr,
-					(JDIMENSION) DCTSIZE);
-
-    /* If we don't have a full iMCU row buffered, return to application for
-     * more data.  Note that preprocessor will always pad to fill the iMCU row
-     * at the bottom of the image.
-     */
-    if (main->rowgroup_ctr != DCTSIZE)
-      return;
-
-    /* Send the completed row to the compressor */
-    if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
-      /* If compressor did not consume the whole row, then we must need to
-       * suspend processing and return to the application.  In this situation
-       * we pretend we didn't yet consume the last input row; otherwise, if
-       * it happened to be the last row of the image, the application would
-       * think we were done.
-       */
-      if (! main->suspended) {
-	(*in_row_ctr)--;
-	main->suspended = TRUE;
-      }
-      return;
-    }
-    /* We did finish the row.  Undo our little suspension hack if a previous
-     * call suspended; then mark the main buffer empty.
-     */
-    if (main->suspended) {
-      (*in_row_ctr)++;
-      main->suspended = FALSE;
-    }
-    main->rowgroup_ctr = 0;
-    main->cur_iMCU_row++;
-  }
-}
-
-
-#ifdef FULL_MAIN_BUFFER_SUPPORTED
-
-/*
- * Process some data.
- * This routine handles all of the modes that use a full-size buffer.
- */
-
-METHODDEF(void)
-process_data_buffer_main (j_compress_ptr cinfo,
-			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
-			  JDIMENSION in_rows_avail)
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-  int ci;
-  jpeg_component_info *compptr;
-  boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
-
-  while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
-    /* Realign the virtual buffers if at the start of an iMCU row. */
-    if (main->rowgroup_ctr == 0) {
-      for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	   ci++, compptr++) {
-	main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
-	  ((j_common_ptr) cinfo, main->whole_image[ci],
-	   main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
-	   (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
-      }
-      /* In a read pass, pretend we just read some source data. */
-      if (! writing) {
-	*in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
-	main->rowgroup_ctr = DCTSIZE;
-      }
-    }
-
-    /* If a write pass, read input data until the current iMCU row is full. */
-    /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
-    if (writing) {
-      (*cinfo->prep->pre_process_data) (cinfo,
-					input_buf, in_row_ctr, in_rows_avail,
-					main->buffer, &main->rowgroup_ctr,
-					(JDIMENSION) DCTSIZE);
-      /* Return to application if we need more data to fill the iMCU row. */
-      if (main->rowgroup_ctr < DCTSIZE)
-	return;
-    }
-
-    /* Emit data, unless this is a sink-only pass. */
-    if (main->pass_mode != JBUF_SAVE_SOURCE) {
-      if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
-	/* If compressor did not consume the whole row, then we must need to
-	 * suspend processing and return to the application.  In this situation
-	 * we pretend we didn't yet consume the last input row; otherwise, if
-	 * it happened to be the last row of the image, the application would
-	 * think we were done.
-	 */
-	if (! main->suspended) {
-	  (*in_row_ctr)--;
-	  main->suspended = TRUE;
-	}
-	return;
-      }
-      /* We did finish the row.  Undo our little suspension hack if a previous
-       * call suspended; then mark the main buffer empty.
-       */
-      if (main->suspended) {
-	(*in_row_ctr)++;
-	main->suspended = FALSE;
-      }
-    }
-
-    /* If get here, we are done with this iMCU row.  Mark buffer empty. */
-    main->rowgroup_ctr = 0;
-    main->cur_iMCU_row++;
-  }
-}
-
-#endif /* FULL_MAIN_BUFFER_SUPPORTED */
-
-
-/*
- * Initialize main buffer controller.
- */
-
-GLOBAL(void)
-jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
-{
-  my_main_ptr main;
-  int ci;
-  jpeg_component_info *compptr;
-
-  main = (my_main_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_main_controller));
-  cinfo->main = (struct jpeg_c_main_controller *) main;
-  main->pub.start_pass = start_pass_main;
-
-  /* We don't need to create a buffer in raw-data mode. */
-  if (cinfo->raw_data_in)
-    return;
-
-  /* Create the buffer.  It holds downsampled data, so each component
-   * may be of a different size.
-   */
-  if (need_full_buffer) {
-#ifdef FULL_MAIN_BUFFER_SUPPORTED
-    /* Allocate a full-image virtual array for each component */
-    /* Note we pad the bottom to a multiple of the iMCU height */
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-	 compptr->width_in_blocks * DCTSIZE,
-	 (JDIMENSION) jround_up((long) compptr->height_in_blocks,
-				(long) compptr->v_samp_factor) * DCTSIZE,
-	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
-    }
-#else
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-#endif
-  } else {
-#ifdef FULL_MAIN_BUFFER_SUPPORTED
-    main->whole_image[0] = NULL; /* flag for no virtual arrays */
-#endif
-    /* Allocate a strip buffer for each component */
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      main->buffer[ci] = (*cinfo->mem->alloc_sarray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE,
-	 compptr->width_in_blocks * DCTSIZE,
-	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
-    }
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcmarker.c ./Shared/jpeg-6b/jcmarker.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcmarker.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jcmarker.c	Wed Dec 31 19:00:00 1969
@@ -1,664 +0,0 @@
-/*
- * jcmarker.c
- *
- * Copyright (C) 1991-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to write JPEG datastream markers.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-typedef enum {			/* JPEG marker codes */
-  M_SOF0  = 0xc0,
-  M_SOF1  = 0xc1,
-  M_SOF2  = 0xc2,
-  M_SOF3  = 0xc3,
-  
-  M_SOF5  = 0xc5,
-  M_SOF6  = 0xc6,
-  M_SOF7  = 0xc7,
-  
-  M_JPG   = 0xc8,
-  M_SOF9  = 0xc9,
-  M_SOF10 = 0xca,
-  M_SOF11 = 0xcb,
-  
-  M_SOF13 = 0xcd,
-  M_SOF14 = 0xce,
-  M_SOF15 = 0xcf,
-  
-  M_DHT   = 0xc4,
-  
-  M_DAC   = 0xcc,
-  
-  M_RST0  = 0xd0,
-  M_RST1  = 0xd1,
-  M_RST2  = 0xd2,
-  M_RST3  = 0xd3,
-  M_RST4  = 0xd4,
-  M_RST5  = 0xd5,
-  M_RST6  = 0xd6,
-  M_RST7  = 0xd7,
-  
-  M_SOI   = 0xd8,
-  M_EOI   = 0xd9,
-  M_SOS   = 0xda,
-  M_DQT   = 0xdb,
-  M_DNL   = 0xdc,
-  M_DRI   = 0xdd,
-  M_DHP   = 0xde,
-  M_EXP   = 0xdf,
-  
-  M_APP0  = 0xe0,
-  M_APP1  = 0xe1,
-  M_APP2  = 0xe2,
-  M_APP3  = 0xe3,
-  M_APP4  = 0xe4,
-  M_APP5  = 0xe5,
-  M_APP6  = 0xe6,
-  M_APP7  = 0xe7,
-  M_APP8  = 0xe8,
-  M_APP9  = 0xe9,
-  M_APP10 = 0xea,
-  M_APP11 = 0xeb,
-  M_APP12 = 0xec,
-  M_APP13 = 0xed,
-  M_APP14 = 0xee,
-  M_APP15 = 0xef,
-  
-  M_JPG0  = 0xf0,
-  M_JPG13 = 0xfd,
-  M_COM   = 0xfe,
-  
-  M_TEM   = 0x01,
-  
-  M_ERROR = 0x100
-} JPEG_MARKER;
-
-
-/* Private state */
-
-typedef struct {
-  struct jpeg_marker_writer pub; /* public fields */
-
-  unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
-} my_marker_writer;
-
-typedef my_marker_writer * my_marker_ptr;
-
-
-/*
- * Basic output routines.
- *
- * Note that we do not support suspension while writing a marker.
- * Therefore, an application using suspension must ensure that there is
- * enough buffer space for the initial markers (typ. 600-700 bytes) before
- * calling jpeg_start_compress, and enough space to write the trailing EOI
- * (a few bytes) before calling jpeg_finish_compress.  Multipass compression
- * modes are not supported at all with suspension, so those two are the only
- * points where markers will be written.
- */
-
-LOCAL(void)
-emit_byte (j_compress_ptr cinfo, int val)
-/* Emit a byte */
-{
-  struct jpeg_destination_mgr * dest = cinfo->dest;
-
-  *(dest->next_output_byte)++ = (JOCTET) val;
-  if (--dest->free_in_buffer == 0) {
-    if (! (*dest->empty_output_buffer) (cinfo))
-      ERREXIT(cinfo, JERR_CANT_SUSPEND);
-  }
-}
-
-
-LOCAL(void)
-emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
-/* Emit a marker code */
-{
-  emit_byte(cinfo, 0xFF);
-  emit_byte(cinfo, (int) mark);
-}
-
-
-LOCAL(void)
-emit_2bytes (j_compress_ptr cinfo, int value)
-/* Emit a 2-byte integer; these are always MSB first in JPEG files */
-{
-  emit_byte(cinfo, (value >> 8) & 0xFF);
-  emit_byte(cinfo, value & 0xFF);
-}
-
-
-/*
- * Routines to write specific marker types.
- */
-
-LOCAL(int)
-emit_dqt (j_compress_ptr cinfo, int index)
-/* Emit a DQT marker */
-/* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
-{
-  JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
-  int prec;
-  int i;
-
-  if (qtbl == NULL)
-    ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
-
-  prec = 0;
-  for (i = 0; i < DCTSIZE2; i++) {
-    if (qtbl->quantval[i] > 255)
-      prec = 1;
-  }
-
-  if (! qtbl->sent_table) {
-    emit_marker(cinfo, M_DQT);
-
-    emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
-
-    emit_byte(cinfo, index + (prec<<4));
-
-    for (i = 0; i < DCTSIZE2; i++) {
-      /* The table entries must be emitted in zigzag order. */
-      unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
-      if (prec)
-	emit_byte(cinfo, (int) (qval >> 8));
-      emit_byte(cinfo, (int) (qval & 0xFF));
-    }
-
-    qtbl->sent_table = TRUE;
-  }
-
-  return prec;
-}
-
-
-LOCAL(void)
-emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
-/* Emit a DHT marker */
-{
-  JHUFF_TBL * htbl;
-  int length, i;
-  
-  if (is_ac) {
-    htbl = cinfo->ac_huff_tbl_ptrs[index];
-    index += 0x10;		/* output index has AC bit set */
-  } else {
-    htbl = cinfo->dc_huff_tbl_ptrs[index];
-  }
-
-  if (htbl == NULL)
-    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
-  
-  if (! htbl->sent_table) {
-    emit_marker(cinfo, M_DHT);
-    
-    length = 0;
-    for (i = 1; i <= 16; i++)
-      length += htbl->bits[i];
-    
-    emit_2bytes(cinfo, length + 2 + 1 + 16);
-    emit_byte(cinfo, index);
-    
-    for (i = 1; i <= 16; i++)
-      emit_byte(cinfo, htbl->bits[i]);
-    
-    for (i = 0; i < length; i++)
-      emit_byte(cinfo, htbl->huffval[i]);
-    
-    htbl->sent_table = TRUE;
-  }
-}
-
-
-LOCAL(void)
-emit_dac (j_compress_ptr cinfo)
-/* Emit a DAC marker */
-/* Since the useful info is so small, we want to emit all the tables in */
-/* one DAC marker.  Therefore this routine does its own scan of the table. */
-{
-#ifdef C_ARITH_CODING_SUPPORTED
-  char dc_in_use[NUM_ARITH_TBLS];
-  char ac_in_use[NUM_ARITH_TBLS];
-  int length, i;
-  jpeg_component_info *compptr;
-  
-  for (i = 0; i < NUM_ARITH_TBLS; i++)
-    dc_in_use[i] = ac_in_use[i] = 0;
-  
-  for (i = 0; i < cinfo->comps_in_scan; i++) {
-    compptr = cinfo->cur_comp_info[i];
-    dc_in_use[compptr->dc_tbl_no] = 1;
-    ac_in_use[compptr->ac_tbl_no] = 1;
-  }
-  
-  length = 0;
-  for (i = 0; i < NUM_ARITH_TBLS; i++)
-    length += dc_in_use[i] + ac_in_use[i];
-  
-  emit_marker(cinfo, M_DAC);
-  
-  emit_2bytes(cinfo, length*2 + 2);
-  
-  for (i = 0; i < NUM_ARITH_TBLS; i++) {
-    if (dc_in_use[i]) {
-      emit_byte(cinfo, i);
-      emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
-    }
-    if (ac_in_use[i]) {
-      emit_byte(cinfo, i + 0x10);
-      emit_byte(cinfo, cinfo->arith_ac_K[i]);
-    }
-  }
-#endif /* C_ARITH_CODING_SUPPORTED */
-}
-
-
-LOCAL(void)
-emit_dri (j_compress_ptr cinfo)
-/* Emit a DRI marker */
-{
-  emit_marker(cinfo, M_DRI);
-  
-  emit_2bytes(cinfo, 4);	/* fixed length */
-
-  emit_2bytes(cinfo, (int) cinfo->restart_interval);
-}
-
-
-LOCAL(void)
-emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
-/* Emit a SOF marker */
-{
-  int ci;
-  jpeg_component_info *compptr;
-  
-  emit_marker(cinfo, code);
-  
-  emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
-
-  /* Make sure image isn't bigger than SOF field can handle */
-  if ((long) cinfo->image_height > 65535L ||
-      (long) cinfo->image_width > 65535L)
-    ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
-
-  emit_byte(cinfo, cinfo->data_precision);
-  emit_2bytes(cinfo, (int) cinfo->image_height);
-  emit_2bytes(cinfo, (int) cinfo->image_width);
-
-  emit_byte(cinfo, cinfo->num_components);
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    emit_byte(cinfo, compptr->component_id);
-    emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
-    emit_byte(cinfo, compptr->quant_tbl_no);
-  }
-}
-
-
-LOCAL(void)
-emit_sos (j_compress_ptr cinfo)
-/* Emit a SOS marker */
-{
-  int i, td, ta;
-  jpeg_component_info *compptr;
-  
-  emit_marker(cinfo, M_SOS);
-  
-  emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
-  
-  emit_byte(cinfo, cinfo->comps_in_scan);
-  
-  for (i = 0; i < cinfo->comps_in_scan; i++) {
-    compptr = cinfo->cur_comp_info[i];
-    emit_byte(cinfo, compptr->component_id);
-    td = compptr->dc_tbl_no;
-    ta = compptr->ac_tbl_no;
-    if (cinfo->progressive_mode) {
-      /* Progressive mode: only DC or only AC tables are used in one scan;
-       * furthermore, Huffman coding of DC refinement uses no table at all.
-       * We emit 0 for unused field(s); this is recommended by the P&M text
-       * but does not seem to be specified in the standard.
-       */
-      if (cinfo->Ss == 0) {
-	ta = 0;			/* DC scan */
-	if (cinfo->Ah != 0 && !cinfo->arith_code)
-	  td = 0;		/* no DC table either */
-      } else {
-	td = 0;			/* AC scan */
-      }
-    }
-    emit_byte(cinfo, (td << 4) + ta);
-  }
-
-  emit_byte(cinfo, cinfo->Ss);
-  emit_byte(cinfo, cinfo->Se);
-  emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
-}
-
-
-LOCAL(void)
-emit_jfif_app0 (j_compress_ptr cinfo)
-/* Emit a JFIF-compliant APP0 marker */
-{
-  /*
-   * Length of APP0 block	(2 bytes)
-   * Block ID			(4 bytes - ASCII "JFIF")
-   * Zero byte			(1 byte to terminate the ID string)
-   * Version Major, Minor	(2 bytes - major first)
-   * Units			(1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
-   * Xdpu			(2 bytes - dots per unit horizontal)
-   * Ydpu			(2 bytes - dots per unit vertical)
-   * Thumbnail X size		(1 byte)
-   * Thumbnail Y size		(1 byte)
-   */
-  
-  emit_marker(cinfo, M_APP0);
-  
-  emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
-
-  emit_byte(cinfo, 0x4A);	/* Identifier: ASCII "JFIF" */
-  emit_byte(cinfo, 0x46);
-  emit_byte(cinfo, 0x49);
-  emit_byte(cinfo, 0x46);
-  emit_byte(cinfo, 0);
-  emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
-  emit_byte(cinfo, cinfo->JFIF_minor_version);
-  emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
-  emit_2bytes(cinfo, (int) cinfo->X_density);
-  emit_2bytes(cinfo, (int) cinfo->Y_density);
-  emit_byte(cinfo, 0);		/* No thumbnail image */
-  emit_byte(cinfo, 0);
-}
-
-
-LOCAL(void)
-emit_adobe_app14 (j_compress_ptr cinfo)
-/* Emit an Adobe APP14 marker */
-{
-  /*
-   * Length of APP14 block	(2 bytes)
-   * Block ID			(5 bytes - ASCII "Adobe")
-   * Version Number		(2 bytes - currently 100)
-   * Flags0			(2 bytes - currently 0)
-   * Flags1			(2 bytes - currently 0)
-   * Color transform		(1 byte)
-   *
-   * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
-   * now in circulation seem to use Version = 100, so that's what we write.
-   *
-   * We write the color transform byte as 1 if the JPEG color space is
-   * YCbCr, 2 if it's YCCK, 0 otherwise.  Adobe's definition has to do with
-   * whether the encoder performed a transformation, which is pretty useless.
-   */
-  
-  emit_marker(cinfo, M_APP14);
-  
-  emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
-
-  emit_byte(cinfo, 0x41);	/* Identifier: ASCII "Adobe" */
-  emit_byte(cinfo, 0x64);
-  emit_byte(cinfo, 0x6F);
-  emit_byte(cinfo, 0x62);
-  emit_byte(cinfo, 0x65);
-  emit_2bytes(cinfo, 100);	/* Version */
-  emit_2bytes(cinfo, 0);	/* Flags0 */
-  emit_2bytes(cinfo, 0);	/* Flags1 */
-  switch (cinfo->jpeg_color_space) {
-  case JCS_YCbCr:
-    emit_byte(cinfo, 1);	/* Color transform = 1 */
-    break;
-  case JCS_YCCK:
-    emit_byte(cinfo, 2);	/* Color transform = 2 */
-    break;
-  default:
-    emit_byte(cinfo, 0);	/* Color transform = 0 */
-    break;
-  }
-}
-
-
-/*
- * These routines allow writing an arbitrary marker with parameters.
- * The only intended use is to emit COM or APPn markers after calling
- * write_file_header and before calling write_frame_header.
- * Other uses are not guaranteed to produce desirable results.
- * Counting the parameter bytes properly is the caller's responsibility.
- */
-
-METHODDEF(void)
-write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
-/* Emit an arbitrary marker header */
-{
-  if (datalen > (unsigned int) 65533)		/* safety check */
-    ERREXIT(cinfo, JERR_BAD_LENGTH);
-
-  emit_marker(cinfo, (JPEG_MARKER) marker);
-
-  emit_2bytes(cinfo, (int) (datalen + 2));	/* total length */
-}
-
-METHODDEF(void)
-write_marker_byte (j_compress_ptr cinfo, int val)
-/* Emit one byte of marker parameters following write_marker_header */
-{
-  emit_byte(cinfo, val);
-}
-
-
-/*
- * Write datastream header.
- * This consists of an SOI and optional APPn markers.
- * We recommend use of the JFIF marker, but not the Adobe marker,
- * when using YCbCr or grayscale data.  The JFIF marker should NOT
- * be used for any other JPEG colorspace.  The Adobe marker is helpful
- * to distinguish RGB, CMYK, and YCCK colorspaces.
- * Note that an application can write additional header markers after
- * jpeg_start_compress returns.
- */
-
-METHODDEF(void)
-write_file_header (j_compress_ptr cinfo)
-{
-  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
-
-  emit_marker(cinfo, M_SOI);	/* first the SOI */
-
-  /* SOI is defined to reset restart interval to 0 */
-  marker->last_restart_interval = 0;
-
-  if (cinfo->write_JFIF_header)	/* next an optional JFIF APP0 */
-    emit_jfif_app0(cinfo);
-  if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
-    emit_adobe_app14(cinfo);
-}
-
-
-/*
- * Write frame header.
- * This consists of DQT and SOFn markers.
- * Note that we do not emit the SOF until we have emitted the DQT(s).
- * This avoids compatibility problems with incorrect implementations that
- * try to error-check the quant table numbers as soon as they see the SOF.
- */
-
-METHODDEF(void)
-write_frame_header (j_compress_ptr cinfo)
-{
-  int ci, prec;
-  boolean is_baseline;
-  jpeg_component_info *compptr;
-  
-  /* Emit DQT for each quantization table.
-   * Note that emit_dqt() suppresses any duplicate tables.
-   */
-  prec = 0;
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    prec += emit_dqt(cinfo, compptr->quant_tbl_no);
-  }
-  /* now prec is nonzero iff there are any 16-bit quant tables. */
-
-  /* Check for a non-baseline specification.
-   * Note we assume that Huffman table numbers won't be changed later.
-   */
-  if (cinfo->arith_code || cinfo->progressive_mode ||
-      cinfo->data_precision != 8) {
-    is_baseline = FALSE;
-  } else {
-    is_baseline = TRUE;
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
-	is_baseline = FALSE;
-    }
-    if (prec && is_baseline) {
-      is_baseline = FALSE;
-      /* If it's baseline except for quantizer size, warn the user */
-      TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
-    }
-  }
-
-  /* Emit the proper SOF marker */
-  if (cinfo->arith_code) {
-    emit_sof(cinfo, M_SOF9);	/* SOF code for arithmetic coding */
-  } else {
-    if (cinfo->progressive_mode)
-      emit_sof(cinfo, M_SOF2);	/* SOF code for progressive Huffman */
-    else if (is_baseline)
-      emit_sof(cinfo, M_SOF0);	/* SOF code for baseline implementation */
-    else
-      emit_sof(cinfo, M_SOF1);	/* SOF code for non-baseline Huffman file */
-  }
-}
-
-
-/*
- * Write scan header.
- * This consists of DHT or DAC markers, optional DRI, and SOS.
- * Compressed data will be written following the SOS.
- */
-
-METHODDEF(void)
-write_scan_header (j_compress_ptr cinfo)
-{
-  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
-  int i;
-  jpeg_component_info *compptr;
-
-  if (cinfo->arith_code) {
-    /* Emit arith conditioning info.  We may have some duplication
-     * if the file has multiple scans, but it's so small it's hardly
-     * worth worrying about.
-     */
-    emit_dac(cinfo);
-  } else {
-    /* Emit Huffman tables.
-     * Note that emit_dht() suppresses any duplicate tables.
-     */
-    for (i = 0; i < cinfo->comps_in_scan; i++) {
-      compptr = cinfo->cur_comp_info[i];
-      if (cinfo->progressive_mode) {
-	/* Progressive mode: only DC or only AC tables are used in one scan */
-	if (cinfo->Ss == 0) {
-	  if (cinfo->Ah == 0)	/* DC needs no table for refinement scan */
-	    emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
-	} else {
-	  emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
-	}
-      } else {
-	/* Sequential mode: need both DC and AC tables */
-	emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
-	emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
-      }
-    }
-  }
-
-  /* Emit DRI if required --- note that DRI value could change for each scan.
-   * We avoid wasting space with unnecessary DRIs, however.
-   */
-  if (cinfo->restart_interval != marker->last_restart_interval) {
-    emit_dri(cinfo);
-    marker->last_restart_interval = cinfo->restart_interval;
-  }
-
-  emit_sos(cinfo);
-}
-
-
-/*
- * Write datastream trailer.
- */
-
-METHODDEF(void)
-write_file_trailer (j_compress_ptr cinfo)
-{
-  emit_marker(cinfo, M_EOI);
-}
-
-
-/*
- * Write an abbreviated table-specification datastream.
- * This consists of SOI, DQT and DHT tables, and EOI.
- * Any table that is defined and not marked sent_table = TRUE will be
- * emitted.  Note that all tables will be marked sent_table = TRUE at exit.
- */
-
-METHODDEF(void)
-write_tables_only (j_compress_ptr cinfo)
-{
-  int i;
-
-  emit_marker(cinfo, M_SOI);
-
-  for (i = 0; i < NUM_QUANT_TBLS; i++) {
-    if (cinfo->quant_tbl_ptrs[i] != NULL)
-      (void) emit_dqt(cinfo, i);
-  }
-
-  if (! cinfo->arith_code) {
-    for (i = 0; i < NUM_HUFF_TBLS; i++) {
-      if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
-	emit_dht(cinfo, i, FALSE);
-      if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
-	emit_dht(cinfo, i, TRUE);
-    }
-  }
-
-  emit_marker(cinfo, M_EOI);
-}
-
-
-/*
- * Initialize the marker writer module.
- */
-
-GLOBAL(void)
-jinit_marker_writer (j_compress_ptr cinfo)
-{
-  my_marker_ptr marker;
-
-  /* Create the subobject */
-  marker = (my_marker_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_marker_writer));
-  cinfo->marker = (struct jpeg_marker_writer *) marker;
-  /* Initialize method pointers */
-  marker->pub.write_file_header = write_file_header;
-  marker->pub.write_frame_header = write_frame_header;
-  marker->pub.write_scan_header = write_scan_header;
-  marker->pub.write_file_trailer = write_file_trailer;
-  marker->pub.write_tables_only = write_tables_only;
-  marker->pub.write_marker_header = write_marker_header;
-  marker->pub.write_marker_byte = write_marker_byte;
-  /* Initialize private state */
-  marker->last_restart_interval = 0;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcmaster.c ./Shared/jpeg-6b/jcmaster.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcmaster.c	Mon Dec  1 12:30:33 2003
+++ ./Shared/jpeg-6b/jcmaster.c	Wed Dec 31 19:00:00 1969
@@ -1,590 +0,0 @@
-/*
- * jcmaster.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains master control logic for the JPEG compressor.
- * These routines are concerned with parameter validation, initial setup,
- * and inter-pass control (determining the number of passes and the work 
- * to be done in each pass).
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Private state */
-
-typedef enum {
-	main_pass,		/* input data, also do first output step */
-	huff_opt_pass,		/* Huffman code optimization pass */
-	output_pass		/* data output pass */
-} c_pass_type;
-
-typedef struct {
-  struct jpeg_comp_master pub;	/* public fields */
-
-  c_pass_type pass_type;	/* the type of the current pass */
-
-  int pass_number;		/* # of passes completed */
-  int total_passes;		/* total # of passes needed */
-
-  int scan_number;		/* current index in scan_info[] */
-} my_comp_master;
-
-typedef my_comp_master * my_master_ptr;
-
-
-/*
- * Support routines that do various essential calculations.
- */
-
-LOCAL(void)
-initial_setup (j_compress_ptr cinfo)
-/* Do computations that are needed before master selection phase */
-{
-  int ci;
-  jpeg_component_info *compptr;
-  long samplesperrow;
-  JDIMENSION jd_samplesperrow;
-
-  /* Sanity check on image dimensions */
-  if (cinfo->image_height <= 0 || cinfo->image_width <= 0
-      || cinfo->num_components <= 0 || cinfo->input_components <= 0)
-    ERREXIT(cinfo, JERR_EMPTY_IMAGE);
-
-  /* Make sure image isn't bigger than I can handle */
-  if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
-      (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
-    ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
-
-  /* Width of an input scanline must be representable as JDIMENSION. */
-  samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
-  jd_samplesperrow = (JDIMENSION) samplesperrow;
-  if ((long) jd_samplesperrow != samplesperrow)
-    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
-
-  /* For now, precision must match compiled-in value... */
-  if (cinfo->data_precision != BITS_IN_JSAMPLE)
-    ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
-
-  /* Check that number of components won't exceed internal array sizes */
-  if (cinfo->num_components > MAX_COMPONENTS)
-    ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
-	     MAX_COMPONENTS);
-
-  /* Compute maximum sampling factors; check factor validity */
-  cinfo->max_h_samp_factor = 1;
-  cinfo->max_v_samp_factor = 1;
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
-	compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
-      ERREXIT(cinfo, JERR_BAD_SAMPLING);
-    cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
-				   compptr->h_samp_factor);
-    cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
-				   compptr->v_samp_factor);
-  }
-
-  /* Compute dimensions of components */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Fill in the correct component_index value; don't rely on application */
-    compptr->component_index = ci;
-    /* For compression, we never do DCT scaling. */
-    compptr->DCT_scaled_size = DCTSIZE;
-    /* Size in DCT blocks */
-    compptr->width_in_blocks = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
-		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
-    compptr->height_in_blocks = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
-		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
-    /* Size in samples */
-    compptr->downsampled_width = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
-		    (long) cinfo->max_h_samp_factor);
-    compptr->downsampled_height = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
-		    (long) cinfo->max_v_samp_factor);
-    /* Mark component needed (this flag isn't actually used for compression) */
-    compptr->component_needed = TRUE;
-  }
-
-  /* Compute number of fully interleaved MCU rows (number of times that
-   * main controller will call coefficient controller).
-   */
-  cinfo->total_iMCU_rows = (JDIMENSION)
-    jdiv_round_up((long) cinfo->image_height,
-		  (long) (cinfo->max_v_samp_factor*DCTSIZE));
-}
-
-
-#ifdef C_MULTISCAN_FILES_SUPPORTED
-
-LOCAL(void)
-validate_script (j_compress_ptr cinfo)
-/* Verify that the scan script in cinfo->scan_info[] is valid; also
- * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
- */
-{
-  const jpeg_scan_info * scanptr;
-  int scanno, ncomps, ci, coefi, thisi;
-  int Ss, Se, Ah, Al;
-  boolean component_sent[MAX_COMPONENTS];
-#ifdef C_PROGRESSIVE_SUPPORTED
-  int * last_bitpos_ptr;
-  int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
-  /* -1 until that coefficient has been seen; then last Al for it */
-#endif
-
-  if (cinfo->num_scans <= 0)
-    ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
-
-  /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
-   * for progressive JPEG, no scan can have this.
-   */
-  scanptr = cinfo->scan_info;
-  if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
-#ifdef C_PROGRESSIVE_SUPPORTED
-    cinfo->progressive_mode = TRUE;
-    last_bitpos_ptr = & last_bitpos[0][0];
-    for (ci = 0; ci < cinfo->num_components; ci++) 
-      for (coefi = 0; coefi < DCTSIZE2; coefi++)
-	*last_bitpos_ptr++ = -1;
-#else
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-  } else {
-    cinfo->progressive_mode = FALSE;
-    for (ci = 0; ci < cinfo->num_components; ci++) 
-      component_sent[ci] = FALSE;
-  }
-
-  for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
-    /* Validate component indexes */
-    ncomps = scanptr->comps_in_scan;
-    if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
-      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
-    for (ci = 0; ci < ncomps; ci++) {
-      thisi = scanptr->component_index[ci];
-      if (thisi < 0 || thisi >= cinfo->num_components)
-	ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
-      /* Components must appear in SOF order within each scan */
-      if (ci > 0 && thisi <= scanptr->component_index[ci-1])
-	ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
-    }
-    /* Validate progression parameters */
-    Ss = scanptr->Ss;
-    Se = scanptr->Se;
-    Ah = scanptr->Ah;
-    Al = scanptr->Al;
-    if (cinfo->progressive_mode) {
-#ifdef C_PROGRESSIVE_SUPPORTED
-      /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
-       * seems wrong: the upper bound ought to depend on data precision.
-       * Perhaps they really meant 0..N+1 for N-bit precision.
-       * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
-       * out-of-range reconstructed DC values during the first DC scan,
-       * which might cause problems for some decoders.
-       */
-#if BITS_IN_JSAMPLE == 8
-#define MAX_AH_AL 10
-#else
-#define MAX_AH_AL 13
-#endif
-      if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
-	  Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
-	ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
-      if (Ss == 0) {
-	if (Se != 0)		/* DC and AC together not OK */
-	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
-      } else {
-	if (ncomps != 1)	/* AC scans must be for only one component */
-	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
-      }
-      for (ci = 0; ci < ncomps; ci++) {
-	last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
-	if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
-	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
-	for (coefi = Ss; coefi <= Se; coefi++) {
-	  if (last_bitpos_ptr[coefi] < 0) {
-	    /* first scan of this coefficient */
-	    if (Ah != 0)
-	      ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
-	  } else {
-	    /* not first scan */
-	    if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
-	      ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
-	  }
-	  last_bitpos_ptr[coefi] = Al;
-	}
-      }
-#endif
-    } else {
-      /* For sequential JPEG, all progression parameters must be these: */
-      if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
-	ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
-      /* Make sure components are not sent twice */
-      for (ci = 0; ci < ncomps; ci++) {
-	thisi = scanptr->component_index[ci];
-	if (component_sent[thisi])
-	  ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
-	component_sent[thisi] = TRUE;
-      }
-    }
-  }
-
-  /* Now verify that everything got sent. */
-  if (cinfo->progressive_mode) {
-#ifdef C_PROGRESSIVE_SUPPORTED
-    /* For progressive mode, we only check that at least some DC data
-     * got sent for each component; the spec does not require that all bits
-     * of all coefficients be transmitted.  Would it be wiser to enforce
-     * transmission of all coefficient bits??
-     */
-    for (ci = 0; ci < cinfo->num_components; ci++) {
-      if (last_bitpos[ci][0] < 0)
-	ERREXIT(cinfo, JERR_MISSING_DATA);
-    }
-#endif
-  } else {
-    for (ci = 0; ci < cinfo->num_components; ci++) {
-      if (! component_sent[ci])
-	ERREXIT(cinfo, JERR_MISSING_DATA);
-    }
-  }
-}
-
-#endif /* C_MULTISCAN_FILES_SUPPORTED */
-
-
-LOCAL(void)
-select_scan_parameters (j_compress_ptr cinfo)
-/* Set up the scan parameters for the current scan */
-{
-  int ci;
-
-#ifdef C_MULTISCAN_FILES_SUPPORTED
-  if (cinfo->scan_info != NULL) {
-    /* Prepare for current scan --- the script is already validated */
-    my_master_ptr master = (my_master_ptr) cinfo->master;
-    const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
-
-    cinfo->comps_in_scan = scanptr->comps_in_scan;
-    for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
-      cinfo->cur_comp_info[ci] =
-	&cinfo->comp_info[scanptr->component_index[ci]];
-    }
-    cinfo->Ss = scanptr->Ss;
-    cinfo->Se = scanptr->Se;
-    cinfo->Ah = scanptr->Ah;
-    cinfo->Al = scanptr->Al;
-  }
-  else
-#endif
-  {
-    /* Prepare for single sequential-JPEG scan containing all components */
-    if (cinfo->num_components > MAX_COMPS_IN_SCAN)
-      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
-	       MAX_COMPS_IN_SCAN);
-    cinfo->comps_in_scan = cinfo->num_components;
-    for (ci = 0; ci < cinfo->num_components; ci++) {
-      cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
-    }
-    cinfo->Ss = 0;
-    cinfo->Se = DCTSIZE2-1;
-    cinfo->Ah = 0;
-    cinfo->Al = 0;
-  }
-}
-
-
-LOCAL(void)
-per_scan_setup (j_compress_ptr cinfo)
-/* Do computations that are needed before processing a JPEG scan */
-/* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
-{
-  int ci, mcublks, tmp;
-  jpeg_component_info *compptr;
-  
-  if (cinfo->comps_in_scan == 1) {
-    
-    /* Noninterleaved (single-component) scan */
-    compptr = cinfo->cur_comp_info[0];
-    
-    /* Overall image size in MCUs */
-    cinfo->MCUs_per_row = compptr->width_in_blocks;
-    cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
-    
-    /* For noninterleaved scan, always one block per MCU */
-    compptr->MCU_width = 1;
-    compptr->MCU_height = 1;
-    compptr->MCU_blocks = 1;
-    compptr->MCU_sample_width = DCTSIZE;
-    compptr->last_col_width = 1;
-    /* For noninterleaved scans, it is convenient to define last_row_height
-     * as the number of block rows present in the last iMCU row.
-     */
-    tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
-    if (tmp == 0) tmp = compptr->v_samp_factor;
-    compptr->last_row_height = tmp;
-    
-    /* Prepare array describing MCU composition */
-    cinfo->blocks_in_MCU = 1;
-    cinfo->MCU_membership[0] = 0;
-    
-  } else {
-    
-    /* Interleaved (multi-component) scan */
-    if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
-      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
-	       MAX_COMPS_IN_SCAN);
-    
-    /* Overall image size in MCUs */
-    cinfo->MCUs_per_row = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width,
-		    (long) (cinfo->max_h_samp_factor*DCTSIZE));
-    cinfo->MCU_rows_in_scan = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height,
-		    (long) (cinfo->max_v_samp_factor*DCTSIZE));
-    
-    cinfo->blocks_in_MCU = 0;
-    
-    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-      compptr = cinfo->cur_comp_info[ci];
-      /* Sampling factors give # of blocks of component in each MCU */
-      compptr->MCU_width = compptr->h_samp_factor;
-      compptr->MCU_height = compptr->v_samp_factor;
-      compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
-      compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
-      /* Figure number of non-dummy blocks in last MCU column & row */
-      tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
-      if (tmp == 0) tmp = compptr->MCU_width;
-      compptr->last_col_width = tmp;
-      tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
-      if (tmp == 0) tmp = compptr->MCU_height;
-      compptr->last_row_height = tmp;
-      /* Prepare array describing MCU composition */
-      mcublks = compptr->MCU_blocks;
-      if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
-	ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
-      while (mcublks-- > 0) {
-	cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
-      }
-    }
-    
-  }
-
-  /* Convert restart specified in rows to actual MCU count. */
-  /* Note that count must fit in 16 bits, so we provide limiting. */
-  if (cinfo->restart_in_rows > 0) {
-    long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
-    cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
-  }
-}
-
-
-/*
- * Per-pass setup.
- * This is called at the beginning of each pass.  We determine which modules
- * will be active during this pass and give them appropriate start_pass calls.
- * We also set is_last_pass to indicate whether any more passes will be
- * required.
- */
-
-METHODDEF(void)
-prepare_for_pass (j_compress_ptr cinfo)
-{
-  my_master_ptr master = (my_master_ptr) cinfo->master;
-
-  switch (master->pass_type) {
-  case main_pass:
-    /* Initial pass: will collect input data, and do either Huffman
-     * optimization or data output for the first scan.
-     */
-    select_scan_parameters(cinfo);
-    per_scan_setup(cinfo);
-    if (! cinfo->raw_data_in) {
-      (*cinfo->cconvert->start_pass) (cinfo);
-      (*cinfo->downsample->start_pass) (cinfo);
-      (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
-    }
-    (*cinfo->fdct->start_pass) (cinfo);
-    (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
-    (*cinfo->coef->start_pass) (cinfo,
-				(master->total_passes > 1 ?
-				 JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
-    (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
-    if (cinfo->optimize_coding) {
-      /* No immediate data output; postpone writing frame/scan headers */
-      master->pub.call_pass_startup = FALSE;
-    } else {
-      /* Will write frame/scan headers at first jpeg_write_scanlines call */
-      master->pub.call_pass_startup = TRUE;
-    }
-    break;
-#ifdef ENTROPY_OPT_SUPPORTED
-  case huff_opt_pass:
-    /* Do Huffman optimization for a scan after the first one. */
-    select_scan_parameters(cinfo);
-    per_scan_setup(cinfo);
-    if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
-      (*cinfo->entropy->start_pass) (cinfo, TRUE);
-      (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
-      master->pub.call_pass_startup = FALSE;
-      break;
-    }
-    /* Special case: Huffman DC refinement scans need no Huffman table
-     * and therefore we can skip the optimization pass for them.
-     */
-    master->pass_type = output_pass;
-    master->pass_number++;
-    /*FALLTHROUGH*/
-#endif
-  case output_pass:
-    /* Do a data-output pass. */
-    /* We need not repeat per-scan setup if prior optimization pass did it. */
-    if (! cinfo->optimize_coding) {
-      select_scan_parameters(cinfo);
-      per_scan_setup(cinfo);
-    }
-    (*cinfo->entropy->start_pass) (cinfo, FALSE);
-    (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
-    /* We emit frame/scan headers now */
-    if (master->scan_number == 0)
-      (*cinfo->marker->write_frame_header) (cinfo);
-    (*cinfo->marker->write_scan_header) (cinfo);
-    master->pub.call_pass_startup = FALSE;
-    break;
-  default:
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-  }
-
-  master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
-
-  /* Set up progress monitor's pass info if present */
-  if (cinfo->progress != NULL) {
-    cinfo->progress->completed_passes = master->pass_number;
-    cinfo->progress->total_passes = master->total_passes;
-  }
-}
-
-
-/*
- * Special start-of-pass hook.
- * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
- * In single-pass processing, we need this hook because we don't want to
- * write frame/scan headers during jpeg_start_compress; we want to let the
- * application write COM markers etc. between jpeg_start_compress and the
- * jpeg_write_scanlines loop.
- * In multi-pass processing, this routine is not used.
- */
-
-METHODDEF(void)
-pass_startup (j_compress_ptr cinfo)
-{
-  cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
-
-  (*cinfo->marker->write_frame_header) (cinfo);
-  (*cinfo->marker->write_scan_header) (cinfo);
-}
-
-
-/*
- * Finish up at end of pass.
- */
-
-METHODDEF(void)
-finish_pass_master (j_compress_ptr cinfo)
-{
-  my_master_ptr master = (my_master_ptr) cinfo->master;
-
-  /* The entropy coder always needs an end-of-pass call,
-   * either to analyze statistics or to flush its output buffer.
-   */
-  (*cinfo->entropy->finish_pass) (cinfo);
-
-  /* Update state for next pass */
-  switch (master->pass_type) {
-  case main_pass:
-    /* next pass is either output of scan 0 (after optimization)
-     * or output of scan 1 (if no optimization).
-     */
-    master->pass_type = output_pass;
-    if (! cinfo->optimize_coding)
-      master->scan_number++;
-    break;
-  case huff_opt_pass:
-    /* next pass is always output of current scan */
-    master->pass_type = output_pass;
-    break;
-  case output_pass:
-    /* next pass is either optimization or output of next scan */
-    if (cinfo->optimize_coding)
-      master->pass_type = huff_opt_pass;
-    master->scan_number++;
-    break;
-  }
-
-  master->pass_number++;
-}
-
-
-/*
- * Initialize master compression control.
- */
-
-GLOBAL(void)
-jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
-{
-  my_master_ptr master;
-
-  master = (my_master_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(my_comp_master));
-  cinfo->master = (struct jpeg_comp_master *) master;
-  master->pub.prepare_for_pass = prepare_for_pass;
-  master->pub.pass_startup = pass_startup;
-  master->pub.finish_pass = finish_pass_master;
-  master->pub.is_last_pass = FALSE;
-
-  /* Validate parameters, determine derived values */
-  initial_setup(cinfo);
-
-  if (cinfo->scan_info != NULL) {
-#ifdef C_MULTISCAN_FILES_SUPPORTED
-    validate_script(cinfo);
-#else
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-  } else {
-    cinfo->progressive_mode = FALSE;
-    cinfo->num_scans = 1;
-  }
-
-  if (cinfo->progressive_mode)	/*  TEMPORARY HACK ??? */
-    cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
-
-  /* Initialize my private state */
-  if (transcode_only) {
-    /* no main pass in transcoding */
-    if (cinfo->optimize_coding)
-      master->pass_type = huff_opt_pass;
-    else
-      master->pass_type = output_pass;
-  } else {
-    /* for normal compression, first pass is always this type: */
-    master->pass_type = main_pass;
-  }
-  master->scan_number = 0;
-  master->pass_number = 0;
-  if (cinfo->optimize_coding)
-    master->total_passes = cinfo->num_scans * 2;
-  else
-    master->total_passes = cinfo->num_scans;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcomapi.c ./Shared/jpeg-6b/jcomapi.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcomapi.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jcomapi.c	Wed Dec 31 19:00:00 1969
@@ -1,106 +0,0 @@
-/*
- * jcomapi.c
- *
- * Copyright (C) 1994-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains application interface routines that are used for both
- * compression and decompression.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * Abort processing of a JPEG compression or decompression operation,
- * but don't destroy the object itself.
- *
- * For this, we merely clean up all the nonpermanent memory pools.
- * Note that temp files (virtual arrays) are not allowed to belong to
- * the permanent pool, so we will be able to close all temp files here.
- * Closing a data source or destination, if necessary, is the application's
- * responsibility.
- */
-
-GLOBAL(void)
-jpeg_abort (j_common_ptr cinfo)
-{
-  int pool;
-
-  /* Do nothing if called on a not-initialized or destroyed JPEG object. */
-  if (cinfo->mem == NULL)
-    return;
-
-  /* Releasing pools in reverse order might help avoid fragmentation
-   * with some (brain-damaged) malloc libraries.
-   */
-  for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
-    (*cinfo->mem->free_pool) (cinfo, pool);
-  }
-
-  /* Reset overall state for possible reuse of object */
-  if (cinfo->is_decompressor) {
-    cinfo->global_state = DSTATE_START;
-    /* Try to keep application from accessing now-deleted marker list.
-     * A bit kludgy to do it here, but this is the most central place.
-     */
-    ((j_decompress_ptr) cinfo)->marker_list = NULL;
-  } else {
-    cinfo->global_state = CSTATE_START;
-  }
-}
-
-
-/*
- * Destruction of a JPEG object.
- *
- * Everything gets deallocated except the master jpeg_compress_struct itself
- * and the error manager struct.  Both of these are supplied by the application
- * and must be freed, if necessary, by the application.  (Often they are on
- * the stack and so don't need to be freed anyway.)
- * Closing a data source or destination, if necessary, is the application's
- * responsibility.
- */
-
-GLOBAL(void)
-jpeg_destroy (j_common_ptr cinfo)
-{
-  /* We need only tell the memory manager to release everything. */
-  /* NB: mem pointer is NULL if memory mgr failed to initialize. */
-  if (cinfo->mem != NULL)
-    (*cinfo->mem->self_destruct) (cinfo);
-  cinfo->mem = NULL;		/* be safe if jpeg_destroy is called twice */
-  cinfo->global_state = 0;	/* mark it destroyed */
-}
-
-
-/*
- * Convenience routines for allocating quantization and Huffman tables.
- * (Would jutils.c be a more reasonable place to put these?)
- */
-
-GLOBAL(JQUANT_TBL *)
-jpeg_alloc_quant_table (j_common_ptr cinfo)
-{
-  JQUANT_TBL *tbl;
-
-  tbl = (JQUANT_TBL *)
-    (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
-  tbl->sent_table = FALSE;	/* make sure this is false in any new table */
-  return tbl;
-}
-
-
-GLOBAL(JHUFF_TBL *)
-jpeg_alloc_huff_table (j_common_ptr cinfo)
-{
-  JHUFF_TBL *tbl;
-
-  tbl = (JHUFF_TBL *)
-    (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
-  tbl->sent_table = FALSE;	/* make sure this is false in any new table */
-  return tbl;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jconfig.doc ./Shared/jpeg-6b/jconfig.doc
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jconfig.doc	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jconfig.doc	Wed Dec 31 19:00:00 1969
@@ -1,155 +0,0 @@
-/*
- * jconfig.doc
- *
- * Copyright (C) 1991-1994, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file documents the configuration options that are required to
- * customize the JPEG software for a particular system.
- *
- * The actual configuration options for a particular installation are stored
- * in jconfig.h.  On many machines, jconfig.h can be generated automatically
- * or copied from one of the "canned" jconfig files that we supply.  But if
- * you need to generate a jconfig.h file by hand, this file tells you how.
- *
- * DO NOT EDIT THIS FILE --- IT WON'T ACCOMPLISH ANYTHING.
- * EDIT A COPY NAMED JCONFIG.H.
- */
-
-
-/*
- * These symbols indicate the properties of your machine or compiler.
- * #define the symbol if yes, #undef it if no.
- */
-
-/* Does your compiler support function prototypes?
- * (If not, you also need to use ansi2knr, see install.doc)
- */
-#define HAVE_PROTOTYPES
-
-/* Does your compiler support the declaration "unsigned char" ?
- * How about "unsigned short" ?
- */
-#define HAVE_UNSIGNED_CHAR
-#define HAVE_UNSIGNED_SHORT
-
-/* Define "void" as "char" if your compiler doesn't know about type void.
- * NOTE: be sure to define void such that "void *" represents the most general
- * pointer type, e.g., that returned by malloc().
- */
-/* #define void char */
-
-/* Define "const" as empty if your compiler doesn't know the "const" keyword.
- */
-/* #define const */
-
-/* Define this if an ordinary "char" type is unsigned.
- * If you're not sure, leaving it undefined will work at some cost in speed.
- * If you defined HAVE_UNSIGNED_CHAR then the speed difference is minimal.
- */
-#undef CHAR_IS_UNSIGNED
-
-/* Define this if your system has an ANSI-conforming <stddef.h> file.
- */
-#define HAVE_STDDEF_H
-
-/* Define this if your system has an ANSI-conforming <stdlib.h> file.
- */
-#define HAVE_STDLIB_H
-
-/* Define this if your system does not have an ANSI/SysV <string.h>,
- * but does have a BSD-style <strings.h>.
- */
-#undef NEED_BSD_STRINGS
-
-/* Define this if your system does not provide typedef size_t in any of the
- * ANSI-standard places (stddef.h, stdlib.h, or stdio.h), but places it in
- * <sys/types.h> instead.
- */
-#undef NEED_SYS_TYPES_H
-
-/* For 80x86 machines, you need to define NEED_FAR_POINTERS,
- * unless you are using a large-data memory model or 80386 flat-memory mode.
- * On less brain-damaged CPUs this symbol must not be defined.
- * (Defining this symbol causes large data structures to be referenced through
- * "far" pointers and to be allocated with a special version of malloc.)
- */
-#undef NEED_FAR_POINTERS
-
-/* Define this if your linker needs global names to be unique in less
- * than the first 15 characters.
- */
-#undef NEED_SHORT_EXTERNAL_NAMES
-
-/* Although a real ANSI C compiler can deal perfectly well with pointers to
- * unspecified structures (see "incomplete types" in the spec), a few pre-ANSI
- * and pseudo-ANSI compilers get confused.  To keep one of these bozos happy,
- * define INCOMPLETE_TYPES_BROKEN.  This is not recommended unless you
- * actually get "missing structure definition" warnings or errors while
- * compiling the JPEG code.
- */
-#undef INCOMPLETE_TYPES_BROKEN
-
-
-/*
- * The following options affect code selection within the JPEG library,
- * but they don't need to be visible to applications using the library.
- * To minimize application namespace pollution, the symbols won't be
- * defined unless JPEG_INTERNALS has been defined.
- */
-
-#ifdef JPEG_INTERNALS
-
-/* Define this if your compiler implements ">>" on signed values as a logical
- * (unsigned) shift; leave it undefined if ">>" is a signed (arithmetic) shift,
- * which is the normal and rational definition.
- */
-#undef RIGHT_SHIFT_IS_UNSIGNED
-
-
-#endif /* JPEG_INTERNALS */
-
-
-/*
- * The remaining options do not affect the JPEG library proper,
- * but only the sample applications cjpeg/djpeg (see cjpeg.c, djpeg.c).
- * Other applications can ignore these.
- */
-
-#ifdef JPEG_CJPEG_DJPEG
-
-/* These defines indicate which image (non-JPEG) file formats are allowed. */
-
-#define BMP_SUPPORTED		/* BMP image file format */
-#define GIF_SUPPORTED		/* GIF image file format */
-#define PPM_SUPPORTED		/* PBMPLUS PPM/PGM image file format */
-#undef RLE_SUPPORTED		/* Utah RLE image file format */
-#define TARGA_SUPPORTED		/* Targa image file format */
-
-/* Define this if you want to name both input and output files on the command
- * line, rather than using stdout and optionally stdin.  You MUST do this if
- * your system can't cope with binary I/O to stdin/stdout.  See comments at
- * head of cjpeg.c or djpeg.c.
- */
-#undef TWO_FILE_COMMANDLINE
-
-/* Define this if your system needs explicit cleanup of temporary files.
- * This is crucial under MS-DOS, where the temporary "files" may be areas
- * of extended memory; on most other systems it's not as important.
- */
-#undef NEED_SIGNAL_CATCHER
-
-/* By default, we open image files with fopen(...,"rb") or fopen(...,"wb").
- * This is necessary on systems that distinguish text files from binary files,
- * and is harmless on most systems that don't.  If you have one of the rare
- * systems that complains about the "b" spec, define this symbol.
- */
-#undef DONT_USE_B_MODE
-
-/* Define this if you want percent-done progress reports from cjpeg/djpeg.
- */
-#undef PROGRESS_REPORT
-
-
-#endif /* JPEG_CJPEG_DJPEG */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jconfig.h ./Shared/jpeg-6b/jconfig.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jconfig.h	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jconfig.h	Wed Dec 31 19:00:00 1969
@@ -1,45 +0,0 @@
-/* jconfig.h.  Generated automatically by configure.  */
-/* jconfig.cfg --- source file edited by configure script */
-/* see jconfig.doc for explanations */
-
-#define HAVE_PROTOTYPES 
-#define HAVE_UNSIGNED_CHAR 
-#define HAVE_UNSIGNED_SHORT 
-#undef void
-#undef const
-#undef CHAR_IS_UNSIGNED
-#define HAVE_STDDEF_H 
-#define HAVE_STDLIB_H 
-#undef NEED_BSD_STRINGS
-#undef NEED_SYS_TYPES_H
-#undef NEED_FAR_POINTERS
-#undef NEED_SHORT_EXTERNAL_NAMES
-/* Define this if you get warnings about undefined structures. */
-#undef INCOMPLETE_TYPES_BROKEN
-
-#ifdef JPEG_INTERNALS
-
-#undef RIGHT_SHIFT_IS_UNSIGNED
-#define INLINE __inline__
-/* These are for configuring the JPEG memory manager. */
-#undef DEFAULT_MAX_MEM
-#undef NO_MKTEMP
-
-#endif /* JPEG_INTERNALS */
-
-#ifdef JPEG_CJPEG_DJPEG
-
-#define BMP_SUPPORTED		/* BMP image file format */
-#define GIF_SUPPORTED		/* GIF image file format */
-#define PPM_SUPPORTED		/* PBMPLUS PPM/PGM image file format */
-#undef RLE_SUPPORTED		/* Utah RLE image file format */
-#define TARGA_SUPPORTED		/* Targa image file format */
-
-#undef TWO_FILE_COMMANDLINE
-#undef NEED_SIGNAL_CATCHER
-#undef DONT_USE_B_MODE
-
-/* Define this if you want percent-done progress reports from cjpeg/djpeg. */
-#undef PROGRESS_REPORT
-
-#endif /* JPEG_CJPEG_DJPEG */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcparam.c ./Shared/jpeg-6b/jcparam.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcparam.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jcparam.c	Wed Dec 31 19:00:00 1969
@@ -1,610 +0,0 @@
-/*
- * jcparam.c
- *
- * Copyright (C) 1991-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains optional default-setting code for the JPEG compressor.
- * Applications do not have to use this file, but those that don't use it
- * must know a lot more about the innards of the JPEG code.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * Quantization table setup routines
- */
-
-GLOBAL(void)
-jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
-		      const unsigned int *basic_table,
-		      int scale_factor, boolean force_baseline)
-/* Define a quantization table equal to the basic_table times
- * a scale factor (given as a percentage).
- * If force_baseline is TRUE, the computed quantization table entries
- * are limited to 1..255 for JPEG baseline compatibility.
- */
-{
-  JQUANT_TBL ** qtblptr;
-  int i;
-  long temp;
-
-  /* Safety check to ensure start_compress not called yet. */
-  if (cinfo->global_state != CSTATE_START)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
-    ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
-
-  qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
-
-  if (*qtblptr == NULL)
-    *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
-
-  for (i = 0; i < DCTSIZE2; i++) {
-    temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
-    /* limit the values to the valid range */
-    if (temp <= 0L) temp = 1L;
-    if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
-    if (force_baseline && temp > 255L)
-      temp = 255L;		/* limit to baseline range if requested */
-    (*qtblptr)->quantval[i] = (UINT16) temp;
-  }
-
-  /* Initialize sent_table FALSE so table will be written to JPEG file. */
-  (*qtblptr)->sent_table = FALSE;
-}
-
-
-GLOBAL(void)
-jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
-			 boolean force_baseline)
-/* Set or change the 'quality' (quantization) setting, using default tables
- * and a straight percentage-scaling quality scale.  In most cases it's better
- * to use jpeg_set_quality (below); this entry point is provided for
- * applications that insist on a linear percentage scaling.
- */
-{
-  /* These are the sample quantization tables given in JPEG spec section K.1.
-   * The spec says that the values given produce "good" quality, and
-   * when divided by 2, "very good" quality.
-   */
-  static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
-    16,  11,  10,  16,  24,  40,  51,  61,
-    12,  12,  14,  19,  26,  58,  60,  55,
-    14,  13,  16,  24,  40,  57,  69,  56,
-    14,  17,  22,  29,  51,  87,  80,  62,
-    18,  22,  37,  56,  68, 109, 103,  77,
-    24,  35,  55,  64,  81, 104, 113,  92,
-    49,  64,  78,  87, 103, 121, 120, 101,
-    72,  92,  95,  98, 112, 100, 103,  99
-  };
-  static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
-    17,  18,  24,  47,  99,  99,  99,  99,
-    18,  21,  26,  66,  99,  99,  99,  99,
-    24,  26,  56,  99,  99,  99,  99,  99,
-    47,  66,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99
-  };
-
-  /* Set up two quantization tables using the specified scaling */
-  jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
-		       scale_factor, force_baseline);
-  jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
-		       scale_factor, force_baseline);
-}
-
-
-GLOBAL(int)
-jpeg_quality_scaling (int quality)
-/* Convert a user-specified quality rating to a percentage scaling factor
- * for an underlying quantization table, using our recommended scaling curve.
- * The input 'quality' factor should be 0 (terrible) to 100 (very good).
- */
-{
-  /* Safety limit on quality factor.  Convert 0 to 1 to avoid zero divide. */
-  if (quality <= 0) quality = 1;
-  if (quality > 100) quality = 100;
-
-  /* The basic table is used as-is (scaling 100) for a quality of 50.
-   * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
-   * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
-   * to make all the table entries 1 (hence, minimum quantization loss).
-   * Qualities 1..50 are converted to scaling percentage 5000/Q.
-   */
-  if (quality < 50)
-    quality = 5000 / quality;
-  else
-    quality = 200 - quality*2;
-
-  return quality;
-}
-
-
-GLOBAL(void)
-jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
-/* Set or change the 'quality' (quantization) setting, using default tables.
- * This is the standard quality-adjusting entry point for typical user
- * interfaces; only those who want detailed control over quantization tables
- * would use the preceding three routines directly.
- */
-{
-  /* Convert user 0-100 rating to percentage scaling */
-  quality = jpeg_quality_scaling(quality);
-
-  /* Set up standard quality tables */
-  jpeg_set_linear_quality(cinfo, quality, force_baseline);
-}
-
-
-/*
- * Huffman table setup routines
- */
-
-LOCAL(void)
-add_huff_table (j_compress_ptr cinfo,
-		JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
-/* Define a Huffman table */
-{
-  int nsymbols, len;
-
-  if (*htblptr == NULL)
-    *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
-
-  /* Copy the number-of-symbols-of-each-code-length counts */
-  MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
-
-  /* Validate the counts.  We do this here mainly so we can copy the right
-   * number of symbols from the val[] array, without risking marching off
-   * the end of memory.  jchuff.c will do a more thorough test later.
-   */
-  nsymbols = 0;
-  for (len = 1; len <= 16; len++)
-    nsymbols += bits[len];
-  if (nsymbols < 1 || nsymbols > 256)
-    ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-
-  MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
-
-  /* Initialize sent_table FALSE so table will be written to JPEG file. */
-  (*htblptr)->sent_table = FALSE;
-}
-
-
-LOCAL(void)
-std_huff_tables (j_compress_ptr cinfo)
-/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
-/* IMPORTANT: these are only valid for 8-bit data precision! */
-{
-  static const UINT8 bits_dc_luminance[17] =
-    { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
-  static const UINT8 val_dc_luminance[] =
-    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
-  
-  static const UINT8 bits_dc_chrominance[17] =
-    { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
-  static const UINT8 val_dc_chrominance[] =
-    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
-  
-  static const UINT8 bits_ac_luminance[17] =
-    { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
-  static const UINT8 val_ac_luminance[] =
-    { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
-      0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
-      0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
-      0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
-      0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
-      0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
-      0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
-      0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
-      0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
-      0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
-      0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
-      0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
-      0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
-      0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
-      0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
-      0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
-      0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
-      0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
-      0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
-      0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
-      0xf9, 0xfa };
-  
-  static const UINT8 bits_ac_chrominance[17] =
-    { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
-  static const UINT8 val_ac_chrominance[] =
-    { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
-      0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
-      0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
-      0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
-      0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
-      0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
-      0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
-      0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
-      0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
-      0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
-      0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
-      0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
-      0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
-      0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
-      0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
-      0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
-      0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
-      0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
-      0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
-      0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
-      0xf9, 0xfa };
-  
-  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
-		 bits_dc_luminance, val_dc_luminance);
-  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
-		 bits_ac_luminance, val_ac_luminance);
-  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
-		 bits_dc_chrominance, val_dc_chrominance);
-  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
-		 bits_ac_chrominance, val_ac_chrominance);
-}
-
-
-/*
- * Default parameter setup for compression.
- *
- * Applications that don't choose to use this routine must do their
- * own setup of all these parameters.  Alternately, you can call this
- * to establish defaults and then alter parameters selectively.  This
- * is the recommended approach since, if we add any new parameters,
- * your code will still work (they'll be set to reasonable defaults).
- */
-
-GLOBAL(void)
-jpeg_set_defaults (j_compress_ptr cinfo)
-{
-  int i;
-
-  /* Safety check to ensure start_compress not called yet. */
-  if (cinfo->global_state != CSTATE_START)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  /* Allocate comp_info array large enough for maximum component count.
-   * Array is made permanent in case application wants to compress
-   * multiple images at same param settings.
-   */
-  if (cinfo->comp_info == NULL)
-    cinfo->comp_info = (jpeg_component_info *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
-				  MAX_COMPONENTS * SIZEOF(jpeg_component_info));
-
-  /* Initialize everything not dependent on the color space */
-
-  cinfo->data_precision = BITS_IN_JSAMPLE;
-  /* Set up two quantization tables using default quality of 75 */
-  jpeg_set_quality(cinfo, 75, TRUE);
-  /* Set up two Huffman tables */
-  std_huff_tables(cinfo);
-
-  /* Initialize default arithmetic coding conditioning */
-  for (i = 0; i < NUM_ARITH_TBLS; i++) {
-    cinfo->arith_dc_L[i] = 0;
-    cinfo->arith_dc_U[i] = 1;
-    cinfo->arith_ac_K[i] = 5;
-  }
-
-  /* Default is no multiple-scan output */
-  cinfo->scan_info = NULL;
-  cinfo->num_scans = 0;
-
-  /* Expect normal source image, not raw downsampled data */
-  cinfo->raw_data_in = FALSE;
-
-  /* Use Huffman coding, not arithmetic coding, by default */
-  cinfo->arith_code = FALSE;
-
-  /* By default, don't do extra passes to optimize entropy coding */
-  cinfo->optimize_coding = FALSE;
-  /* The standard Huffman tables are only valid for 8-bit data precision.
-   * If the precision is higher, force optimization on so that usable
-   * tables will be computed.  This test can be removed if default tables
-   * are supplied that are valid for the desired precision.
-   */
-  if (cinfo->data_precision > 8)
-    cinfo->optimize_coding = TRUE;
-
-  /* By default, use the simpler non-cosited sampling alignment */
-  cinfo->CCIR601_sampling = FALSE;
-
-  /* No input smoothing */
-  cinfo->smoothing_factor = 0;
-
-  /* DCT algorithm preference */
-  cinfo->dct_method = JDCT_DEFAULT;
-
-  /* No restart markers */
-  cinfo->restart_interval = 0;
-  cinfo->restart_in_rows = 0;
-
-  /* Fill in default JFIF marker parameters.  Note that whether the marker
-   * will actually be written is determined by jpeg_set_colorspace.
-   *
-   * By default, the library emits JFIF version code 1.01.
-   * An application that wants to emit JFIF 1.02 extension markers should set
-   * JFIF_minor_version to 2.  We could probably get away with just defaulting
-   * to 1.02, but there may still be some decoders in use that will complain
-   * about that; saying 1.01 should minimize compatibility problems.
-   */
-  cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
-  cinfo->JFIF_minor_version = 1;
-  cinfo->density_unit = 0;	/* Pixel size is unknown by default */
-  cinfo->X_density = 1;		/* Pixel aspect ratio is square by default */
-  cinfo->Y_density = 1;
-
-  /* Choose JPEG colorspace based on input space, set defaults accordingly */
-
-  jpeg_default_colorspace(cinfo);
-}
-
-
-/*
- * Select an appropriate JPEG colorspace for in_color_space.
- */
-
-GLOBAL(void)
-jpeg_default_colorspace (j_compress_ptr cinfo)
-{
-  switch (cinfo->in_color_space) {
-  case JCS_GRAYSCALE:
-    jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
-    break;
-  case JCS_RGB:
-    jpeg_set_colorspace(cinfo, JCS_YCbCr);
-    break;
-  case JCS_YCbCr:
-    jpeg_set_colorspace(cinfo, JCS_YCbCr);
-    break;
-  case JCS_CMYK:
-    jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
-    break;
-  case JCS_YCCK:
-    jpeg_set_colorspace(cinfo, JCS_YCCK);
-    break;
-  case JCS_UNKNOWN:
-    jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
-    break;
-  default:
-    ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
-  }
-}
-
-
-/*
- * Set the JPEG colorspace, and choose colorspace-dependent default values.
- */
-
-GLOBAL(void)
-jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
-{
-  jpeg_component_info * compptr;
-  int ci;
-
-#define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl)  \
-  (compptr = &cinfo->comp_info[index], \
-   compptr->component_id = (id), \
-   compptr->h_samp_factor = (hsamp), \
-   compptr->v_samp_factor = (vsamp), \
-   compptr->quant_tbl_no = (quant), \
-   compptr->dc_tbl_no = (dctbl), \
-   compptr->ac_tbl_no = (actbl) )
-
-  /* Safety check to ensure start_compress not called yet. */
-  if (cinfo->global_state != CSTATE_START)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
-   * tables 1 for chrominance components.
-   */
-
-  cinfo->jpeg_color_space = colorspace;
-
-  cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
-  cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
-
-  switch (colorspace) {
-  case JCS_GRAYSCALE:
-    cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
-    cinfo->num_components = 1;
-    /* JFIF specifies component ID 1 */
-    SET_COMP(0, 1, 1,1, 0, 0,0);
-    break;
-  case JCS_RGB:
-    cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
-    cinfo->num_components = 3;
-    SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
-    SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
-    SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
-    break;
-  case JCS_YCbCr:
-    cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
-    cinfo->num_components = 3;
-    /* JFIF specifies component IDs 1,2,3 */
-    /* We default to 2x2 subsamples of chrominance */
-    SET_COMP(0, 1, 2,2, 0, 0,0);
-    SET_COMP(1, 2, 1,1, 1, 1,1);
-    SET_COMP(2, 3, 1,1, 1, 1,1);
-    break;
-  case JCS_CMYK:
-    cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
-    cinfo->num_components = 4;
-    SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
-    SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
-    SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
-    SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
-    break;
-  case JCS_YCCK:
-    cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
-    cinfo->num_components = 4;
-    SET_COMP(0, 1, 2,2, 0, 0,0);
-    SET_COMP(1, 2, 1,1, 1, 1,1);
-    SET_COMP(2, 3, 1,1, 1, 1,1);
-    SET_COMP(3, 4, 2,2, 0, 0,0);
-    break;
-  case JCS_UNKNOWN:
-    cinfo->num_components = cinfo->input_components;
-    if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
-      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
-	       MAX_COMPONENTS);
-    for (ci = 0; ci < cinfo->num_components; ci++) {
-      SET_COMP(ci, ci, 1,1, 0, 0,0);
-    }
-    break;
-  default:
-    ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-  }
-}
-
-
-#ifdef C_PROGRESSIVE_SUPPORTED
-
-LOCAL(jpeg_scan_info *)
-fill_a_scan (jpeg_scan_info * scanptr, int ci,
-	     int Ss, int Se, int Ah, int Al)
-/* Support routine: generate one scan for specified component */
-{
-  scanptr->comps_in_scan = 1;
-  scanptr->component_index[0] = ci;
-  scanptr->Ss = Ss;
-  scanptr->Se = Se;
-  scanptr->Ah = Ah;
-  scanptr->Al = Al;
-  scanptr++;
-  return scanptr;
-}
-
-LOCAL(jpeg_scan_info *)
-fill_scans (jpeg_scan_info * scanptr, int ncomps,
-	    int Ss, int Se, int Ah, int Al)
-/* Support routine: generate one scan for each component */
-{
-  int ci;
-
-  for (ci = 0; ci < ncomps; ci++) {
-    scanptr->comps_in_scan = 1;
-    scanptr->component_index[0] = ci;
-    scanptr->Ss = Ss;
-    scanptr->Se = Se;
-    scanptr->Ah = Ah;
-    scanptr->Al = Al;
-    scanptr++;
-  }
-  return scanptr;
-}
-
-LOCAL(jpeg_scan_info *)
-fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
-/* Support routine: generate interleaved DC scan if possible, else N scans */
-{
-  int ci;
-
-  if (ncomps <= MAX_COMPS_IN_SCAN) {
-    /* Single interleaved DC scan */
-    scanptr->comps_in_scan = ncomps;
-    for (ci = 0; ci < ncomps; ci++)
-      scanptr->component_index[ci] = ci;
-    scanptr->Ss = scanptr->Se = 0;
-    scanptr->Ah = Ah;
-    scanptr->Al = Al;
-    scanptr++;
-  } else {
-    /* Noninterleaved DC scan for each component */
-    scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
-  }
-  return scanptr;
-}
-
-
-/*
- * Create a recommended progressive-JPEG script.
- * cinfo->num_components and cinfo->jpeg_color_space must be correct.
- */
-
-GLOBAL(void)
-jpeg_simple_progression (j_compress_ptr cinfo)
-{
-  int ncomps = cinfo->num_components;
-  int nscans;
-  jpeg_scan_info * scanptr;
-
-  /* Safety check to ensure start_compress not called yet. */
-  if (cinfo->global_state != CSTATE_START)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  /* Figure space needed for script.  Calculation must match code below! */
-  if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
-    /* Custom script for YCbCr color images. */
-    nscans = 10;
-  } else {
-    /* All-purpose script for other color spaces. */
-    if (ncomps > MAX_COMPS_IN_SCAN)
-      nscans = 6 * ncomps;	/* 2 DC + 4 AC scans per component */
-    else
-      nscans = 2 + 4 * ncomps;	/* 2 DC scans; 4 AC scans per component */
-  }
-
-  /* Allocate space for script.
-   * We need to put it in the permanent pool in case the application performs
-   * multiple compressions without changing the settings.  To avoid a memory
-   * leak if jpeg_simple_progression is called repeatedly for the same JPEG
-   * object, we try to re-use previously allocated space, and we allocate
-   * enough space to handle YCbCr even if initially asked for grayscale.
-   */
-  if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
-    cinfo->script_space_size = MAX(nscans, 10);
-    cinfo->script_space = (jpeg_scan_info *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
-			cinfo->script_space_size * SIZEOF(jpeg_scan_info));
-  }
-  scanptr = cinfo->script_space;
-  cinfo->scan_info = scanptr;
-  cinfo->num_scans = nscans;
-
-  if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
-    /* Custom script for YCbCr color images. */
-    /* Initial DC scan */
-    scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
-    /* Initial AC scan: get some luma data out in a hurry */
-    scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
-    /* Chroma data is too small to be worth expending many scans on */
-    scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
-    scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
-    /* Complete spectral selection for luma AC */
-    scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
-    /* Refine next bit of luma AC */
-    scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
-    /* Finish DC successive approximation */
-    scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
-    /* Finish AC successive approximation */
-    scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
-    scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
-    /* Luma bottom bit comes last since it's usually largest scan */
-    scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
-  } else {
-    /* All-purpose script for other color spaces. */
-    /* Successive approximation first pass */
-    scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
-    scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
-    scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
-    /* Successive approximation second pass */
-    scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
-    /* Successive approximation final pass */
-    scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
-    scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
-  }
-}
-
-#endif /* C_PROGRESSIVE_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcphuff.c ./Shared/jpeg-6b/jcphuff.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcphuff.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jcphuff.c	Wed Dec 31 19:00:00 1969
@@ -1,833 +0,0 @@
-/*
- * jcphuff.c
- *
- * Copyright (C) 1995-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains Huffman entropy encoding routines for progressive JPEG.
- *
- * We do not support output suspension in this module, since the library
- * currently does not allow multiple-scan files to be written with output
- * suspension.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jchuff.h"		/* Declarations shared with jchuff.c */
-
-#ifdef C_PROGRESSIVE_SUPPORTED
-
-/* Expanded entropy encoder object for progressive Huffman encoding. */
-
-typedef struct {
-  struct jpeg_entropy_encoder pub; /* public fields */
-
-  /* Mode flag: TRUE for optimization, FALSE for actual data output */
-  boolean gather_statistics;
-
-  /* Bit-level coding status.
-   * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
-   */
-  JOCTET * next_output_byte;	/* => next byte to write in buffer */
-  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
-  INT32 put_buffer;		/* current bit-accumulation buffer */
-  int put_bits;			/* # of bits now in it */
-  j_compress_ptr cinfo;		/* link to cinfo (needed for dump_buffer) */
-
-  /* Coding status for DC components */
-  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
-
-  /* Coding status for AC components */
-  int ac_tbl_no;		/* the table number of the single component */
-  unsigned int EOBRUN;		/* run length of EOBs */
-  unsigned int BE;		/* # of buffered correction bits before MCU */
-  char * bit_buffer;		/* buffer for correction bits (1 per char) */
-  /* packing correction bits tightly would save some space but cost time... */
-
-  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
-  int next_restart_num;		/* next restart number to write (0-7) */
-
-  /* Pointers to derived tables (these workspaces have image lifespan).
-   * Since any one scan codes only DC or only AC, we only need one set
-   * of tables, not one for DC and one for AC.
-   */
-  c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
-
-  /* Statistics tables for optimization; again, one set is enough */
-  long * count_ptrs[NUM_HUFF_TBLS];
-} phuff_entropy_encoder;
-
-typedef phuff_entropy_encoder * phuff_entropy_ptr;
-
-/* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
- * buffer can hold.  Larger sizes may slightly improve compression, but
- * 1000 is already well into the realm of overkill.
- * The minimum safe size is 64 bits.
- */
-
-#define MAX_CORR_BITS  1000	/* Max # of correction bits I can buffer */
-
-/* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
- * We assume that int right shift is unsigned if INT32 right shift is,
- * which should be safe.
- */
-
-#ifdef RIGHT_SHIFT_IS_UNSIGNED
-#define ISHIFT_TEMPS	int ishift_temp;
-#define IRIGHT_SHIFT(x,shft)  \
-	((ishift_temp = (x)) < 0 ? \
-	 (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
-	 (ishift_temp >> (shft)))
-#else
-#define ISHIFT_TEMPS
-#define IRIGHT_SHIFT(x,shft)	((x) >> (shft))
-#endif
-
-/* Forward declarations */
-METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
-					    JBLOCKROW *MCU_data));
-METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
-					    JBLOCKROW *MCU_data));
-METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
-					     JBLOCKROW *MCU_data));
-METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
-					     JBLOCKROW *MCU_data));
-METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
-METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
-
-
-/*
- * Initialize for a Huffman-compressed scan using progressive JPEG.
- */
-
-METHODDEF(void)
-start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
-{  
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  boolean is_DC_band;
-  int ci, tbl;
-  jpeg_component_info * compptr;
-
-  entropy->cinfo = cinfo;
-  entropy->gather_statistics = gather_statistics;
-
-  is_DC_band = (cinfo->Ss == 0);
-
-  /* We assume jcmaster.c already validated the scan parameters. */
-
-  /* Select execution routines */
-  if (cinfo->Ah == 0) {
-    if (is_DC_band)
-      entropy->pub.encode_mcu = encode_mcu_DC_first;
-    else
-      entropy->pub.encode_mcu = encode_mcu_AC_first;
-  } else {
-    if (is_DC_band)
-      entropy->pub.encode_mcu = encode_mcu_DC_refine;
-    else {
-      entropy->pub.encode_mcu = encode_mcu_AC_refine;
-      /* AC refinement needs a correction bit buffer */
-      if (entropy->bit_buffer == NULL)
-	entropy->bit_buffer = (char *)
-	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				      MAX_CORR_BITS * SIZEOF(char));
-    }
-  }
-  if (gather_statistics)
-    entropy->pub.finish_pass = finish_pass_gather_phuff;
-  else
-    entropy->pub.finish_pass = finish_pass_phuff;
-
-  /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
-   * for AC coefficients.
-   */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    /* Initialize DC predictions to 0 */
-    entropy->last_dc_val[ci] = 0;
-    /* Get table index */
-    if (is_DC_band) {
-      if (cinfo->Ah != 0)	/* DC refinement needs no table */
-	continue;
-      tbl = compptr->dc_tbl_no;
-    } else {
-      entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
-    }
-    if (gather_statistics) {
-      /* Check for invalid table index */
-      /* (make_c_derived_tbl does this in the other path) */
-      if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
-        ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
-      /* Allocate and zero the statistics tables */
-      /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
-      if (entropy->count_ptrs[tbl] == NULL)
-	entropy->count_ptrs[tbl] = (long *)
-	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				      257 * SIZEOF(long));
-      MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
-    } else {
-      /* Compute derived values for Huffman table */
-      /* We may do this more than once for a table, but it's not expensive */
-      jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
-			      & entropy->derived_tbls[tbl]);
-    }
-  }
-
-  /* Initialize AC stuff */
-  entropy->EOBRUN = 0;
-  entropy->BE = 0;
-
-  /* Initialize bit buffer to empty */
-  entropy->put_buffer = 0;
-  entropy->put_bits = 0;
-
-  /* Initialize restart stuff */
-  entropy->restarts_to_go = cinfo->restart_interval;
-  entropy->next_restart_num = 0;
-}
-
-
-/* Outputting bytes to the file.
- * NB: these must be called only when actually outputting,
- * that is, entropy->gather_statistics == FALSE.
- */
-
-/* Emit a byte */
-#define emit_byte(entropy,val)  \
-	{ *(entropy)->next_output_byte++ = (JOCTET) (val);  \
-	  if (--(entropy)->free_in_buffer == 0)  \
-	    dump_buffer(entropy); }
-
-
-LOCAL(void)
-dump_buffer (phuff_entropy_ptr entropy)
-/* Empty the output buffer; we do not support suspension in this module. */
-{
-  struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
-
-  if (! (*dest->empty_output_buffer) (entropy->cinfo))
-    ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
-  /* After a successful buffer dump, must reset buffer pointers */
-  entropy->next_output_byte = dest->next_output_byte;
-  entropy->free_in_buffer = dest->free_in_buffer;
-}
-
-
-/* Outputting bits to the file */
-
-/* Only the right 24 bits of put_buffer are used; the valid bits are
- * left-justified in this part.  At most 16 bits can be passed to emit_bits
- * in one call, and we never retain more than 7 bits in put_buffer
- * between calls, so 24 bits are sufficient.
- */
-
-INLINE
-LOCAL(void)
-emit_bits (phuff_entropy_ptr entropy, unsigned int code, int size)
-/* Emit some bits, unless we are in gather mode */
-{
-  /* This routine is heavily used, so it's worth coding tightly. */
-  register INT32 put_buffer = (INT32) code;
-  register int put_bits = entropy->put_bits;
-
-  /* if size is 0, caller used an invalid Huffman table entry */
-  if (size == 0)
-    ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
-
-  if (entropy->gather_statistics)
-    return;			/* do nothing if we're only getting stats */
-
-  put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
-  
-  put_bits += size;		/* new number of bits in buffer */
-  
-  put_buffer <<= 24 - put_bits; /* align incoming bits */
-
-  put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
-
-  while (put_bits >= 8) {
-    int c = (int) ((put_buffer >> 16) & 0xFF);
-    
-    emit_byte(entropy, c);
-    if (c == 0xFF) {		/* need to stuff a zero byte? */
-      emit_byte(entropy, 0);
-    }
-    put_buffer <<= 8;
-    put_bits -= 8;
-  }
-
-  entropy->put_buffer = put_buffer; /* update variables */
-  entropy->put_bits = put_bits;
-}
-
-
-LOCAL(void)
-flush_bits (phuff_entropy_ptr entropy)
-{
-  emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */
-  entropy->put_buffer = 0;     /* and reset bit-buffer to empty */
-  entropy->put_bits = 0;
-}
-
-
-/*
- * Emit (or just count) a Huffman symbol.
- */
-
-INLINE
-LOCAL(void)
-emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
-{
-  if (entropy->gather_statistics)
-    entropy->count_ptrs[tbl_no][symbol]++;
-  else {
-    c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
-    emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
-  }
-}
-
-
-/*
- * Emit bits from a correction bit buffer.
- */
-
-LOCAL(void)
-emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
-		    unsigned int nbits)
-{
-  if (entropy->gather_statistics)
-    return;			/* no real work */
-
-  while (nbits > 0) {
-    emit_bits(entropy, (unsigned int) (*bufstart), 1);
-    bufstart++;
-    nbits--;
-  }
-}
-
-
-/*
- * Emit any pending EOBRUN symbol.
- */
-
-LOCAL(void)
-emit_eobrun (phuff_entropy_ptr entropy)
-{
-  register int temp, nbits;
-
-  if (entropy->EOBRUN > 0) {	/* if there is any pending EOBRUN */
-    temp = entropy->EOBRUN;
-    nbits = 0;
-    while ((temp >>= 1))
-      nbits++;
-    /* safety check: shouldn't happen given limited correction-bit buffer */
-    if (nbits > 14)
-      ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
-
-    emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
-    if (nbits)
-      emit_bits(entropy, entropy->EOBRUN, nbits);
-
-    entropy->EOBRUN = 0;
-
-    /* Emit any buffered correction bits */
-    emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
-    entropy->BE = 0;
-  }
-}
-
-
-/*
- * Emit a restart marker & resynchronize predictions.
- */
-
-LOCAL(void)
-emit_restart (phuff_entropy_ptr entropy, int restart_num)
-{
-  int ci;
-
-  emit_eobrun(entropy);
-
-  if (! entropy->gather_statistics) {
-    flush_bits(entropy);
-    emit_byte(entropy, 0xFF);
-    emit_byte(entropy, JPEG_RST0 + restart_num);
-  }
-
-  if (entropy->cinfo->Ss == 0) {
-    /* Re-initialize DC predictions to 0 */
-    for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
-      entropy->last_dc_val[ci] = 0;
-  } else {
-    /* Re-initialize all AC-related fields to 0 */
-    entropy->EOBRUN = 0;
-    entropy->BE = 0;
-  }
-}
-
-
-/*
- * MCU encoding for DC initial scan (either spectral selection,
- * or first pass of successive approximation).
- */
-
-METHODDEF(boolean)
-encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
-{
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  register int temp, temp2;
-  register int nbits;
-  int blkn, ci;
-  int Al = cinfo->Al;
-  JBLOCKROW block;
-  jpeg_component_info * compptr;
-  ISHIFT_TEMPS
-
-  entropy->next_output_byte = cinfo->dest->next_output_byte;
-  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
-
-  /* Emit restart marker if needed */
-  if (cinfo->restart_interval)
-    if (entropy->restarts_to_go == 0)
-      emit_restart(entropy, entropy->next_restart_num);
-
-  /* Encode the MCU data blocks */
-  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-    block = MCU_data[blkn];
-    ci = cinfo->MCU_membership[blkn];
-    compptr = cinfo->cur_comp_info[ci];
-
-    /* Compute the DC value after the required point transform by Al.
-     * This is simply an arithmetic right shift.
-     */
-    temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
-
-    /* DC differences are figured on the point-transformed values. */
-    temp = temp2 - entropy->last_dc_val[ci];
-    entropy->last_dc_val[ci] = temp2;
-
-    /* Encode the DC coefficient difference per section G.1.2.1 */
-    temp2 = temp;
-    if (temp < 0) {
-      temp = -temp;		/* temp is abs value of input */
-      /* For a negative input, want temp2 = bitwise complement of abs(input) */
-      /* This code assumes we are on a two's complement machine */
-      temp2--;
-    }
-    
-    /* Find the number of bits needed for the magnitude of the coefficient */
-    nbits = 0;
-    while (temp) {
-      nbits++;
-      temp >>= 1;
-    }
-    /* Check for out-of-range coefficient values.
-     * Since we're encoding a difference, the range limit is twice as much.
-     */
-    if (nbits > MAX_COEF_BITS+1)
-      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
-    
-    /* Count/emit the Huffman-coded symbol for the number of bits */
-    emit_symbol(entropy, compptr->dc_tbl_no, nbits);
-    
-    /* Emit that number of bits of the value, if positive, */
-    /* or the complement of its magnitude, if negative. */
-    if (nbits)			/* emit_bits rejects calls with size 0 */
-      emit_bits(entropy, (unsigned int) temp2, nbits);
-  }
-
-  cinfo->dest->next_output_byte = entropy->next_output_byte;
-  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
-
-  /* Update restart-interval state too */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0) {
-      entropy->restarts_to_go = cinfo->restart_interval;
-      entropy->next_restart_num++;
-      entropy->next_restart_num &= 7;
-    }
-    entropy->restarts_to_go--;
-  }
-
-  return TRUE;
-}
-
-
-/*
- * MCU encoding for AC initial scan (either spectral selection,
- * or first pass of successive approximation).
- */
-
-METHODDEF(boolean)
-encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
-{
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  register int temp, temp2;
-  register int nbits;
-  register int r, k;
-  int Se = cinfo->Se;
-  int Al = cinfo->Al;
-  JBLOCKROW block;
-
-  entropy->next_output_byte = cinfo->dest->next_output_byte;
-  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
-
-  /* Emit restart marker if needed */
-  if (cinfo->restart_interval)
-    if (entropy->restarts_to_go == 0)
-      emit_restart(entropy, entropy->next_restart_num);
-
-  /* Encode the MCU data block */
-  block = MCU_data[0];
-
-  /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
-  
-  r = 0;			/* r = run length of zeros */
-   
-  for (k = cinfo->Ss; k <= Se; k++) {
-    if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
-      r++;
-      continue;
-    }
-    /* We must apply the point transform by Al.  For AC coefficients this
-     * is an integer division with rounding towards 0.  To do this portably
-     * in C, we shift after obtaining the absolute value; so the code is
-     * interwoven with finding the abs value (temp) and output bits (temp2).
-     */
-    if (temp < 0) {
-      temp = -temp;		/* temp is abs value of input */
-      temp >>= Al;		/* apply the point transform */
-      /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
-      temp2 = ~temp;
-    } else {
-      temp >>= Al;		/* apply the point transform */
-      temp2 = temp;
-    }
-    /* Watch out for case that nonzero coef is zero after point transform */
-    if (temp == 0) {
-      r++;
-      continue;
-    }
-
-    /* Emit any pending EOBRUN */
-    if (entropy->EOBRUN > 0)
-      emit_eobrun(entropy);
-    /* if run length > 15, must emit special run-length-16 codes (0xF0) */
-    while (r > 15) {
-      emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
-      r -= 16;
-    }
-
-    /* Find the number of bits needed for the magnitude of the coefficient */
-    nbits = 1;			/* there must be at least one 1 bit */
-    while ((temp >>= 1))
-      nbits++;
-    /* Check for out-of-range coefficient values */
-    if (nbits > MAX_COEF_BITS)
-      ERREXIT(cinfo, JERR_BAD_DCT_COEF);
-
-    /* Count/emit Huffman symbol for run length / number of bits */
-    emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
-
-    /* Emit that number of bits of the value, if positive, */
-    /* or the complement of its magnitude, if negative. */
-    emit_bits(entropy, (unsigned int) temp2, nbits);
-
-    r = 0;			/* reset zero run length */
-  }
-
-  if (r > 0) {			/* If there are trailing zeroes, */
-    entropy->EOBRUN++;		/* count an EOB */
-    if (entropy->EOBRUN == 0x7FFF)
-      emit_eobrun(entropy);	/* force it out to avoid overflow */
-  }
-
-  cinfo->dest->next_output_byte = entropy->next_output_byte;
-  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
-
-  /* Update restart-interval state too */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0) {
-      entropy->restarts_to_go = cinfo->restart_interval;
-      entropy->next_restart_num++;
-      entropy->next_restart_num &= 7;
-    }
-    entropy->restarts_to_go--;
-  }
-
-  return TRUE;
-}
-
-
-/*
- * MCU encoding for DC successive approximation refinement scan.
- * Note: we assume such scans can be multi-component, although the spec
- * is not very clear on the point.
- */
-
-METHODDEF(boolean)
-encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
-{
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  register int temp;
-  int blkn;
-  int Al = cinfo->Al;
-  JBLOCKROW block;
-
-  entropy->next_output_byte = cinfo->dest->next_output_byte;
-  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
-
-  /* Emit restart marker if needed */
-  if (cinfo->restart_interval)
-    if (entropy->restarts_to_go == 0)
-      emit_restart(entropy, entropy->next_restart_num);
-
-  /* Encode the MCU data blocks */
-  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-    block = MCU_data[blkn];
-
-    /* We simply emit the Al'th bit of the DC coefficient value. */
-    temp = (*block)[0];
-    emit_bits(entropy, (unsigned int) (temp >> Al), 1);
-  }
-
-  cinfo->dest->next_output_byte = entropy->next_output_byte;
-  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
-
-  /* Update restart-interval state too */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0) {
-      entropy->restarts_to_go = cinfo->restart_interval;
-      entropy->next_restart_num++;
-      entropy->next_restart_num &= 7;
-    }
-    entropy->restarts_to_go--;
-  }
-
-  return TRUE;
-}
-
-
-/*
- * MCU encoding for AC successive approximation refinement scan.
- */
-
-METHODDEF(boolean)
-encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
-{
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  register int temp;
-  register int r, k;
-  int EOB;
-  char *BR_buffer;
-  unsigned int BR;
-  int Se = cinfo->Se;
-  int Al = cinfo->Al;
-  JBLOCKROW block;
-  int absvalues[DCTSIZE2];
-
-  entropy->next_output_byte = cinfo->dest->next_output_byte;
-  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
-
-  /* Emit restart marker if needed */
-  if (cinfo->restart_interval)
-    if (entropy->restarts_to_go == 0)
-      emit_restart(entropy, entropy->next_restart_num);
-
-  /* Encode the MCU data block */
-  block = MCU_data[0];
-
-  /* It is convenient to make a pre-pass to determine the transformed
-   * coefficients' absolute values and the EOB position.
-   */
-  EOB = 0;
-  for (k = cinfo->Ss; k <= Se; k++) {
-    temp = (*block)[jpeg_natural_order[k]];
-    /* We must apply the point transform by Al.  For AC coefficients this
-     * is an integer division with rounding towards 0.  To do this portably
-     * in C, we shift after obtaining the absolute value.
-     */
-    if (temp < 0)
-      temp = -temp;		/* temp is abs value of input */
-    temp >>= Al;		/* apply the point transform */
-    absvalues[k] = temp;	/* save abs value for main pass */
-    if (temp == 1)
-      EOB = k;			/* EOB = index of last newly-nonzero coef */
-  }
-
-  /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
-  
-  r = 0;			/* r = run length of zeros */
-  BR = 0;			/* BR = count of buffered bits added now */
-  BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
-
-  for (k = cinfo->Ss; k <= Se; k++) {
-    if ((temp = absvalues[k]) == 0) {
-      r++;
-      continue;
-    }
-
-    /* Emit any required ZRLs, but not if they can be folded into EOB */
-    while (r > 15 && k <= EOB) {
-      /* emit any pending EOBRUN and the BE correction bits */
-      emit_eobrun(entropy);
-      /* Emit ZRL */
-      emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
-      r -= 16;
-      /* Emit buffered correction bits that must be associated with ZRL */
-      emit_buffered_bits(entropy, BR_buffer, BR);
-      BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
-      BR = 0;
-    }
-
-    /* If the coef was previously nonzero, it only needs a correction bit.
-     * NOTE: a straight translation of the spec's figure G.7 would suggest
-     * that we also need to test r > 15.  But if r > 15, we can only get here
-     * if k > EOB, which implies that this coefficient is not 1.
-     */
-    if (temp > 1) {
-      /* The correction bit is the next bit of the absolute value. */
-      BR_buffer[BR++] = (char) (temp & 1);
-      continue;
-    }
-
-    /* Emit any pending EOBRUN and the BE correction bits */
-    emit_eobrun(entropy);
-
-    /* Count/emit Huffman symbol for run length / number of bits */
-    emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
-
-    /* Emit output bit for newly-nonzero coef */
-    temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
-    emit_bits(entropy, (unsigned int) temp, 1);
-
-    /* Emit buffered correction bits that must be associated with this code */
-    emit_buffered_bits(entropy, BR_buffer, BR);
-    BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
-    BR = 0;
-    r = 0;			/* reset zero run length */
-  }
-
-  if (r > 0 || BR > 0) {	/* If there are trailing zeroes, */
-    entropy->EOBRUN++;		/* count an EOB */
-    entropy->BE += BR;		/* concat my correction bits to older ones */
-    /* We force out the EOB if we risk either:
-     * 1. overflow of the EOB counter;
-     * 2. overflow of the correction bit buffer during the next MCU.
-     */
-    if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
-      emit_eobrun(entropy);
-  }
-
-  cinfo->dest->next_output_byte = entropy->next_output_byte;
-  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
-
-  /* Update restart-interval state too */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0) {
-      entropy->restarts_to_go = cinfo->restart_interval;
-      entropy->next_restart_num++;
-      entropy->next_restart_num &= 7;
-    }
-    entropy->restarts_to_go--;
-  }
-
-  return TRUE;
-}
-
-
-/*
- * Finish up at the end of a Huffman-compressed progressive scan.
- */
-
-METHODDEF(void)
-finish_pass_phuff (j_compress_ptr cinfo)
-{   
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-
-  entropy->next_output_byte = cinfo->dest->next_output_byte;
-  entropy->free_in_buffer = cinfo->dest->free_in_buffer;
-
-  /* Flush out any buffered data */
-  emit_eobrun(entropy);
-  flush_bits(entropy);
-
-  cinfo->dest->next_output_byte = entropy->next_output_byte;
-  cinfo->dest->free_in_buffer = entropy->free_in_buffer;
-}
-
-
-/*
- * Finish up a statistics-gathering pass and create the new Huffman tables.
- */
-
-METHODDEF(void)
-finish_pass_gather_phuff (j_compress_ptr cinfo)
-{
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  boolean is_DC_band;
-  int ci, tbl;
-  jpeg_component_info * compptr;
-  JHUFF_TBL **htblptr;
-  boolean did[NUM_HUFF_TBLS];
-
-  /* Flush out buffered data (all we care about is counting the EOB symbol) */
-  emit_eobrun(entropy);
-
-  is_DC_band = (cinfo->Ss == 0);
-
-  /* It's important not to apply jpeg_gen_optimal_table more than once
-   * per table, because it clobbers the input frequency counts!
-   */
-  MEMZERO(did, SIZEOF(did));
-
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    if (is_DC_band) {
-      if (cinfo->Ah != 0)	/* DC refinement needs no table */
-	continue;
-      tbl = compptr->dc_tbl_no;
-    } else {
-      tbl = compptr->ac_tbl_no;
-    }
-    if (! did[tbl]) {
-      if (is_DC_band)
-        htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
-      else
-        htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
-      if (*htblptr == NULL)
-        *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
-      jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
-      did[tbl] = TRUE;
-    }
-  }
-}
-
-
-/*
- * Module initialization routine for progressive Huffman entropy encoding.
- */
-
-GLOBAL(void)
-jinit_phuff_encoder (j_compress_ptr cinfo)
-{
-  phuff_entropy_ptr entropy;
-  int i;
-
-  entropy = (phuff_entropy_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(phuff_entropy_encoder));
-  cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
-  entropy->pub.start_pass = start_pass_phuff;
-
-  /* Mark tables unallocated */
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    entropy->derived_tbls[i] = NULL;
-    entropy->count_ptrs[i] = NULL;
-  }
-  entropy->bit_buffer = NULL;	/* needed only in AC refinement scan */
-}
-
-#endif /* C_PROGRESSIVE_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcprepct.c ./Shared/jpeg-6b/jcprepct.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcprepct.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jcprepct.c	Wed Dec 31 19:00:00 1969
@@ -1,354 +0,0 @@
-/*
- * jcprepct.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the compression preprocessing controller.
- * This controller manages the color conversion, downsampling,
- * and edge expansion steps.
- *
- * Most of the complexity here is associated with buffering input rows
- * as required by the downsampler.  See the comments at the head of
- * jcsample.c for the downsampler's needs.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* At present, jcsample.c can request context rows only for smoothing.
- * In the future, we might also need context rows for CCIR601 sampling
- * or other more-complex downsampling procedures.  The code to support
- * context rows should be compiled only if needed.
- */
-#ifdef INPUT_SMOOTHING_SUPPORTED
-#define CONTEXT_ROWS_SUPPORTED
-#endif
-
-
-/*
- * For the simple (no-context-row) case, we just need to buffer one
- * row group's worth of pixels for the downsampling step.  At the bottom of
- * the image, we pad to a full row group by replicating the last pixel row.
- * The downsampler's last output row is then replicated if needed to pad
- * out to a full iMCU row.
- *
- * When providing context rows, we must buffer three row groups' worth of
- * pixels.  Three row groups are physically allocated, but the row pointer
- * arrays are made five row groups high, with the extra pointers above and
- * below "wrapping around" to point to the last and first real row groups.
- * This allows the downsampler to access the proper context rows.
- * At the top and bottom of the image, we create dummy context rows by
- * copying the first or last real pixel row.  This copying could be avoided
- * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
- * trouble on the compression side.
- */
-
-
-/* Private buffer controller object */
-
-typedef struct {
-  struct jpeg_c_prep_controller pub; /* public fields */
-
-  /* Downsampling input buffer.  This buffer holds color-converted data
-   * until we have enough to do a downsample step.
-   */
-  JSAMPARRAY color_buf[MAX_COMPONENTS];
-
-  JDIMENSION rows_to_go;	/* counts rows remaining in source image */
-  int next_buf_row;		/* index of next row to store in color_buf */
-
-#ifdef CONTEXT_ROWS_SUPPORTED	/* only needed for context case */
-  int this_row_group;		/* starting row index of group to process */
-  int next_buf_stop;		/* downsample when we reach this index */
-#endif
-} my_prep_controller;
-
-typedef my_prep_controller * my_prep_ptr;
-
-
-/*
- * Initialize for a processing pass.
- */
-
-METHODDEF(void)
-start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
-{
-  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
-
-  if (pass_mode != JBUF_PASS_THRU)
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-
-  /* Initialize total-height counter for detecting bottom of image */
-  prep->rows_to_go = cinfo->image_height;
-  /* Mark the conversion buffer empty */
-  prep->next_buf_row = 0;
-#ifdef CONTEXT_ROWS_SUPPORTED
-  /* Preset additional state variables for context mode.
-   * These aren't used in non-context mode, so we needn't test which mode.
-   */
-  prep->this_row_group = 0;
-  /* Set next_buf_stop to stop after two row groups have been read in. */
-  prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
-#endif
-}
-
-
-/*
- * Expand an image vertically from height input_rows to height output_rows,
- * by duplicating the bottom row.
- */
-
-LOCAL(void)
-expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
-		    int input_rows, int output_rows)
-{
-  register int row;
-
-  for (row = input_rows; row < output_rows; row++) {
-    jcopy_sample_rows(image_data, input_rows-1, image_data, row,
-		      1, num_cols);
-  }
-}
-
-
-/*
- * Process some data in the simple no-context case.
- *
- * Preprocessor output data is counted in "row groups".  A row group
- * is defined to be v_samp_factor sample rows of each component.
- * Downsampling will produce this much data from each max_v_samp_factor
- * input rows.
- */
-
-METHODDEF(void)
-pre_process_data (j_compress_ptr cinfo,
-		  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
-		  JDIMENSION in_rows_avail,
-		  JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
-		  JDIMENSION out_row_groups_avail)
-{
-  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
-  int numrows, ci;
-  JDIMENSION inrows;
-  jpeg_component_info * compptr;
-
-  while (*in_row_ctr < in_rows_avail &&
-	 *out_row_group_ctr < out_row_groups_avail) {
-    /* Do color conversion to fill the conversion buffer. */
-    inrows = in_rows_avail - *in_row_ctr;
-    numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
-    numrows = (int) MIN((JDIMENSION) numrows, inrows);
-    (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
-				       prep->color_buf,
-				       (JDIMENSION) prep->next_buf_row,
-				       numrows);
-    *in_row_ctr += numrows;
-    prep->next_buf_row += numrows;
-    prep->rows_to_go -= numrows;
-    /* If at bottom of image, pad to fill the conversion buffer. */
-    if (prep->rows_to_go == 0 &&
-	prep->next_buf_row < cinfo->max_v_samp_factor) {
-      for (ci = 0; ci < cinfo->num_components; ci++) {
-	expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
-			   prep->next_buf_row, cinfo->max_v_samp_factor);
-      }
-      prep->next_buf_row = cinfo->max_v_samp_factor;
-    }
-    /* If we've filled the conversion buffer, empty it. */
-    if (prep->next_buf_row == cinfo->max_v_samp_factor) {
-      (*cinfo->downsample->downsample) (cinfo,
-					prep->color_buf, (JDIMENSION) 0,
-					output_buf, *out_row_group_ctr);
-      prep->next_buf_row = 0;
-      (*out_row_group_ctr)++;
-    }
-    /* If at bottom of image, pad the output to a full iMCU height.
-     * Note we assume the caller is providing a one-iMCU-height output buffer!
-     */
-    if (prep->rows_to_go == 0 &&
-	*out_row_group_ctr < out_row_groups_avail) {
-      for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	   ci++, compptr++) {
-	expand_bottom_edge(output_buf[ci],
-			   compptr->width_in_blocks * DCTSIZE,
-			   (int) (*out_row_group_ctr * compptr->v_samp_factor),
-			   (int) (out_row_groups_avail * compptr->v_samp_factor));
-      }
-      *out_row_group_ctr = out_row_groups_avail;
-      break;			/* can exit outer loop without test */
-    }
-  }
-}
-
-
-#ifdef CONTEXT_ROWS_SUPPORTED
-
-/*
- * Process some data in the context case.
- */
-
-METHODDEF(void)
-pre_process_context (j_compress_ptr cinfo,
-		     JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
-		     JDIMENSION in_rows_avail,
-		     JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
-		     JDIMENSION out_row_groups_avail)
-{
-  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
-  int numrows, ci;
-  int buf_height = cinfo->max_v_samp_factor * 3;
-  JDIMENSION inrows;
-
-  while (*out_row_group_ctr < out_row_groups_avail) {
-    if (*in_row_ctr < in_rows_avail) {
-      /* Do color conversion to fill the conversion buffer. */
-      inrows = in_rows_avail - *in_row_ctr;
-      numrows = prep->next_buf_stop - prep->next_buf_row;
-      numrows = (int) MIN((JDIMENSION) numrows, inrows);
-      (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
-					 prep->color_buf,
-					 (JDIMENSION) prep->next_buf_row,
-					 numrows);
-      /* Pad at top of image, if first time through */
-      if (prep->rows_to_go == cinfo->image_height) {
-	for (ci = 0; ci < cinfo->num_components; ci++) {
-	  int row;
-	  for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
-	    jcopy_sample_rows(prep->color_buf[ci], 0,
-			      prep->color_buf[ci], -row,
-			      1, cinfo->image_width);
-	  }
-	}
-      }
-      *in_row_ctr += numrows;
-      prep->next_buf_row += numrows;
-      prep->rows_to_go -= numrows;
-    } else {
-      /* Return for more data, unless we are at the bottom of the image. */
-      if (prep->rows_to_go != 0)
-	break;
-      /* When at bottom of image, pad to fill the conversion buffer. */
-      if (prep->next_buf_row < prep->next_buf_stop) {
-	for (ci = 0; ci < cinfo->num_components; ci++) {
-	  expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
-			     prep->next_buf_row, prep->next_buf_stop);
-	}
-	prep->next_buf_row = prep->next_buf_stop;
-      }
-    }
-    /* If we've gotten enough data, downsample a row group. */
-    if (prep->next_buf_row == prep->next_buf_stop) {
-      (*cinfo->downsample->downsample) (cinfo,
-					prep->color_buf,
-					(JDIMENSION) prep->this_row_group,
-					output_buf, *out_row_group_ctr);
-      (*out_row_group_ctr)++;
-      /* Advance pointers with wraparound as necessary. */
-      prep->this_row_group += cinfo->max_v_samp_factor;
-      if (prep->this_row_group >= buf_height)
-	prep->this_row_group = 0;
-      if (prep->next_buf_row >= buf_height)
-	prep->next_buf_row = 0;
-      prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
-    }
-  }
-}
-
-
-/*
- * Create the wrapped-around downsampling input buffer needed for context mode.
- */
-
-LOCAL(void)
-create_context_buffer (j_compress_ptr cinfo)
-{
-  my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
-  int rgroup_height = cinfo->max_v_samp_factor;
-  int ci, i;
-  jpeg_component_info * compptr;
-  JSAMPARRAY true_buffer, fake_buffer;
-
-  /* Grab enough space for fake row pointers for all the components;
-   * we need five row groups' worth of pointers for each component.
-   */
-  fake_buffer = (JSAMPARRAY)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(cinfo->num_components * 5 * rgroup_height) *
-				SIZEOF(JSAMPROW));
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Allocate the actual buffer space (3 row groups) for this component.
-     * We make the buffer wide enough to allow the downsampler to edge-expand
-     * horizontally within the buffer, if it so chooses.
-     */
-    true_buffer = (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
-		      cinfo->max_h_samp_factor) / compptr->h_samp_factor),
-       (JDIMENSION) (3 * rgroup_height));
-    /* Copy true buffer row pointers into the middle of the fake row array */
-    MEMCOPY(fake_buffer + rgroup_height, true_buffer,
-	    3 * rgroup_height * SIZEOF(JSAMPROW));
-    /* Fill in the above and below wraparound pointers */
-    for (i = 0; i < rgroup_height; i++) {
-      fake_buffer[i] = true_buffer[2 * rgroup_height + i];
-      fake_buffer[4 * rgroup_height + i] = true_buffer[i];
-    }
-    prep->color_buf[ci] = fake_buffer + rgroup_height;
-    fake_buffer += 5 * rgroup_height; /* point to space for next component */
-  }
-}
-
-#endif /* CONTEXT_ROWS_SUPPORTED */
-
-
-/*
- * Initialize preprocessing controller.
- */
-
-GLOBAL(void)
-jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
-{
-  my_prep_ptr prep;
-  int ci;
-  jpeg_component_info * compptr;
-
-  if (need_full_buffer)		/* safety check */
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-
-  prep = (my_prep_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_prep_controller));
-  cinfo->prep = (struct jpeg_c_prep_controller *) prep;
-  prep->pub.start_pass = start_pass_prep;
-
-  /* Allocate the color conversion buffer.
-   * We make the buffer wide enough to allow the downsampler to edge-expand
-   * horizontally within the buffer, if it so chooses.
-   */
-  if (cinfo->downsample->need_context_rows) {
-    /* Set up to provide context rows */
-#ifdef CONTEXT_ROWS_SUPPORTED
-    prep->pub.pre_process_data = pre_process_context;
-    create_context_buffer(cinfo);
-#else
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-  } else {
-    /* No context, just make it tall enough for one row group */
-    prep->pub.pre_process_data = pre_process_data;
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE,
-	 (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
-			cinfo->max_h_samp_factor) / compptr->h_samp_factor),
-	 (JDIMENSION) cinfo->max_v_samp_factor);
-    }
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jcsample.c ./Shared/jpeg-6b/jcsample.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jcsample.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jcsample.c	Wed Dec 31 19:00:00 1969
@@ -1,519 +0,0 @@
-/*
- * jcsample.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains downsampling routines.
- *
- * Downsampling input data is counted in "row groups".  A row group
- * is defined to be max_v_samp_factor pixel rows of each component,
- * from which the downsampler produces v_samp_factor sample rows.
- * A single row group is processed in each call to the downsampler module.
- *
- * The downsampler is responsible for edge-expansion of its output data
- * to fill an integral number of DCT blocks horizontally.  The source buffer
- * may be modified if it is helpful for this purpose (the source buffer is
- * allocated wide enough to correspond to the desired output width).
- * The caller (the prep controller) is responsible for vertical padding.
- *
- * The downsampler may request "context rows" by setting need_context_rows
- * during startup.  In this case, the input arrays will contain at least
- * one row group's worth of pixels above and below the passed-in data;
- * the caller will create dummy rows at image top and bottom by replicating
- * the first or last real pixel row.
- *
- * An excellent reference for image resampling is
- *   Digital Image Warping, George Wolberg, 1990.
- *   Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
- *
- * The downsampling algorithm used here is a simple average of the source
- * pixels covered by the output pixel.  The hi-falutin sampling literature
- * refers to this as a "box filter".  In general the characteristics of a box
- * filter are not very good, but for the specific cases we normally use (1:1
- * and 2:1 ratios) the box is equivalent to a "triangle filter" which is not
- * nearly so bad.  If you intend to use other sampling ratios, you'd be well
- * advised to improve this code.
- *
- * A simple input-smoothing capability is provided.  This is mainly intended
- * for cleaning up color-dithered GIF input files (if you find it inadequate,
- * we suggest using an external filtering program such as pnmconvol).  When
- * enabled, each input pixel P is replaced by a weighted sum of itself and its
- * eight neighbors.  P's weight is 1-8*SF and each neighbor's weight is SF,
- * where SF = (smoothing_factor / 1024).
- * Currently, smoothing is only supported for 2h2v sampling factors.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Pointer to routine to downsample a single component */
-typedef JMETHOD(void, downsample1_ptr,
-		(j_compress_ptr cinfo, jpeg_component_info * compptr,
-		 JSAMPARRAY input_data, JSAMPARRAY output_data));
-
-/* Private subobject */
-
-typedef struct {
-  struct jpeg_downsampler pub;	/* public fields */
-
-  /* Downsampling method pointers, one per component */
-  downsample1_ptr methods[MAX_COMPONENTS];
-} my_downsampler;
-
-typedef my_downsampler * my_downsample_ptr;
-
-
-/*
- * Initialize for a downsampling pass.
- */
-
-METHODDEF(void)
-start_pass_downsample (j_compress_ptr cinfo)
-{
-  /* no work for now */
-}
-
-
-/*
- * Expand a component horizontally from width input_cols to width output_cols,
- * by duplicating the rightmost samples.
- */
-
-LOCAL(void)
-expand_right_edge (JSAMPARRAY image_data, int num_rows,
-		   JDIMENSION input_cols, JDIMENSION output_cols)
-{
-  register JSAMPROW ptr;
-  register JSAMPLE pixval;
-  register int count;
-  int row;
-  int numcols = (int) (output_cols - input_cols);
-
-  if (numcols > 0) {
-    for (row = 0; row < num_rows; row++) {
-      ptr = image_data[row] + input_cols;
-      pixval = ptr[-1];		/* don't need GETJSAMPLE() here */
-      for (count = numcols; count > 0; count--)
-	*ptr++ = pixval;
-    }
-  }
-}
-
-
-/*
- * Do downsampling for a whole row group (all components).
- *
- * In this version we simply downsample each component independently.
- */
-
-METHODDEF(void)
-sep_downsample (j_compress_ptr cinfo,
-		JSAMPIMAGE input_buf, JDIMENSION in_row_index,
-		JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
-{
-  my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
-  int ci;
-  jpeg_component_info * compptr;
-  JSAMPARRAY in_ptr, out_ptr;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    in_ptr = input_buf[ci] + in_row_index;
-    out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
-    (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
-  }
-}
-
-
-/*
- * Downsample pixel values of a single component.
- * One row group is processed per call.
- * This version handles arbitrary integral sampling ratios, without smoothing.
- * Note that this version is not actually used for customary sampling ratios.
- */
-
-METHODDEF(void)
-int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
-		JSAMPARRAY input_data, JSAMPARRAY output_data)
-{
-  int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
-  JDIMENSION outcol, outcol_h;	/* outcol_h == outcol*h_expand */
-  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
-  JSAMPROW inptr, outptr;
-  INT32 outvalue;
-
-  h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
-  v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
-  numpix = h_expand * v_expand;
-  numpix2 = numpix/2;
-
-  /* Expand input data enough to let all the output samples be generated
-   * by the standard loop.  Special-casing padded output would be more
-   * efficient.
-   */
-  expand_right_edge(input_data, cinfo->max_v_samp_factor,
-		    cinfo->image_width, output_cols * h_expand);
-
-  inrow = 0;
-  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
-    outptr = output_data[outrow];
-    for (outcol = 0, outcol_h = 0; outcol < output_cols;
-	 outcol++, outcol_h += h_expand) {
-      outvalue = 0;
-      for (v = 0; v < v_expand; v++) {
-	inptr = input_data[inrow+v] + outcol_h;
-	for (h = 0; h < h_expand; h++) {
-	  outvalue += (INT32) GETJSAMPLE(*inptr++);
-	}
-      }
-      *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
-    }
-    inrow += v_expand;
-  }
-}
-
-
-/*
- * Downsample pixel values of a single component.
- * This version handles the special case of a full-size component,
- * without smoothing.
- */
-
-METHODDEF(void)
-fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
-		     JSAMPARRAY input_data, JSAMPARRAY output_data)
-{
-  /* Copy the data */
-  jcopy_sample_rows(input_data, 0, output_data, 0,
-		    cinfo->max_v_samp_factor, cinfo->image_width);
-  /* Edge-expand */
-  expand_right_edge(output_data, cinfo->max_v_samp_factor,
-		    cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
-}
-
-
-/*
- * Downsample pixel values of a single component.
- * This version handles the common case of 2:1 horizontal and 1:1 vertical,
- * without smoothing.
- *
- * A note about the "bias" calculations: when rounding fractional values to
- * integer, we do not want to always round 0.5 up to the next integer.
- * If we did that, we'd introduce a noticeable bias towards larger values.
- * Instead, this code is arranged so that 0.5 will be rounded up or down at
- * alternate pixel locations (a simple ordered dither pattern).
- */
-
-METHODDEF(void)
-h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
-		 JSAMPARRAY input_data, JSAMPARRAY output_data)
-{
-  int outrow;
-  JDIMENSION outcol;
-  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
-  register JSAMPROW inptr, outptr;
-  register int bias;
-
-  /* Expand input data enough to let all the output samples be generated
-   * by the standard loop.  Special-casing padded output would be more
-   * efficient.
-   */
-  expand_right_edge(input_data, cinfo->max_v_samp_factor,
-		    cinfo->image_width, output_cols * 2);
-
-  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
-    outptr = output_data[outrow];
-    inptr = input_data[outrow];
-    bias = 0;			/* bias = 0,1,0,1,... for successive samples */
-    for (outcol = 0; outcol < output_cols; outcol++) {
-      *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
-			      + bias) >> 1);
-      bias ^= 1;		/* 0=>1, 1=>0 */
-      inptr += 2;
-    }
-  }
-}
-
-
-/*
- * Downsample pixel values of a single component.
- * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
- * without smoothing.
- */
-
-METHODDEF(void)
-h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
-		 JSAMPARRAY input_data, JSAMPARRAY output_data)
-{
-  int inrow, outrow;
-  JDIMENSION outcol;
-  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
-  register JSAMPROW inptr0, inptr1, outptr;
-  register int bias;
-
-  /* Expand input data enough to let all the output samples be generated
-   * by the standard loop.  Special-casing padded output would be more
-   * efficient.
-   */
-  expand_right_edge(input_data, cinfo->max_v_samp_factor,
-		    cinfo->image_width, output_cols * 2);
-
-  inrow = 0;
-  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
-    outptr = output_data[outrow];
-    inptr0 = input_data[inrow];
-    inptr1 = input_data[inrow+1];
-    bias = 1;			/* bias = 1,2,1,2,... for successive samples */
-    for (outcol = 0; outcol < output_cols; outcol++) {
-      *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
-			      GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
-			      + bias) >> 2);
-      bias ^= 3;		/* 1=>2, 2=>1 */
-      inptr0 += 2; inptr1 += 2;
-    }
-    inrow += 2;
-  }
-}
-
-
-#ifdef INPUT_SMOOTHING_SUPPORTED
-
-/*
- * Downsample pixel values of a single component.
- * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
- * with smoothing.  One row of context is required.
- */
-
-METHODDEF(void)
-h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
-			JSAMPARRAY input_data, JSAMPARRAY output_data)
-{
-  int inrow, outrow;
-  JDIMENSION colctr;
-  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
-  register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
-  INT32 membersum, neighsum, memberscale, neighscale;
-
-  /* Expand input data enough to let all the output samples be generated
-   * by the standard loop.  Special-casing padded output would be more
-   * efficient.
-   */
-  expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
-		    cinfo->image_width, output_cols * 2);
-
-  /* We don't bother to form the individual "smoothed" input pixel values;
-   * we can directly compute the output which is the average of the four
-   * smoothed values.  Each of the four member pixels contributes a fraction
-   * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
-   * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
-   * output.  The four corner-adjacent neighbor pixels contribute a fraction
-   * SF to just one smoothed pixel, or SF/4 to the final output; while the
-   * eight edge-adjacent neighbors contribute SF to each of two smoothed
-   * pixels, or SF/2 overall.  In order to use integer arithmetic, these
-   * factors are scaled by 2^16 = 65536.
-   * Also recall that SF = smoothing_factor / 1024.
-   */
-
-  memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
-  neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
-
-  inrow = 0;
-  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
-    outptr = output_data[outrow];
-    inptr0 = input_data[inrow];
-    inptr1 = input_data[inrow+1];
-    above_ptr = input_data[inrow-1];
-    below_ptr = input_data[inrow+2];
-
-    /* Special case for first column: pretend column -1 is same as column 0 */
-    membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
-		GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
-    neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
-	       GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
-	       GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
-	       GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
-    neighsum += neighsum;
-    neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
-		GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
-    membersum = membersum * memberscale + neighsum * neighscale;
-    *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
-    inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
-
-    for (colctr = output_cols - 2; colctr > 0; colctr--) {
-      /* sum of pixels directly mapped to this output element */
-      membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
-		  GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
-      /* sum of edge-neighbor pixels */
-      neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
-		 GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
-		 GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
-		 GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
-      /* The edge-neighbors count twice as much as corner-neighbors */
-      neighsum += neighsum;
-      /* Add in the corner-neighbors */
-      neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
-		  GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
-      /* form final output scaled up by 2^16 */
-      membersum = membersum * memberscale + neighsum * neighscale;
-      /* round, descale and output it */
-      *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
-      inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
-    }
-
-    /* Special case for last column */
-    membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
-		GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
-    neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
-	       GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
-	       GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
-	       GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
-    neighsum += neighsum;
-    neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
-		GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
-    membersum = membersum * memberscale + neighsum * neighscale;
-    *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
-
-    inrow += 2;
-  }
-}
-
-
-/*
- * Downsample pixel values of a single component.
- * This version handles the special case of a full-size component,
- * with smoothing.  One row of context is required.
- */
-
-METHODDEF(void)
-fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
-			    JSAMPARRAY input_data, JSAMPARRAY output_data)
-{
-  int outrow;
-  JDIMENSION colctr;
-  JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
-  register JSAMPROW inptr, above_ptr, below_ptr, outptr;
-  INT32 membersum, neighsum, memberscale, neighscale;
-  int colsum, lastcolsum, nextcolsum;
-
-  /* Expand input data enough to let all the output samples be generated
-   * by the standard loop.  Special-casing padded output would be more
-   * efficient.
-   */
-  expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
-		    cinfo->image_width, output_cols);
-
-  /* Each of the eight neighbor pixels contributes a fraction SF to the
-   * smoothed pixel, while the main pixel contributes (1-8*SF).  In order
-   * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
-   * Also recall that SF = smoothing_factor / 1024.
-   */
-
-  memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
-  neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
-
-  for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
-    outptr = output_data[outrow];
-    inptr = input_data[outrow];
-    above_ptr = input_data[outrow-1];
-    below_ptr = input_data[outrow+1];
-
-    /* Special case for first column */
-    colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
-	     GETJSAMPLE(*inptr);
-    membersum = GETJSAMPLE(*inptr++);
-    nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
-		 GETJSAMPLE(*inptr);
-    neighsum = colsum + (colsum - membersum) + nextcolsum;
-    membersum = membersum * memberscale + neighsum * neighscale;
-    *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
-    lastcolsum = colsum; colsum = nextcolsum;
-
-    for (colctr = output_cols - 2; colctr > 0; colctr--) {
-      membersum = GETJSAMPLE(*inptr++);
-      above_ptr++; below_ptr++;
-      nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
-		   GETJSAMPLE(*inptr);
-      neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
-      membersum = membersum * memberscale + neighsum * neighscale;
-      *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
-      lastcolsum = colsum; colsum = nextcolsum;
-    }
-
-    /* Special case for last column */
-    membersum = GETJSAMPLE(*inptr);
-    neighsum = lastcolsum + (colsum - membersum) + colsum;
-    membersum = membersum * memberscale + neighsum * neighscale;
-    *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
-
-  }
-}
-
-#endif /* INPUT_SMOOTHING_SUPPORTED */
-
-
-/*
- * Module initialization routine for downsampling.
- * Note that we must select a routine for each component.
- */
-
-GLOBAL(void)
-jinit_downsampler (j_compress_ptr cinfo)
-{
-  my_downsample_ptr downsample;
-  int ci;
-  jpeg_component_info * compptr;
-  boolean smoothok = TRUE;
-
-  downsample = (my_downsample_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_downsampler));
-  cinfo->downsample = (struct jpeg_downsampler *) downsample;
-  downsample->pub.start_pass = start_pass_downsample;
-  downsample->pub.downsample = sep_downsample;
-  downsample->pub.need_context_rows = FALSE;
-
-  if (cinfo->CCIR601_sampling)
-    ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
-
-  /* Verify we can handle the sampling factors, and set up method pointers */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
-	compptr->v_samp_factor == cinfo->max_v_samp_factor) {
-#ifdef INPUT_SMOOTHING_SUPPORTED
-      if (cinfo->smoothing_factor) {
-	downsample->methods[ci] = fullsize_smooth_downsample;
-	downsample->pub.need_context_rows = TRUE;
-      } else
-#endif
-	downsample->methods[ci] = fullsize_downsample;
-    } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
-	       compptr->v_samp_factor == cinfo->max_v_samp_factor) {
-      smoothok = FALSE;
-      downsample->methods[ci] = h2v1_downsample;
-    } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
-	       compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
-#ifdef INPUT_SMOOTHING_SUPPORTED
-      if (cinfo->smoothing_factor) {
-	downsample->methods[ci] = h2v2_smooth_downsample;
-	downsample->pub.need_context_rows = TRUE;
-      } else
-#endif
-	downsample->methods[ci] = h2v2_downsample;
-    } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
-	       (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
-      smoothok = FALSE;
-      downsample->methods[ci] = int_downsample;
-    } else
-      ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
-  }
-
-#ifdef INPUT_SMOOTHING_SUPPORTED
-  if (cinfo->smoothing_factor && !smoothok)
-    TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
-#endif
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jctrans.c ./Shared/jpeg-6b/jctrans.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jctrans.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jctrans.c	Wed Dec 31 19:00:00 1969
@@ -1,388 +0,0 @@
-/*
- * jctrans.c
- *
- * Copyright (C) 1995-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains library routines for transcoding compression,
- * that is, writing raw DCT coefficient arrays to an output JPEG file.
- * The routines in jcapimin.c will also be needed by a transcoder.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Forward declarations */
-LOCAL(void) transencode_master_selection
-	JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
-LOCAL(void) transencode_coef_controller
-	JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
-
-
-/*
- * Compression initialization for writing raw-coefficient data.
- * Before calling this, all parameters and a data destination must be set up.
- * Call jpeg_finish_compress() to actually write the data.
- *
- * The number of passed virtual arrays must match cinfo->num_components.
- * Note that the virtual arrays need not be filled or even realized at
- * the time write_coefficients is called; indeed, if the virtual arrays
- * were requested from this compression object's memory manager, they
- * typically will be realized during this routine and filled afterwards.
- */
-
-GLOBAL(void)
-jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
-{
-  if (cinfo->global_state != CSTATE_START)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  /* Mark all tables to be written */
-  jpeg_suppress_tables(cinfo, FALSE);
-  /* (Re)initialize error mgr and destination modules */
-  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
-  (*cinfo->dest->init_destination) (cinfo);
-  /* Perform master selection of active modules */
-  transencode_master_selection(cinfo, coef_arrays);
-  /* Wait for jpeg_finish_compress() call */
-  cinfo->next_scanline = 0;	/* so jpeg_write_marker works */
-  cinfo->global_state = CSTATE_WRCOEFS;
-}
-
-
-/*
- * Initialize the compression object with default parameters,
- * then copy from the source object all parameters needed for lossless
- * transcoding.  Parameters that can be varied without loss (such as
- * scan script and Huffman optimization) are left in their default states.
- */
-
-GLOBAL(void)
-jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
-			       j_compress_ptr dstinfo)
-{
-  JQUANT_TBL ** qtblptr;
-  jpeg_component_info *incomp, *outcomp;
-  JQUANT_TBL *c_quant, *slot_quant;
-  int tblno, ci, coefi;
-
-  /* Safety check to ensure start_compress not called yet. */
-  if (dstinfo->global_state != CSTATE_START)
-    ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
-  /* Copy fundamental image dimensions */
-  dstinfo->image_width = srcinfo->image_width;
-  dstinfo->image_height = srcinfo->image_height;
-  dstinfo->input_components = srcinfo->num_components;
-  dstinfo->in_color_space = srcinfo->jpeg_color_space;
-  /* Initialize all parameters to default values */
-  jpeg_set_defaults(dstinfo);
-  /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
-   * Fix it to get the right header markers for the image colorspace.
-   */
-  jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
-  dstinfo->data_precision = srcinfo->data_precision;
-  dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
-  /* Copy the source's quantization tables. */
-  for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
-    if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
-      qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
-      if (*qtblptr == NULL)
-	*qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
-      MEMCOPY((*qtblptr)->quantval,
-	      srcinfo->quant_tbl_ptrs[tblno]->quantval,
-	      SIZEOF((*qtblptr)->quantval));
-      (*qtblptr)->sent_table = FALSE;
-    }
-  }
-  /* Copy the source's per-component info.
-   * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
-   */
-  dstinfo->num_components = srcinfo->num_components;
-  if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
-    ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
-	     MAX_COMPONENTS);
-  for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
-       ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
-    outcomp->component_id = incomp->component_id;
-    outcomp->h_samp_factor = incomp->h_samp_factor;
-    outcomp->v_samp_factor = incomp->v_samp_factor;
-    outcomp->quant_tbl_no = incomp->quant_tbl_no;
-    /* Make sure saved quantization table for component matches the qtable
-     * slot.  If not, the input file re-used this qtable slot.
-     * IJG encoder currently cannot duplicate this.
-     */
-    tblno = outcomp->quant_tbl_no;
-    if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
-	srcinfo->quant_tbl_ptrs[tblno] == NULL)
-      ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
-    slot_quant = srcinfo->quant_tbl_ptrs[tblno];
-    c_quant = incomp->quant_table;
-    if (c_quant != NULL) {
-      for (coefi = 0; coefi < DCTSIZE2; coefi++) {
-	if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
-	  ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
-      }
-    }
-    /* Note: we do not copy the source's Huffman table assignments;
-     * instead we rely on jpeg_set_colorspace to have made a suitable choice.
-     */
-  }
-  /* Also copy JFIF version and resolution information, if available.
-   * Strictly speaking this isn't "critical" info, but it's nearly
-   * always appropriate to copy it if available.  In particular,
-   * if the application chooses to copy JFIF 1.02 extension markers from
-   * the source file, we need to copy the version to make sure we don't
-   * emit a file that has 1.02 extensions but a claimed version of 1.01.
-   * We will *not*, however, copy version info from mislabeled "2.01" files.
-   */
-  if (srcinfo->saw_JFIF_marker) {
-    if (srcinfo->JFIF_major_version == 1) {
-      dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
-      dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
-    }
-    dstinfo->density_unit = srcinfo->density_unit;
-    dstinfo->X_density = srcinfo->X_density;
-    dstinfo->Y_density = srcinfo->Y_density;
-  }
-}
-
-
-/*
- * Master selection of compression modules for transcoding.
- * This substitutes for jcinit.c's initialization of the full compressor.
- */
-
-LOCAL(void)
-transencode_master_selection (j_compress_ptr cinfo,
-			      jvirt_barray_ptr * coef_arrays)
-{
-  /* Although we don't actually use input_components for transcoding,
-   * jcmaster.c's initial_setup will complain if input_components is 0.
-   */
-  cinfo->input_components = 1;
-  /* Initialize master control (includes parameter checking/processing) */
-  jinit_c_master_control(cinfo, TRUE /* transcode only */);
-
-  /* Entropy encoding: either Huffman or arithmetic coding. */
-  if (cinfo->arith_code) {
-    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
-  } else {
-    if (cinfo->progressive_mode) {
-#ifdef C_PROGRESSIVE_SUPPORTED
-      jinit_phuff_encoder(cinfo);
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-    } else
-      jinit_huff_encoder(cinfo);
-  }
-
-  /* We need a special coefficient buffer controller. */
-  transencode_coef_controller(cinfo, coef_arrays);
-
-  jinit_marker_writer(cinfo);
-
-  /* We can now tell the memory manager to allocate virtual arrays. */
-  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
-
-  /* Write the datastream header (SOI, JFIF) immediately.
-   * Frame and scan headers are postponed till later.
-   * This lets application insert special markers after the SOI.
-   */
-  (*cinfo->marker->write_file_header) (cinfo);
-}
-
-
-/*
- * The rest of this file is a special implementation of the coefficient
- * buffer controller.  This is similar to jccoefct.c, but it handles only
- * output from presupplied virtual arrays.  Furthermore, we generate any
- * dummy padding blocks on-the-fly rather than expecting them to be present
- * in the arrays.
- */
-
-/* Private buffer controller object */
-
-typedef struct {
-  struct jpeg_c_coef_controller pub; /* public fields */
-
-  JDIMENSION iMCU_row_num;	/* iMCU row # within image */
-  JDIMENSION mcu_ctr;		/* counts MCUs processed in current row */
-  int MCU_vert_offset;		/* counts MCU rows within iMCU row */
-  int MCU_rows_per_iMCU_row;	/* number of such rows needed */
-
-  /* Virtual block array for each component. */
-  jvirt_barray_ptr * whole_image;
-
-  /* Workspace for constructing dummy blocks at right/bottom edges. */
-  JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
-} my_coef_controller;
-
-typedef my_coef_controller * my_coef_ptr;
-
-
-LOCAL(void)
-start_iMCU_row (j_compress_ptr cinfo)
-/* Reset within-iMCU-row counters for a new row */
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-
-  /* In an interleaved scan, an MCU row is the same as an iMCU row.
-   * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
-   * But at the bottom of the image, process only what's left.
-   */
-  if (cinfo->comps_in_scan > 1) {
-    coef->MCU_rows_per_iMCU_row = 1;
-  } else {
-    if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
-      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
-    else
-      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
-  }
-
-  coef->mcu_ctr = 0;
-  coef->MCU_vert_offset = 0;
-}
-
-
-/*
- * Initialize for a processing pass.
- */
-
-METHODDEF(void)
-start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-
-  if (pass_mode != JBUF_CRANK_DEST)
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-
-  coef->iMCU_row_num = 0;
-  start_iMCU_row(cinfo);
-}
-
-
-/*
- * Process some data.
- * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
- * per call, ie, v_samp_factor block rows for each component in the scan.
- * The data is obtained from the virtual arrays and fed to the entropy coder.
- * Returns TRUE if the iMCU row is completed, FALSE if suspended.
- *
- * NB: input_buf is ignored; it is likely to be a NULL pointer.
- */
-
-METHODDEF(boolean)
-compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION MCU_col_num;	/* index of current MCU within row */
-  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
-  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
-  int blkn, ci, xindex, yindex, yoffset, blockcnt;
-  JDIMENSION start_col;
-  JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
-  JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
-  JBLOCKROW buffer_ptr;
-  jpeg_component_info *compptr;
-
-  /* Align the virtual buffers for the components used in this scan. */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    buffer[ci] = (*cinfo->mem->access_virt_barray)
-      ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
-       coef->iMCU_row_num * compptr->v_samp_factor,
-       (JDIMENSION) compptr->v_samp_factor, FALSE);
-  }
-
-  /* Loop to process one whole iMCU row */
-  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
-       yoffset++) {
-    for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
-	 MCU_col_num++) {
-      /* Construct list of pointers to DCT blocks belonging to this MCU */
-      blkn = 0;			/* index of current DCT block within MCU */
-      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-	compptr = cinfo->cur_comp_info[ci];
-	start_col = MCU_col_num * compptr->MCU_width;
-	blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
-						: compptr->last_col_width;
-	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
-	  if (coef->iMCU_row_num < last_iMCU_row ||
-	      yindex+yoffset < compptr->last_row_height) {
-	    /* Fill in pointers to real blocks in this row */
-	    buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
-	    for (xindex = 0; xindex < blockcnt; xindex++)
-	      MCU_buffer[blkn++] = buffer_ptr++;
-	  } else {
-	    /* At bottom of image, need a whole row of dummy blocks */
-	    xindex = 0;
-	  }
-	  /* Fill in any dummy blocks needed in this row.
-	   * Dummy blocks are filled in the same way as in jccoefct.c:
-	   * all zeroes in the AC entries, DC entries equal to previous
-	   * block's DC value.  The init routine has already zeroed the
-	   * AC entries, so we need only set the DC entries correctly.
-	   */
-	  for (; xindex < compptr->MCU_width; xindex++) {
-	    MCU_buffer[blkn] = coef->dummy_buffer[blkn];
-	    MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
-	    blkn++;
-	  }
-	}
-      }
-      /* Try to write the MCU. */
-      if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
-	/* Suspension forced; update state counters and exit */
-	coef->MCU_vert_offset = yoffset;
-	coef->mcu_ctr = MCU_col_num;
-	return FALSE;
-      }
-    }
-    /* Completed an MCU row, but perhaps not an iMCU row */
-    coef->mcu_ctr = 0;
-  }
-  /* Completed the iMCU row, advance counters for next one */
-  coef->iMCU_row_num++;
-  start_iMCU_row(cinfo);
-  return TRUE;
-}
-
-
-/*
- * Initialize coefficient buffer controller.
- *
- * Each passed coefficient array must be the right size for that
- * coefficient: width_in_blocks wide and height_in_blocks high,
- * with unitheight at least v_samp_factor.
- */
-
-LOCAL(void)
-transencode_coef_controller (j_compress_ptr cinfo,
-			     jvirt_barray_ptr * coef_arrays)
-{
-  my_coef_ptr coef;
-  JBLOCKROW buffer;
-  int i;
-
-  coef = (my_coef_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_coef_controller));
-  cinfo->coef = (struct jpeg_c_coef_controller *) coef;
-  coef->pub.start_pass = start_pass_coef;
-  coef->pub.compress_data = compress_output;
-
-  /* Save pointer to virtual arrays */
-  coef->whole_image = coef_arrays;
-
-  /* Allocate and pre-zero space for dummy DCT blocks. */
-  buffer = (JBLOCKROW)
-    (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
-  jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
-  for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
-    coef->dummy_buffer[i] = buffer + i;
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdapimin.c ./Shared/jpeg-6b/jdapimin.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdapimin.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jdapimin.c	Wed Dec 31 19:00:00 1969
@@ -1,395 +0,0 @@
-/*
- * jdapimin.c
- *
- * Copyright (C) 1994-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains application interface code for the decompression half
- * of the JPEG library.  These are the "minimum" API routines that may be
- * needed in either the normal full-decompression case or the
- * transcoding-only case.
- *
- * Most of the routines intended to be called directly by an application
- * are in this file or in jdapistd.c.  But also see jcomapi.c for routines
- * shared by compression and decompression, and jdtrans.c for the transcoding
- * case.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * Initialization of a JPEG decompression object.
- * The error manager must already be set up (in case memory manager fails).
- */
-
-GLOBAL(void)
-jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
-{
-  int i;
-
-  /* Guard against version mismatches between library and caller. */
-  cinfo->mem = NULL;		/* so jpeg_destroy knows mem mgr not called */
-  if (version != JPEG_LIB_VERSION)
-    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
-  if (structsize != SIZEOF(struct jpeg_decompress_struct))
-    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE, 
-	     (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
-
-  /* For debugging purposes, we zero the whole master structure.
-   * But the application has already set the err pointer, and may have set
-   * client_data, so we have to save and restore those fields.
-   * Note: if application hasn't set client_data, tools like Purify may
-   * complain here.
-   */
-  {
-    struct jpeg_error_mgr * err = cinfo->err;
-    void * client_data = cinfo->client_data; /* ignore Purify complaint here */
-    MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
-    cinfo->err = err;
-    cinfo->client_data = client_data;
-  }
-  cinfo->is_decompressor = TRUE;
-
-  /* Initialize a memory manager instance for this object */
-  jinit_memory_mgr((j_common_ptr) cinfo);
-
-  /* Zero out pointers to permanent structures. */
-  cinfo->progress = NULL;
-  cinfo->src = NULL;
-
-  for (i = 0; i < NUM_QUANT_TBLS; i++)
-    cinfo->quant_tbl_ptrs[i] = NULL;
-
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    cinfo->dc_huff_tbl_ptrs[i] = NULL;
-    cinfo->ac_huff_tbl_ptrs[i] = NULL;
-  }
-
-  /* Initialize marker processor so application can override methods
-   * for COM, APPn markers before calling jpeg_read_header.
-   */
-  cinfo->marker_list = NULL;
-  jinit_marker_reader(cinfo);
-
-  /* And initialize the overall input controller. */
-  jinit_input_controller(cinfo);
-
-  /* OK, I'm ready */
-  cinfo->global_state = DSTATE_START;
-}
-
-
-/*
- * Destruction of a JPEG decompression object
- */
-
-GLOBAL(void)
-jpeg_destroy_decompress (j_decompress_ptr cinfo)
-{
-  jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
-}
-
-
-/*
- * Abort processing of a JPEG decompression operation,
- * but don't destroy the object itself.
- */
-
-GLOBAL(void)
-jpeg_abort_decompress (j_decompress_ptr cinfo)
-{
-  jpeg_abort((j_common_ptr) cinfo); /* use common routine */
-}
-
-
-/*
- * Set default decompression parameters.
- */
-
-LOCAL(void)
-default_decompress_parms (j_decompress_ptr cinfo)
-{
-  /* Guess the input colorspace, and set output colorspace accordingly. */
-  /* (Wish JPEG committee had provided a real way to specify this...) */
-  /* Note application may override our guesses. */
-  switch (cinfo->num_components) {
-  case 1:
-    cinfo->jpeg_color_space = JCS_GRAYSCALE;
-    cinfo->out_color_space = JCS_GRAYSCALE;
-    break;
-    
-  case 3:
-    if (cinfo->saw_JFIF_marker) {
-      cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
-    } else if (cinfo->saw_Adobe_marker) {
-      switch (cinfo->Adobe_transform) {
-      case 0:
-	cinfo->jpeg_color_space = JCS_RGB;
-	break;
-      case 1:
-	cinfo->jpeg_color_space = JCS_YCbCr;
-	break;
-      default:
-	WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
-	cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
-	break;
-      }
-    } else {
-      /* Saw no special markers, try to guess from the component IDs */
-      int cid0 = cinfo->comp_info[0].component_id;
-      int cid1 = cinfo->comp_info[1].component_id;
-      int cid2 = cinfo->comp_info[2].component_id;
-
-      if (cid0 == 1 && cid1 == 2 && cid2 == 3)
-	cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
-      else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
-	cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
-      else {
-	TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
-	cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
-      }
-    }
-    /* Always guess RGB is proper output colorspace. */
-    cinfo->out_color_space = JCS_RGB;
-    break;
-    
-  case 4:
-    if (cinfo->saw_Adobe_marker) {
-      switch (cinfo->Adobe_transform) {
-      case 0:
-	cinfo->jpeg_color_space = JCS_CMYK;
-	break;
-      case 2:
-	cinfo->jpeg_color_space = JCS_YCCK;
-	break;
-      default:
-	WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
-	cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
-	break;
-      }
-    } else {
-      /* No special markers, assume straight CMYK. */
-      cinfo->jpeg_color_space = JCS_CMYK;
-    }
-    cinfo->out_color_space = JCS_CMYK;
-    break;
-    
-  default:
-    cinfo->jpeg_color_space = JCS_UNKNOWN;
-    cinfo->out_color_space = JCS_UNKNOWN;
-    break;
-  }
-
-  /* Set defaults for other decompression parameters. */
-  cinfo->scale_num = 1;		/* 1:1 scaling */
-  cinfo->scale_denom = 1;
-  cinfo->output_gamma = 1.0;
-  cinfo->buffered_image = FALSE;
-  cinfo->raw_data_out = FALSE;
-  cinfo->dct_method = JDCT_DEFAULT;
-  cinfo->do_fancy_upsampling = TRUE;
-  cinfo->do_block_smoothing = TRUE;
-  cinfo->quantize_colors = FALSE;
-  /* We set these in case application only sets quantize_colors. */
-  cinfo->dither_mode = JDITHER_FS;
-#ifdef QUANT_2PASS_SUPPORTED
-  cinfo->two_pass_quantize = TRUE;
-#else
-  cinfo->two_pass_quantize = FALSE;
-#endif
-  cinfo->desired_number_of_colors = 256;
-  cinfo->colormap = NULL;
-  /* Initialize for no mode change in buffered-image mode. */
-  cinfo->enable_1pass_quant = FALSE;
-  cinfo->enable_external_quant = FALSE;
-  cinfo->enable_2pass_quant = FALSE;
-}
-
-
-/*
- * Decompression startup: read start of JPEG datastream to see what's there.
- * Need only initialize JPEG object and supply a data source before calling.
- *
- * This routine will read as far as the first SOS marker (ie, actual start of
- * compressed data), and will save all tables and parameters in the JPEG
- * object.  It will also initialize the decompression parameters to default
- * values, and finally return JPEG_HEADER_OK.  On return, the application may
- * adjust the decompression parameters and then call jpeg_start_decompress.
- * (Or, if the application only wanted to determine the image parameters,
- * the data need not be decompressed.  In that case, call jpeg_abort or
- * jpeg_destroy to release any temporary space.)
- * If an abbreviated (tables only) datastream is presented, the routine will
- * return JPEG_HEADER_TABLES_ONLY upon reaching EOI.  The application may then
- * re-use the JPEG object to read the abbreviated image datastream(s).
- * It is unnecessary (but OK) to call jpeg_abort in this case.
- * The JPEG_SUSPENDED return code only occurs if the data source module
- * requests suspension of the decompressor.  In this case the application
- * should load more source data and then re-call jpeg_read_header to resume
- * processing.
- * If a non-suspending data source is used and require_image is TRUE, then the
- * return code need not be inspected since only JPEG_HEADER_OK is possible.
- *
- * This routine is now just a front end to jpeg_consume_input, with some
- * extra error checking.
- */
-
-GLOBAL(int)
-jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
-{
-  int retcode;
-
-  if (cinfo->global_state != DSTATE_START &&
-      cinfo->global_state != DSTATE_INHEADER)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  retcode = jpeg_consume_input(cinfo);
-
-  switch (retcode) {
-  case JPEG_REACHED_SOS:
-    retcode = JPEG_HEADER_OK;
-    break;
-  case JPEG_REACHED_EOI:
-    if (require_image)		/* Complain if application wanted an image */
-      ERREXIT(cinfo, JERR_NO_IMAGE);
-    /* Reset to start state; it would be safer to require the application to
-     * call jpeg_abort, but we can't change it now for compatibility reasons.
-     * A side effect is to free any temporary memory (there shouldn't be any).
-     */
-    jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
-    retcode = JPEG_HEADER_TABLES_ONLY;
-    break;
-  case JPEG_SUSPENDED:
-    /* no work */
-    break;
-  }
-
-  return retcode;
-}
-
-
-/*
- * Consume data in advance of what the decompressor requires.
- * This can be called at any time once the decompressor object has
- * been created and a data source has been set up.
- *
- * This routine is essentially a state machine that handles a couple
- * of critical state-transition actions, namely initial setup and
- * transition from header scanning to ready-for-start_decompress.
- * All the actual input is done via the input controller's consume_input
- * method.
- */
-
-GLOBAL(int)
-jpeg_consume_input (j_decompress_ptr cinfo)
-{
-  int retcode = JPEG_SUSPENDED;
-
-  /* NB: every possible DSTATE value should be listed in this switch */
-  switch (cinfo->global_state) {
-  case DSTATE_START:
-    /* Start-of-datastream actions: reset appropriate modules */
-    (*cinfo->inputctl->reset_input_controller) (cinfo);
-    /* Initialize application's data source module */
-    (*cinfo->src->init_source) (cinfo);
-    cinfo->global_state = DSTATE_INHEADER;
-    /*FALLTHROUGH*/
-  case DSTATE_INHEADER:
-    retcode = (*cinfo->inputctl->consume_input) (cinfo);
-    if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
-      /* Set up default parameters based on header data */
-      default_decompress_parms(cinfo);
-      /* Set global state: ready for start_decompress */
-      cinfo->global_state = DSTATE_READY;
-    }
-    break;
-  case DSTATE_READY:
-    /* Can't advance past first SOS until start_decompress is called */
-    retcode = JPEG_REACHED_SOS;
-    break;
-  case DSTATE_PRELOAD:
-  case DSTATE_PRESCAN:
-  case DSTATE_SCANNING:
-  case DSTATE_RAW_OK:
-  case DSTATE_BUFIMAGE:
-  case DSTATE_BUFPOST:
-  case DSTATE_STOPPING:
-    retcode = (*cinfo->inputctl->consume_input) (cinfo);
-    break;
-  default:
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  }
-  return retcode;
-}
-
-
-/*
- * Have we finished reading the input file?
- */
-
-GLOBAL(boolean)
-jpeg_input_complete (j_decompress_ptr cinfo)
-{
-  /* Check for valid jpeg object */
-  if (cinfo->global_state < DSTATE_START ||
-      cinfo->global_state > DSTATE_STOPPING)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  return cinfo->inputctl->eoi_reached;
-}
-
-
-/*
- * Is there more than one scan?
- */
-
-GLOBAL(boolean)
-jpeg_has_multiple_scans (j_decompress_ptr cinfo)
-{
-  /* Only valid after jpeg_read_header completes */
-  if (cinfo->global_state < DSTATE_READY ||
-      cinfo->global_state > DSTATE_STOPPING)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  return cinfo->inputctl->has_multiple_scans;
-}
-
-
-/*
- * Finish JPEG decompression.
- *
- * This will normally just verify the file trailer and release temp storage.
- *
- * Returns FALSE if suspended.  The return value need be inspected only if
- * a suspending data source is used.
- */
-
-GLOBAL(boolean)
-jpeg_finish_decompress (j_decompress_ptr cinfo)
-{
-  if ((cinfo->global_state == DSTATE_SCANNING ||
-       cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
-    /* Terminate final pass of non-buffered mode */
-    if (cinfo->output_scanline < cinfo->output_height)
-      ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
-    (*cinfo->master->finish_output_pass) (cinfo);
-    cinfo->global_state = DSTATE_STOPPING;
-  } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
-    /* Finishing after a buffered-image operation */
-    cinfo->global_state = DSTATE_STOPPING;
-  } else if (cinfo->global_state != DSTATE_STOPPING) {
-    /* STOPPING = repeat call after a suspension, anything else is error */
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  }
-  /* Read until EOI */
-  while (! cinfo->inputctl->eoi_reached) {
-    if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
-      return FALSE;		/* Suspend, come back later */
-  }
-  /* Do final cleanup */
-  (*cinfo->src->term_source) (cinfo);
-  /* We can use jpeg_abort to release memory and reset global_state */
-  jpeg_abort((j_common_ptr) cinfo);
-  return TRUE;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdapistd.c ./Shared/jpeg-6b/jdapistd.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdapistd.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jdapistd.c	Wed Dec 31 19:00:00 1969
@@ -1,275 +0,0 @@
-/*
- * jdapistd.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains application interface code for the decompression half
- * of the JPEG library.  These are the "standard" API routines that are
- * used in the normal full-decompression case.  They are not used by a
- * transcoding-only application.  Note that if an application links in
- * jpeg_start_decompress, it will end up linking in the entire decompressor.
- * We thus must separate this file from jdapimin.c to avoid linking the
- * whole decompression library into a transcoder.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Forward declarations */
-LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
-
-
-/*
- * Decompression initialization.
- * jpeg_read_header must be completed before calling this.
- *
- * If a multipass operating mode was selected, this will do all but the
- * last pass, and thus may take a great deal of time.
- *
- * Returns FALSE if suspended.  The return value need be inspected only if
- * a suspending data source is used.
- */
-
-GLOBAL(boolean)
-jpeg_start_decompress (j_decompress_ptr cinfo)
-{
-  if (cinfo->global_state == DSTATE_READY) {
-    /* First call: initialize master control, select active modules */
-    jinit_master_decompress(cinfo);
-    if (cinfo->buffered_image) {
-      /* No more work here; expecting jpeg_start_output next */
-      cinfo->global_state = DSTATE_BUFIMAGE;
-      return TRUE;
-    }
-    cinfo->global_state = DSTATE_PRELOAD;
-  }
-  if (cinfo->global_state == DSTATE_PRELOAD) {
-    /* If file has multiple scans, absorb them all into the coef buffer */
-    if (cinfo->inputctl->has_multiple_scans) {
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-      for (;;) {
-	int retcode;
-	/* Call progress monitor hook if present */
-	if (cinfo->progress != NULL)
-	  (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-	/* Absorb some more input */
-	retcode = (*cinfo->inputctl->consume_input) (cinfo);
-	if (retcode == JPEG_SUSPENDED)
-	  return FALSE;
-	if (retcode == JPEG_REACHED_EOI)
-	  break;
-	/* Advance progress counter if appropriate */
-	if (cinfo->progress != NULL &&
-	    (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
-	  if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
-	    /* jdmaster underestimated number of scans; ratchet up one scan */
-	    cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
-	  }
-	}
-      }
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif /* D_MULTISCAN_FILES_SUPPORTED */
-    }
-    cinfo->output_scan_number = cinfo->input_scan_number;
-  } else if (cinfo->global_state != DSTATE_PRESCAN)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  /* Perform any dummy output passes, and set up for the final pass */
-  return output_pass_setup(cinfo);
-}
-
-
-/*
- * Set up for an output pass, and perform any dummy pass(es) needed.
- * Common subroutine for jpeg_start_decompress and jpeg_start_output.
- * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
- * Exit: If done, returns TRUE and sets global_state for proper output mode.
- *       If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
- */
-
-LOCAL(boolean)
-output_pass_setup (j_decompress_ptr cinfo)
-{
-  if (cinfo->global_state != DSTATE_PRESCAN) {
-    /* First call: do pass setup */
-    (*cinfo->master->prepare_for_output_pass) (cinfo);
-    cinfo->output_scanline = 0;
-    cinfo->global_state = DSTATE_PRESCAN;
-  }
-  /* Loop over any required dummy passes */
-  while (cinfo->master->is_dummy_pass) {
-#ifdef QUANT_2PASS_SUPPORTED
-    /* Crank through the dummy pass */
-    while (cinfo->output_scanline < cinfo->output_height) {
-      JDIMENSION last_scanline;
-      /* Call progress monitor hook if present */
-      if (cinfo->progress != NULL) {
-	cinfo->progress->pass_counter = (long) cinfo->output_scanline;
-	cinfo->progress->pass_limit = (long) cinfo->output_height;
-	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-      }
-      /* Process some data */
-      last_scanline = cinfo->output_scanline;
-      (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
-				    &cinfo->output_scanline, (JDIMENSION) 0);
-      if (cinfo->output_scanline == last_scanline)
-	return FALSE;		/* No progress made, must suspend */
-    }
-    /* Finish up dummy pass, and set up for another one */
-    (*cinfo->master->finish_output_pass) (cinfo);
-    (*cinfo->master->prepare_for_output_pass) (cinfo);
-    cinfo->output_scanline = 0;
-#else
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif /* QUANT_2PASS_SUPPORTED */
-  }
-  /* Ready for application to drive output pass through
-   * jpeg_read_scanlines or jpeg_read_raw_data.
-   */
-  cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
-  return TRUE;
-}
-
-
-/*
- * Read some scanlines of data from the JPEG decompressor.
- *
- * The return value will be the number of lines actually read.
- * This may be less than the number requested in several cases,
- * including bottom of image, data source suspension, and operating
- * modes that emit multiple scanlines at a time.
- *
- * Note: we warn about excess calls to jpeg_read_scanlines() since
- * this likely signals an application programmer error.  However,
- * an oversize buffer (max_lines > scanlines remaining) is not an error.
- */
-
-GLOBAL(JDIMENSION)
-jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
-		     JDIMENSION max_lines)
-{
-  JDIMENSION row_ctr;
-
-  if (cinfo->global_state != DSTATE_SCANNING)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  if (cinfo->output_scanline >= cinfo->output_height) {
-    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
-    return 0;
-  }
-
-  /* Call progress monitor hook if present */
-  if (cinfo->progress != NULL) {
-    cinfo->progress->pass_counter = (long) cinfo->output_scanline;
-    cinfo->progress->pass_limit = (long) cinfo->output_height;
-    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-  }
-
-  /* Process some data */
-  row_ctr = 0;
-  (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
-  cinfo->output_scanline += row_ctr;
-  return row_ctr;
-}
-
-
-/*
- * Alternate entry point to read raw data.
- * Processes exactly one iMCU row per call, unless suspended.
- */
-
-GLOBAL(JDIMENSION)
-jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
-		    JDIMENSION max_lines)
-{
-  JDIMENSION lines_per_iMCU_row;
-
-  if (cinfo->global_state != DSTATE_RAW_OK)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  if (cinfo->output_scanline >= cinfo->output_height) {
-    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
-    return 0;
-  }
-
-  /* Call progress monitor hook if present */
-  if (cinfo->progress != NULL) {
-    cinfo->progress->pass_counter = (long) cinfo->output_scanline;
-    cinfo->progress->pass_limit = (long) cinfo->output_height;
-    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-  }
-
-  /* Verify that at least one iMCU row can be returned. */
-  lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
-  if (max_lines < lines_per_iMCU_row)
-    ERREXIT(cinfo, JERR_BUFFER_SIZE);
-
-  /* Decompress directly into user's buffer. */
-  if (! (*cinfo->coef->decompress_data) (cinfo, data))
-    return 0;			/* suspension forced, can do nothing more */
-
-  /* OK, we processed one iMCU row. */
-  cinfo->output_scanline += lines_per_iMCU_row;
-  return lines_per_iMCU_row;
-}
-
-
-/* Additional entry points for buffered-image mode. */
-
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-
-/*
- * Initialize for an output pass in buffered-image mode.
- */
-
-GLOBAL(boolean)
-jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
-{
-  if (cinfo->global_state != DSTATE_BUFIMAGE &&
-      cinfo->global_state != DSTATE_PRESCAN)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  /* Limit scan number to valid range */
-  if (scan_number <= 0)
-    scan_number = 1;
-  if (cinfo->inputctl->eoi_reached &&
-      scan_number > cinfo->input_scan_number)
-    scan_number = cinfo->input_scan_number;
-  cinfo->output_scan_number = scan_number;
-  /* Perform any dummy output passes, and set up for the real pass */
-  return output_pass_setup(cinfo);
-}
-
-
-/*
- * Finish up after an output pass in buffered-image mode.
- *
- * Returns FALSE if suspended.  The return value need be inspected only if
- * a suspending data source is used.
- */
-
-GLOBAL(boolean)
-jpeg_finish_output (j_decompress_ptr cinfo)
-{
-  if ((cinfo->global_state == DSTATE_SCANNING ||
-       cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
-    /* Terminate this pass. */
-    /* We do not require the whole pass to have been completed. */
-    (*cinfo->master->finish_output_pass) (cinfo);
-    cinfo->global_state = DSTATE_BUFPOST;
-  } else if (cinfo->global_state != DSTATE_BUFPOST) {
-    /* BUFPOST = repeat call after a suspension, anything else is error */
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  }
-  /* Read markers looking for SOS or EOI */
-  while (cinfo->input_scan_number <= cinfo->output_scan_number &&
-	 ! cinfo->inputctl->eoi_reached) {
-    if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
-      return FALSE;		/* Suspend, come back later */
-  }
-  cinfo->global_state = DSTATE_BUFIMAGE;
-  return TRUE;
-}
-
-#endif /* D_MULTISCAN_FILES_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdatadst.c ./Shared/jpeg-6b/jdatadst.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdatadst.c	Mon Dec  1 12:30:34 2003
+++ ./Shared/jpeg-6b/jdatadst.c	Wed Dec 31 19:00:00 1969
@@ -1,151 +0,0 @@
-/*
- * jdatadst.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains compression data destination routines for the case of
- * emitting JPEG data to a file (or any stdio stream).  While these routines
- * are sufficient for most applications, some will want to use a different
- * destination manager.
- * IMPORTANT: we assume that fwrite() will correctly transcribe an array of
- * JOCTETs into 8-bit-wide elements on external storage.  If char is wider
- * than 8 bits on your machine, you may need to do some tweaking.
- */
-
-/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jerror.h"
-
-
-/* Expanded data destination object for stdio output */
-
-typedef struct {
-  struct jpeg_destination_mgr pub; /* public fields */
-
-  FILE * outfile;		/* target stream */
-  JOCTET * buffer;		/* start of buffer */
-} my_destination_mgr;
-
-typedef my_destination_mgr * my_dest_ptr;
-
-#define OUTPUT_BUF_SIZE  4096	/* choose an efficiently fwrite'able size */
-
-
-/*
- * Initialize destination --- called by jpeg_start_compress
- * before any data is actually written.
- */
-
-METHODDEF(void)
-init_destination (j_compress_ptr cinfo)
-{
-  my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
-
-  /* Allocate the output buffer --- it will be released when done with image */
-  dest->buffer = (JOCTET *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  OUTPUT_BUF_SIZE * SIZEOF(JOCTET));
-
-  dest->pub.next_output_byte = dest->buffer;
-  dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
-}
-
-
-/*
- * Empty the output buffer --- called whenever buffer fills up.
- *
- * In typical applications, this should write the entire output buffer
- * (ignoring the current state of next_output_byte & free_in_buffer),
- * reset the pointer & count to the start of the buffer, and return TRUE
- * indicating that the buffer has been dumped.
- *
- * In applications that need to be able to suspend compression due to output
- * overrun, a FALSE return indicates that the buffer cannot be emptied now.
- * In this situation, the compressor will return to its caller (possibly with
- * an indication that it has not accepted all the supplied scanlines).  The
- * application should resume compression after it has made more room in the
- * output buffer.  Note that there are substantial restrictions on the use of
- * suspension --- see the documentation.
- *
- * When suspending, the compressor will back up to a convenient restart point
- * (typically the start of the current MCU). next_output_byte & free_in_buffer
- * indicate where the restart point will be if the current call returns FALSE.
- * Data beyond this point will be regenerated after resumption, so do not
- * write it out when emptying the buffer externally.
- */
-
-METHODDEF(boolean)
-empty_output_buffer (j_compress_ptr cinfo)
-{
-  my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
-
-  if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) !=
-      (size_t) OUTPUT_BUF_SIZE)
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-
-  dest->pub.next_output_byte = dest->buffer;
-  dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
-
-  return TRUE;
-}
-
-
-/*
- * Terminate destination --- called by jpeg_finish_compress
- * after all data has been written.  Usually needs to flush buffer.
- *
- * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
- * application must deal with any cleanup that should happen even
- * for error exit.
- */
-
-METHODDEF(void)
-term_destination (j_compress_ptr cinfo)
-{
-  my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
-  size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
-
-  /* Write any data remaining in the buffer */
-  if (datacount > 0) {
-    if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount)
-      ERREXIT(cinfo, JERR_FILE_WRITE);
-  }
-  fflush(dest->outfile);
-  /* Make sure we wrote the output file OK */
-  if (ferror(dest->outfile))
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-}
-
-
-/*
- * Prepare for output to a stdio stream.
- * The caller must have already opened the stream, and is responsible
- * for closing it after finishing compression.
- */
-
-GLOBAL(void)
-jpeg_stdio_dest (j_compress_ptr cinfo, FILE * outfile)
-{
-  my_dest_ptr dest;
-
-  /* The destination object is made permanent so that multiple JPEG images
-   * can be written to the same file without re-executing jpeg_stdio_dest.
-   * This makes it dangerous to use this manager and a different destination
-   * manager serially with the same JPEG object, because their private object
-   * sizes may be different.  Caveat programmer.
-   */
-  if (cinfo->dest == NULL) {	/* first time for this JPEG object? */
-    cinfo->dest = (struct jpeg_destination_mgr *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
-				  SIZEOF(my_destination_mgr));
-  }
-
-  dest = (my_dest_ptr) cinfo->dest;
-  dest->pub.init_destination = init_destination;
-  dest->pub.empty_output_buffer = empty_output_buffer;
-  dest->pub.term_destination = term_destination;
-  dest->outfile = outfile;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdatasrc.c ./Shared/jpeg-6b/jdatasrc.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdatasrc.c	Mon Dec  1 12:30:35 2003
+++ ./Shared/jpeg-6b/jdatasrc.c	Wed Dec 31 19:00:00 1969
@@ -1,212 +0,0 @@
-/*
- * jdatasrc.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains decompression data source routines for the case of
- * reading JPEG data from a file (or any stdio stream).  While these routines
- * are sufficient for most applications, some will want to use a different
- * source manager.
- * IMPORTANT: we assume that fread() will correctly transcribe an array of
- * JOCTETs from 8-bit-wide elements on external storage.  If char is wider
- * than 8 bits on your machine, you may need to do some tweaking.
- */
-
-/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jerror.h"
-
-
-/* Expanded data source object for stdio input */
-
-typedef struct {
-  struct jpeg_source_mgr pub;	/* public fields */
-
-  FILE * infile;		/* source stream */
-  JOCTET * buffer;		/* start of buffer */
-  boolean start_of_file;	/* have we gotten any data yet? */
-} my_source_mgr;
-
-typedef my_source_mgr * my_src_ptr;
-
-#define INPUT_BUF_SIZE  4096	/* choose an efficiently fread'able size */
-
-
-/*
- * Initialize source --- called by jpeg_read_header
- * before any data is actually read.
- */
-
-METHODDEF(void)
-init_source (j_decompress_ptr cinfo)
-{
-  my_src_ptr src = (my_src_ptr) cinfo->src;
-
-  /* We reset the empty-input-file flag for each image,
-   * but we don't clear the input buffer.
-   * This is correct behavior for reading a series of images from one source.
-   */
-  src->start_of_file = TRUE;
-}
-
-
-/*
- * Fill the input buffer --- called whenever buffer is emptied.
- *
- * In typical applications, this should read fresh data into the buffer
- * (ignoring the current state of next_input_byte & bytes_in_buffer),
- * reset the pointer & count to the start of the buffer, and return TRUE
- * indicating that the buffer has been reloaded.  It is not necessary to
- * fill the buffer entirely, only to obtain at least one more byte.
- *
- * There is no such thing as an EOF return.  If the end of the file has been
- * reached, the routine has a choice of ERREXIT() or inserting fake data into
- * the buffer.  In most cases, generating a warning message and inserting a
- * fake EOI marker is the best course of action --- this will allow the
- * decompressor to output however much of the image is there.  However,
- * the resulting error message is misleading if the real problem is an empty
- * input file, so we handle that case specially.
- *
- * In applications that need to be able to suspend compression due to input
- * not being available yet, a FALSE return indicates that no more data can be
- * obtained right now, but more may be forthcoming later.  In this situation,
- * the decompressor will return to its caller (with an indication of the
- * number of scanlines it has read, if any).  The application should resume
- * decompression after it has loaded more data into the input buffer.  Note
- * that there are substantial restrictions on the use of suspension --- see
- * the documentation.
- *
- * When suspending, the decompressor will back up to a convenient restart point
- * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
- * indicate where the restart point will be if the current call returns FALSE.
- * Data beyond this point must be rescanned after resumption, so move it to
- * the front of the buffer rather than discarding it.
- */
-
-METHODDEF(boolean)
-fill_input_buffer (j_decompress_ptr cinfo)
-{
-  my_src_ptr src = (my_src_ptr) cinfo->src;
-  size_t nbytes;
-
-  nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
-
-  if (nbytes <= 0) {
-    if (src->start_of_file)	/* Treat empty input file as fatal error */
-      ERREXIT(cinfo, JERR_INPUT_EMPTY);
-    WARNMS(cinfo, JWRN_JPEG_EOF);
-    /* Insert a fake EOI marker */
-    src->buffer[0] = (JOCTET) 0xFF;
-    src->buffer[1] = (JOCTET) JPEG_EOI;
-    nbytes = 2;
-  }
-
-  src->pub.next_input_byte = src->buffer;
-  src->pub.bytes_in_buffer = nbytes;
-  src->start_of_file = FALSE;
-
-  return TRUE;
-}
-
-
-/*
- * Skip data --- used to skip over a potentially large amount of
- * uninteresting data (such as an APPn marker).
- *
- * Writers of suspendable-input applications must note that skip_input_data
- * is not granted the right to give a suspension return.  If the skip extends
- * beyond the data currently in the buffer, the buffer can be marked empty so
- * that the next read will cause a fill_input_buffer call that can suspend.
- * Arranging for additional bytes to be discarded before reloading the input
- * buffer is the application writer's problem.
- */
-
-METHODDEF(void)
-skip_input_data (j_decompress_ptr cinfo, long num_bytes)
-{
-  my_src_ptr src = (my_src_ptr) cinfo->src;
-
-  /* Just a dumb implementation for now.  Could use fseek() except
-   * it doesn't work on pipes.  Not clear that being smart is worth
-   * any trouble anyway --- large skips are infrequent.
-   */
-  if (num_bytes > 0) {
-    while (num_bytes > (long) src->pub.bytes_in_buffer) {
-      num_bytes -= (long) src->pub.bytes_in_buffer;
-      (void) fill_input_buffer(cinfo);
-      /* note we assume that fill_input_buffer will never return FALSE,
-       * so suspension need not be handled.
-       */
-    }
-    src->pub.next_input_byte += (size_t) num_bytes;
-    src->pub.bytes_in_buffer -= (size_t) num_bytes;
-  }
-}
-
-
-/*
- * An additional method that can be provided by data source modules is the
- * resync_to_restart method for error recovery in the presence of RST markers.
- * For the moment, this source module just uses the default resync method
- * provided by the JPEG library.  That method assumes that no backtracking
- * is possible.
- */
-
-
-/*
- * Terminate source --- called by jpeg_finish_decompress
- * after all data has been read.  Often a no-op.
- *
- * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
- * application must deal with any cleanup that should happen even
- * for error exit.
- */
-
-METHODDEF(void)
-term_source (j_decompress_ptr cinfo)
-{
-  /* no work necessary here */
-}
-
-
-/*
- * Prepare for input from a stdio stream.
- * The caller must have already opened the stream, and is responsible
- * for closing it after finishing decompression.
- */
-
-GLOBAL(void)
-jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
-{
-  my_src_ptr src;
-
-  /* The source object and input buffer are made permanent so that a series
-   * of JPEG images can be read from the same file by calling jpeg_stdio_src
-   * only before the first one.  (If we discarded the buffer at the end of
-   * one image, we'd likely lose the start of the next one.)
-   * This makes it unsafe to use this manager and a different source
-   * manager serially with the same JPEG object.  Caveat programmer.
-   */
-  if (cinfo->src == NULL) {	/* first time for this JPEG object? */
-    cinfo->src = (struct jpeg_source_mgr *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
-				  SIZEOF(my_source_mgr));
-    src = (my_src_ptr) cinfo->src;
-    src->buffer = (JOCTET *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
-				  INPUT_BUF_SIZE * SIZEOF(JOCTET));
-  }
-
-  src = (my_src_ptr) cinfo->src;
-  src->pub.init_source = init_source;
-  src->pub.fill_input_buffer = fill_input_buffer;
-  src->pub.skip_input_data = skip_input_data;
-  src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
-  src->pub.term_source = term_source;
-  src->infile = infile;
-  src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
-  src->pub.next_input_byte = NULL; /* until buffer loaded */
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdcoefct.c ./Shared/jpeg-6b/jdcoefct.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdcoefct.c	Mon Dec  1 12:30:35 2003
+++ ./Shared/jpeg-6b/jdcoefct.c	Wed Dec 31 19:00:00 1969
@@ -1,736 +0,0 @@
-/*
- * jdcoefct.c
- *
- * Copyright (C) 1994-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the coefficient buffer controller for decompression.
- * This controller is the top level of the JPEG decompressor proper.
- * The coefficient buffer lies between entropy decoding and inverse-DCT steps.
- *
- * In buffered-image mode, this controller is the interface between
- * input-oriented processing and output-oriented processing.
- * Also, the input side (only) is used when reading a file for transcoding.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-/* Block smoothing is only applicable for progressive JPEG, so: */
-#ifndef D_PROGRESSIVE_SUPPORTED
-#undef BLOCK_SMOOTHING_SUPPORTED
-#endif
-
-/* Private buffer controller object */
-
-typedef struct {
-  struct jpeg_d_coef_controller pub; /* public fields */
-
-  /* These variables keep track of the current location of the input side. */
-  /* cinfo->input_iMCU_row is also used for this. */
-  JDIMENSION MCU_ctr;		/* counts MCUs processed in current row */
-  int MCU_vert_offset;		/* counts MCU rows within iMCU row */
-  int MCU_rows_per_iMCU_row;	/* number of such rows needed */
-
-  /* The output side's location is represented by cinfo->output_iMCU_row. */
-
-  /* In single-pass modes, it's sufficient to buffer just one MCU.
-   * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
-   * and let the entropy decoder write into that workspace each time.
-   * (On 80x86, the workspace is FAR even though it's not really very big;
-   * this is to keep the module interfaces unchanged when a large coefficient
-   * buffer is necessary.)
-   * In multi-pass modes, this array points to the current MCU's blocks
-   * within the virtual arrays; it is used only by the input side.
-   */
-  JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
-
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-  /* In multi-pass modes, we need a virtual block array for each component. */
-  jvirt_barray_ptr whole_image[MAX_COMPONENTS];
-#endif
-
-#ifdef BLOCK_SMOOTHING_SUPPORTED
-  /* When doing block smoothing, we latch coefficient Al values here */
-  int * coef_bits_latch;
-#define SAVED_COEFS  6		/* we save coef_bits[0..5] */
-#endif
-} my_coef_controller;
-
-typedef my_coef_controller * my_coef_ptr;
-
-/* Forward declarations */
-METHODDEF(int) decompress_onepass
-	JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-METHODDEF(int) decompress_data
-	JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
-#endif
-#ifdef BLOCK_SMOOTHING_SUPPORTED
-LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
-METHODDEF(int) decompress_smooth_data
-	JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
-#endif
-
-
-LOCAL(void)
-start_iMCU_row (j_decompress_ptr cinfo)
-/* Reset within-iMCU-row counters for a new row (input side) */
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-
-  /* In an interleaved scan, an MCU row is the same as an iMCU row.
-   * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
-   * But at the bottom of the image, process only what's left.
-   */
-  if (cinfo->comps_in_scan > 1) {
-    coef->MCU_rows_per_iMCU_row = 1;
-  } else {
-    if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
-      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
-    else
-      coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
-  }
-
-  coef->MCU_ctr = 0;
-  coef->MCU_vert_offset = 0;
-}
-
-
-/*
- * Initialize for an input processing pass.
- */
-
-METHODDEF(void)
-start_input_pass (j_decompress_ptr cinfo)
-{
-  cinfo->input_iMCU_row = 0;
-  start_iMCU_row(cinfo);
-}
-
-
-/*
- * Initialize for an output processing pass.
- */
-
-METHODDEF(void)
-start_output_pass (j_decompress_ptr cinfo)
-{
-#ifdef BLOCK_SMOOTHING_SUPPORTED
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-
-  /* If multipass, check to see whether to use block smoothing on this pass */
-  if (coef->pub.coef_arrays != NULL) {
-    if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
-      coef->pub.decompress_data = decompress_smooth_data;
-    else
-      coef->pub.decompress_data = decompress_data;
-  }
-#endif
-  cinfo->output_iMCU_row = 0;
-}
-
-
-/*
- * Decompress and return some data in the single-pass case.
- * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
- * Input and output must run in lockstep since we have only a one-MCU buffer.
- * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
- *
- * NB: output_buf contains a plane for each component in image,
- * which we index according to the component's SOF position.
- */
-
-METHODDEF(int)
-decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION MCU_col_num;	/* index of current MCU within row */
-  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
-  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
-  int blkn, ci, xindex, yindex, yoffset, useful_width;
-  JSAMPARRAY output_ptr;
-  JDIMENSION start_col, output_col;
-  jpeg_component_info *compptr;
-  inverse_DCT_method_ptr inverse_DCT;
-
-  /* Loop to process as much as one whole iMCU row */
-  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
-       yoffset++) {
-    for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
-	 MCU_col_num++) {
-      /* Try to fetch an MCU.  Entropy decoder expects buffer to be zeroed. */
-      jzero_far((void FAR *) coef->MCU_buffer[0],
-		(size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
-      if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
-	/* Suspension forced; update state counters and exit */
-	coef->MCU_vert_offset = yoffset;
-	coef->MCU_ctr = MCU_col_num;
-	return JPEG_SUSPENDED;
-      }
-      /* Determine where data should go in output_buf and do the IDCT thing.
-       * We skip dummy blocks at the right and bottom edges (but blkn gets
-       * incremented past them!).  Note the inner loop relies on having
-       * allocated the MCU_buffer[] blocks sequentially.
-       */
-      blkn = 0;			/* index of current DCT block within MCU */
-      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-	compptr = cinfo->cur_comp_info[ci];
-	/* Don't bother to IDCT an uninteresting component. */
-	if (! compptr->component_needed) {
-	  blkn += compptr->MCU_blocks;
-	  continue;
-	}
-	inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
-	useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
-						    : compptr->last_col_width;
-	output_ptr = output_buf[compptr->component_index] +
-	  yoffset * compptr->DCT_scaled_size;
-	start_col = MCU_col_num * compptr->MCU_sample_width;
-	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
-	  if (cinfo->input_iMCU_row < last_iMCU_row ||
-	      yoffset+yindex < compptr->last_row_height) {
-	    output_col = start_col;
-	    for (xindex = 0; xindex < useful_width; xindex++) {
-	      (*inverse_DCT) (cinfo, compptr,
-			      (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
-			      output_ptr, output_col);
-	      output_col += compptr->DCT_scaled_size;
-	    }
-	  }
-	  blkn += compptr->MCU_width;
-	  output_ptr += compptr->DCT_scaled_size;
-	}
-      }
-    }
-    /* Completed an MCU row, but perhaps not an iMCU row */
-    coef->MCU_ctr = 0;
-  }
-  /* Completed the iMCU row, advance counters for next one */
-  cinfo->output_iMCU_row++;
-  if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
-    start_iMCU_row(cinfo);
-    return JPEG_ROW_COMPLETED;
-  }
-  /* Completed the scan */
-  (*cinfo->inputctl->finish_input_pass) (cinfo);
-  return JPEG_SCAN_COMPLETED;
-}
-
-
-/*
- * Dummy consume-input routine for single-pass operation.
- */
-
-METHODDEF(int)
-dummy_consume_data (j_decompress_ptr cinfo)
-{
-  return JPEG_SUSPENDED;	/* Always indicate nothing was done */
-}
-
-
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-
-/*
- * Consume input data and store it in the full-image coefficient buffer.
- * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
- * ie, v_samp_factor block rows for each component in the scan.
- * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
- */
-
-METHODDEF(int)
-consume_data (j_decompress_ptr cinfo)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION MCU_col_num;	/* index of current MCU within row */
-  int blkn, ci, xindex, yindex, yoffset;
-  JDIMENSION start_col;
-  JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
-  JBLOCKROW buffer_ptr;
-  jpeg_component_info *compptr;
-
-  /* Align the virtual buffers for the components used in this scan. */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    buffer[ci] = (*cinfo->mem->access_virt_barray)
-      ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
-       cinfo->input_iMCU_row * compptr->v_samp_factor,
-       (JDIMENSION) compptr->v_samp_factor, TRUE);
-    /* Note: entropy decoder expects buffer to be zeroed,
-     * but this is handled automatically by the memory manager
-     * because we requested a pre-zeroed array.
-     */
-  }
-
-  /* Loop to process one whole iMCU row */
-  for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
-       yoffset++) {
-    for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
-	 MCU_col_num++) {
-      /* Construct list of pointers to DCT blocks belonging to this MCU */
-      blkn = 0;			/* index of current DCT block within MCU */
-      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-	compptr = cinfo->cur_comp_info[ci];
-	start_col = MCU_col_num * compptr->MCU_width;
-	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
-	  buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
-	  for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
-	    coef->MCU_buffer[blkn++] = buffer_ptr++;
-	  }
-	}
-      }
-      /* Try to fetch the MCU. */
-      if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
-	/* Suspension forced; update state counters and exit */
-	coef->MCU_vert_offset = yoffset;
-	coef->MCU_ctr = MCU_col_num;
-	return JPEG_SUSPENDED;
-      }
-    }
-    /* Completed an MCU row, but perhaps not an iMCU row */
-    coef->MCU_ctr = 0;
-  }
-  /* Completed the iMCU row, advance counters for next one */
-  if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
-    start_iMCU_row(cinfo);
-    return JPEG_ROW_COMPLETED;
-  }
-  /* Completed the scan */
-  (*cinfo->inputctl->finish_input_pass) (cinfo);
-  return JPEG_SCAN_COMPLETED;
-}
-
-
-/*
- * Decompress and return some data in the multi-pass case.
- * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
- * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
- *
- * NB: output_buf contains a plane for each component in image.
- */
-
-METHODDEF(int)
-decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
-  JDIMENSION block_num;
-  int ci, block_row, block_rows;
-  JBLOCKARRAY buffer;
-  JBLOCKROW buffer_ptr;
-  JSAMPARRAY output_ptr;
-  JDIMENSION output_col;
-  jpeg_component_info *compptr;
-  inverse_DCT_method_ptr inverse_DCT;
-
-  /* Force some input to be done if we are getting ahead of the input. */
-  while (cinfo->input_scan_number < cinfo->output_scan_number ||
-	 (cinfo->input_scan_number == cinfo->output_scan_number &&
-	  cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
-    if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
-      return JPEG_SUSPENDED;
-  }
-
-  /* OK, output from the virtual arrays. */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Don't bother to IDCT an uninteresting component. */
-    if (! compptr->component_needed)
-      continue;
-    /* Align the virtual buffer for this component. */
-    buffer = (*cinfo->mem->access_virt_barray)
-      ((j_common_ptr) cinfo, coef->whole_image[ci],
-       cinfo->output_iMCU_row * compptr->v_samp_factor,
-       (JDIMENSION) compptr->v_samp_factor, FALSE);
-    /* Count non-dummy DCT block rows in this iMCU row. */
-    if (cinfo->output_iMCU_row < last_iMCU_row)
-      block_rows = compptr->v_samp_factor;
-    else {
-      /* NB: can't use last_row_height here; it is input-side-dependent! */
-      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
-      if (block_rows == 0) block_rows = compptr->v_samp_factor;
-    }
-    inverse_DCT = cinfo->idct->inverse_DCT[ci];
-    output_ptr = output_buf[ci];
-    /* Loop over all DCT blocks to be processed. */
-    for (block_row = 0; block_row < block_rows; block_row++) {
-      buffer_ptr = buffer[block_row];
-      output_col = 0;
-      for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
-	(*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
-			output_ptr, output_col);
-	buffer_ptr++;
-	output_col += compptr->DCT_scaled_size;
-      }
-      output_ptr += compptr->DCT_scaled_size;
-    }
-  }
-
-  if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
-    return JPEG_ROW_COMPLETED;
-  return JPEG_SCAN_COMPLETED;
-}
-
-#endif /* D_MULTISCAN_FILES_SUPPORTED */
-
-
-#ifdef BLOCK_SMOOTHING_SUPPORTED
-
-/*
- * This code applies interblock smoothing as described by section K.8
- * of the JPEG standard: the first 5 AC coefficients are estimated from
- * the DC values of a DCT block and its 8 neighboring blocks.
- * We apply smoothing only for progressive JPEG decoding, and only if
- * the coefficients it can estimate are not yet known to full precision.
- */
-
-/* Natural-order array positions of the first 5 zigzag-order coefficients */
-#define Q01_POS  1
-#define Q10_POS  8
-#define Q20_POS  16
-#define Q11_POS  9
-#define Q02_POS  2
-
-/*
- * Determine whether block smoothing is applicable and safe.
- * We also latch the current states of the coef_bits[] entries for the
- * AC coefficients; otherwise, if the input side of the decompressor
- * advances into a new scan, we might think the coefficients are known
- * more accurately than they really are.
- */
-
-LOCAL(boolean)
-smoothing_ok (j_decompress_ptr cinfo)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  boolean smoothing_useful = FALSE;
-  int ci, coefi;
-  jpeg_component_info *compptr;
-  JQUANT_TBL * qtable;
-  int * coef_bits;
-  int * coef_bits_latch;
-
-  if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
-    return FALSE;
-
-  /* Allocate latch area if not already done */
-  if (coef->coef_bits_latch == NULL)
-    coef->coef_bits_latch = (int *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  cinfo->num_components *
-				  (SAVED_COEFS * SIZEOF(int)));
-  coef_bits_latch = coef->coef_bits_latch;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* All components' quantization values must already be latched. */
-    if ((qtable = compptr->quant_table) == NULL)
-      return FALSE;
-    /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
-    if (qtable->quantval[0] == 0 ||
-	qtable->quantval[Q01_POS] == 0 ||
-	qtable->quantval[Q10_POS] == 0 ||
-	qtable->quantval[Q20_POS] == 0 ||
-	qtable->quantval[Q11_POS] == 0 ||
-	qtable->quantval[Q02_POS] == 0)
-      return FALSE;
-    /* DC values must be at least partly known for all components. */
-    coef_bits = cinfo->coef_bits[ci];
-    if (coef_bits[0] < 0)
-      return FALSE;
-    /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
-    for (coefi = 1; coefi <= 5; coefi++) {
-      coef_bits_latch[coefi] = coef_bits[coefi];
-      if (coef_bits[coefi] != 0)
-	smoothing_useful = TRUE;
-    }
-    coef_bits_latch += SAVED_COEFS;
-  }
-
-  return smoothing_useful;
-}
-
-
-/*
- * Variant of decompress_data for use when doing block smoothing.
- */
-
-METHODDEF(int)
-decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
-{
-  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
-  JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
-  JDIMENSION block_num, last_block_column;
-  int ci, block_row, block_rows, access_rows;
-  JBLOCKARRAY buffer;
-  JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
-  JSAMPARRAY output_ptr;
-  JDIMENSION output_col;
-  jpeg_component_info *compptr;
-  inverse_DCT_method_ptr inverse_DCT;
-  boolean first_row, last_row;
-  JBLOCK workspace;
-  int *coef_bits;
-  JQUANT_TBL *quanttbl;
-  INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
-  int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
-  int Al, pred;
-
-  /* Force some input to be done if we are getting ahead of the input. */
-  while (cinfo->input_scan_number <= cinfo->output_scan_number &&
-	 ! cinfo->inputctl->eoi_reached) {
-    if (cinfo->input_scan_number == cinfo->output_scan_number) {
-      /* If input is working on current scan, we ordinarily want it to
-       * have completed the current row.  But if input scan is DC,
-       * we want it to keep one row ahead so that next block row's DC
-       * values are up to date.
-       */
-      JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
-      if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
-	break;
-    }
-    if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
-      return JPEG_SUSPENDED;
-  }
-
-  /* OK, output from the virtual arrays. */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Don't bother to IDCT an uninteresting component. */
-    if (! compptr->component_needed)
-      continue;
-    /* Count non-dummy DCT block rows in this iMCU row. */
-    if (cinfo->output_iMCU_row < last_iMCU_row) {
-      block_rows = compptr->v_samp_factor;
-      access_rows = block_rows * 2; /* this and next iMCU row */
-      last_row = FALSE;
-    } else {
-      /* NB: can't use last_row_height here; it is input-side-dependent! */
-      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
-      if (block_rows == 0) block_rows = compptr->v_samp_factor;
-      access_rows = block_rows; /* this iMCU row only */
-      last_row = TRUE;
-    }
-    /* Align the virtual buffer for this component. */
-    if (cinfo->output_iMCU_row > 0) {
-      access_rows += compptr->v_samp_factor; /* prior iMCU row too */
-      buffer = (*cinfo->mem->access_virt_barray)
-	((j_common_ptr) cinfo, coef->whole_image[ci],
-	 (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
-	 (JDIMENSION) access_rows, FALSE);
-      buffer += compptr->v_samp_factor;	/* point to current iMCU row */
-      first_row = FALSE;
-    } else {
-      buffer = (*cinfo->mem->access_virt_barray)
-	((j_common_ptr) cinfo, coef->whole_image[ci],
-	 (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
-      first_row = TRUE;
-    }
-    /* Fetch component-dependent info */
-    coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
-    quanttbl = compptr->quant_table;
-    Q00 = quanttbl->quantval[0];
-    Q01 = quanttbl->quantval[Q01_POS];
-    Q10 = quanttbl->quantval[Q10_POS];
-    Q20 = quanttbl->quantval[Q20_POS];
-    Q11 = quanttbl->quantval[Q11_POS];
-    Q02 = quanttbl->quantval[Q02_POS];
-    inverse_DCT = cinfo->idct->inverse_DCT[ci];
-    output_ptr = output_buf[ci];
-    /* Loop over all DCT blocks to be processed. */
-    for (block_row = 0; block_row < block_rows; block_row++) {
-      buffer_ptr = buffer[block_row];
-      if (first_row && block_row == 0)
-	prev_block_row = buffer_ptr;
-      else
-	prev_block_row = buffer[block_row-1];
-      if (last_row && block_row == block_rows-1)
-	next_block_row = buffer_ptr;
-      else
-	next_block_row = buffer[block_row+1];
-      /* We fetch the surrounding DC values using a sliding-register approach.
-       * Initialize all nine here so as to do the right thing on narrow pics.
-       */
-      DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
-      DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
-      DC7 = DC8 = DC9 = (int) next_block_row[0][0];
-      output_col = 0;
-      last_block_column = compptr->width_in_blocks - 1;
-      for (block_num = 0; block_num <= last_block_column; block_num++) {
-	/* Fetch current DCT block into workspace so we can modify it. */
-	jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
-	/* Update DC values */
-	if (block_num < last_block_column) {
-	  DC3 = (int) prev_block_row[1][0];
-	  DC6 = (int) buffer_ptr[1][0];
-	  DC9 = (int) next_block_row[1][0];
-	}
-	/* Compute coefficient estimates per K.8.
-	 * An estimate is applied only if coefficient is still zero,
-	 * and is not known to be fully accurate.
-	 */
-	/* AC01 */
-	if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
-	  num = 36 * Q00 * (DC4 - DC6);
-	  if (num >= 0) {
-	    pred = (int) (((Q01<<7) + num) / (Q01<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	  } else {
-	    pred = (int) (((Q01<<7) - num) / (Q01<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	    pred = -pred;
-	  }
-	  workspace[1] = (JCOEF) pred;
-	}
-	/* AC10 */
-	if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
-	  num = 36 * Q00 * (DC2 - DC8);
-	  if (num >= 0) {
-	    pred = (int) (((Q10<<7) + num) / (Q10<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	  } else {
-	    pred = (int) (((Q10<<7) - num) / (Q10<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	    pred = -pred;
-	  }
-	  workspace[8] = (JCOEF) pred;
-	}
-	/* AC20 */
-	if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
-	  num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
-	  if (num >= 0) {
-	    pred = (int) (((Q20<<7) + num) / (Q20<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	  } else {
-	    pred = (int) (((Q20<<7) - num) / (Q20<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	    pred = -pred;
-	  }
-	  workspace[16] = (JCOEF) pred;
-	}
-	/* AC11 */
-	if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
-	  num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
-	  if (num >= 0) {
-	    pred = (int) (((Q11<<7) + num) / (Q11<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	  } else {
-	    pred = (int) (((Q11<<7) - num) / (Q11<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	    pred = -pred;
-	  }
-	  workspace[9] = (JCOEF) pred;
-	}
-	/* AC02 */
-	if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
-	  num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
-	  if (num >= 0) {
-	    pred = (int) (((Q02<<7) + num) / (Q02<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	  } else {
-	    pred = (int) (((Q02<<7) - num) / (Q02<<8));
-	    if (Al > 0 && pred >= (1<<Al))
-	      pred = (1<<Al)-1;
-	    pred = -pred;
-	  }
-	  workspace[2] = (JCOEF) pred;
-	}
-	/* OK, do the IDCT */
-	(*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
-			output_ptr, output_col);
-	/* Advance for next column */
-	DC1 = DC2; DC2 = DC3;
-	DC4 = DC5; DC5 = DC6;
-	DC7 = DC8; DC8 = DC9;
-	buffer_ptr++, prev_block_row++, next_block_row++;
-	output_col += compptr->DCT_scaled_size;
-      }
-      output_ptr += compptr->DCT_scaled_size;
-    }
-  }
-
-  if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
-    return JPEG_ROW_COMPLETED;
-  return JPEG_SCAN_COMPLETED;
-}
-
-#endif /* BLOCK_SMOOTHING_SUPPORTED */
-
-
-/*
- * Initialize coefficient buffer controller.
- */
-
-GLOBAL(void)
-jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
-{
-  my_coef_ptr coef;
-
-  coef = (my_coef_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_coef_controller));
-  cinfo->coef = (struct jpeg_d_coef_controller *) coef;
-  coef->pub.start_input_pass = start_input_pass;
-  coef->pub.start_output_pass = start_output_pass;
-#ifdef BLOCK_SMOOTHING_SUPPORTED
-  coef->coef_bits_latch = NULL;
-#endif
-
-  /* Create the coefficient buffer. */
-  if (need_full_buffer) {
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-    /* Allocate a full-image virtual array for each component, */
-    /* padded to a multiple of samp_factor DCT blocks in each direction. */
-    /* Note we ask for a pre-zeroed array. */
-    int ci, access_rows;
-    jpeg_component_info *compptr;
-
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      access_rows = compptr->v_samp_factor;
-#ifdef BLOCK_SMOOTHING_SUPPORTED
-      /* If block smoothing could be used, need a bigger window */
-      if (cinfo->progressive_mode)
-	access_rows *= 3;
-#endif
-      coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
-	 (JDIMENSION) jround_up((long) compptr->width_in_blocks,
-				(long) compptr->h_samp_factor),
-	 (JDIMENSION) jround_up((long) compptr->height_in_blocks,
-				(long) compptr->v_samp_factor),
-	 (JDIMENSION) access_rows);
-    }
-    coef->pub.consume_data = consume_data;
-    coef->pub.decompress_data = decompress_data;
-    coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
-#else
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-  } else {
-    /* We only need a single-MCU buffer. */
-    JBLOCKROW buffer;
-    int i;
-
-    buffer = (JBLOCKROW)
-      (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
-    for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
-      coef->MCU_buffer[i] = buffer + i;
-    }
-    coef->pub.consume_data = dummy_consume_data;
-    coef->pub.decompress_data = decompress_onepass;
-    coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdcolor.c ./Shared/jpeg-6b/jdcolor.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdcolor.c	Mon Dec  1 12:30:35 2003
+++ ./Shared/jpeg-6b/jdcolor.c	Wed Dec 31 19:00:00 1969
@@ -1,396 +0,0 @@
-/*
- * jdcolor.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains output colorspace conversion routines.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Private subobject */
-
-typedef struct {
-  struct jpeg_color_deconverter pub; /* public fields */
-
-  /* Private state for YCC->RGB conversion */
-  int * Cr_r_tab;		/* => table for Cr to R conversion */
-  int * Cb_b_tab;		/* => table for Cb to B conversion */
-  INT32 * Cr_g_tab;		/* => table for Cr to G conversion */
-  INT32 * Cb_g_tab;		/* => table for Cb to G conversion */
-} my_color_deconverter;
-
-typedef my_color_deconverter * my_cconvert_ptr;
-
-
-/**************** YCbCr -> RGB conversion: most common case **************/
-
-/*
- * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
- * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
- * The conversion equations to be implemented are therefore
- *	R = Y                + 1.40200 * Cr
- *	G = Y - 0.34414 * Cb - 0.71414 * Cr
- *	B = Y + 1.77200 * Cb
- * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
- * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
- *
- * To avoid floating-point arithmetic, we represent the fractional constants
- * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
- * the products by 2^16, with appropriate rounding, to get the correct answer.
- * Notice that Y, being an integral input, does not contribute any fraction
- * so it need not participate in the rounding.
- *
- * For even more speed, we avoid doing any multiplications in the inner loop
- * by precalculating the constants times Cb and Cr for all possible values.
- * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
- * for 12-bit samples it is still acceptable.  It's not very reasonable for
- * 16-bit samples, but if you want lossless storage you shouldn't be changing
- * colorspace anyway.
- * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
- * values for the G calculation are left scaled up, since we must add them
- * together before rounding.
- */
-
-#define SCALEBITS	16	/* speediest right-shift on some machines */
-#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
-#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
-
-
-/*
- * Initialize tables for YCC->RGB colorspace conversion.
- */
-
-LOCAL(void)
-build_ycc_rgb_table (j_decompress_ptr cinfo)
-{
-  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
-  int i;
-  INT32 x;
-  SHIFT_TEMPS
-
-  cconvert->Cr_r_tab = (int *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(int));
-  cconvert->Cb_b_tab = (int *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(int));
-  cconvert->Cr_g_tab = (INT32 *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(INT32));
-  cconvert->Cb_g_tab = (INT32 *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(INT32));
-
-  for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
-    /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
-    /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
-    /* Cr=>R value is nearest int to 1.40200 * x */
-    cconvert->Cr_r_tab[i] = (int)
-		    RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
-    /* Cb=>B value is nearest int to 1.77200 * x */
-    cconvert->Cb_b_tab[i] = (int)
-		    RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
-    /* Cr=>G value is scaled-up -0.71414 * x */
-    cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
-    /* Cb=>G value is scaled-up -0.34414 * x */
-    /* We also add in ONE_HALF so that need not do it in inner loop */
-    cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
-  }
-}
-
-
-/*
- * Convert some rows of samples to the output colorspace.
- *
- * Note that we change from noninterleaved, one-plane-per-component format
- * to interleaved-pixel format.  The output buffer is therefore three times
- * as wide as the input buffer.
- * A starting row offset is provided only for the input buffer.  The caller
- * can easily adjust the passed output_buf value to accommodate any row
- * offset required on that side.
- */
-
-METHODDEF(void)
-ycc_rgb_convert (j_decompress_ptr cinfo,
-		 JSAMPIMAGE input_buf, JDIMENSION input_row,
-		 JSAMPARRAY output_buf, int num_rows)
-{
-  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
-  register int y, cb, cr;
-  register JSAMPROW outptr;
-  register JSAMPROW inptr0, inptr1, inptr2;
-  register JDIMENSION col;
-  JDIMENSION num_cols = cinfo->output_width;
-  /* copy these pointers into registers if possible */
-  register JSAMPLE * range_limit = cinfo->sample_range_limit;
-  register int * Crrtab = cconvert->Cr_r_tab;
-  register int * Cbbtab = cconvert->Cb_b_tab;
-  register INT32 * Crgtab = cconvert->Cr_g_tab;
-  register INT32 * Cbgtab = cconvert->Cb_g_tab;
-  SHIFT_TEMPS
-
-  while (--num_rows >= 0) {
-    inptr0 = input_buf[0][input_row];
-    inptr1 = input_buf[1][input_row];
-    inptr2 = input_buf[2][input_row];
-    input_row++;
-    outptr = *output_buf++;
-    for (col = 0; col < num_cols; col++) {
-      y  = GETJSAMPLE(inptr0[col]);
-      cb = GETJSAMPLE(inptr1[col]);
-      cr = GETJSAMPLE(inptr2[col]);
-      /* Range-limiting is essential due to noise introduced by DCT losses. */
-      outptr[RGB_RED] =   range_limit[y + Crrtab[cr]];
-      outptr[RGB_GREEN] = range_limit[y +
-			      ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
-						 SCALEBITS))];
-      outptr[RGB_BLUE] =  range_limit[y + Cbbtab[cb]];
-      outptr += RGB_PIXELSIZE;
-    }
-  }
-}
-
-
-/**************** Cases other than YCbCr -> RGB **************/
-
-
-/*
- * Color conversion for no colorspace change: just copy the data,
- * converting from separate-planes to interleaved representation.
- */
-
-METHODDEF(void)
-null_convert (j_decompress_ptr cinfo,
-	      JSAMPIMAGE input_buf, JDIMENSION input_row,
-	      JSAMPARRAY output_buf, int num_rows)
-{
-  register JSAMPROW inptr, outptr;
-  register JDIMENSION count;
-  register int num_components = cinfo->num_components;
-  JDIMENSION num_cols = cinfo->output_width;
-  int ci;
-
-  while (--num_rows >= 0) {
-    for (ci = 0; ci < num_components; ci++) {
-      inptr = input_buf[ci][input_row];
-      outptr = output_buf[0] + ci;
-      for (count = num_cols; count > 0; count--) {
-	*outptr = *inptr++;	/* needn't bother with GETJSAMPLE() here */
-	outptr += num_components;
-      }
-    }
-    input_row++;
-    output_buf++;
-  }
-}
-
-
-/*
- * Color conversion for grayscale: just copy the data.
- * This also works for YCbCr -> grayscale conversion, in which
- * we just copy the Y (luminance) component and ignore chrominance.
- */
-
-METHODDEF(void)
-grayscale_convert (j_decompress_ptr cinfo,
-		   JSAMPIMAGE input_buf, JDIMENSION input_row,
-		   JSAMPARRAY output_buf, int num_rows)
-{
-  jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
-		    num_rows, cinfo->output_width);
-}
-
-
-/*
- * Convert grayscale to RGB: just duplicate the graylevel three times.
- * This is provided to support applications that don't want to cope
- * with grayscale as a separate case.
- */
-
-METHODDEF(void)
-gray_rgb_convert (j_decompress_ptr cinfo,
-		  JSAMPIMAGE input_buf, JDIMENSION input_row,
-		  JSAMPARRAY output_buf, int num_rows)
-{
-  register JSAMPROW inptr, outptr;
-  register JDIMENSION col;
-  JDIMENSION num_cols = cinfo->output_width;
-
-  while (--num_rows >= 0) {
-    inptr = input_buf[0][input_row++];
-    outptr = *output_buf++;
-    for (col = 0; col < num_cols; col++) {
-      /* We can dispense with GETJSAMPLE() here */
-      outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
-      outptr += RGB_PIXELSIZE;
-    }
-  }
-}
-
-
-/*
- * Adobe-style YCCK->CMYK conversion.
- * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
- * conversion as above, while passing K (black) unchanged.
- * We assume build_ycc_rgb_table has been called.
- */
-
-METHODDEF(void)
-ycck_cmyk_convert (j_decompress_ptr cinfo,
-		   JSAMPIMAGE input_buf, JDIMENSION input_row,
-		   JSAMPARRAY output_buf, int num_rows)
-{
-  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
-  register int y, cb, cr;
-  register JSAMPROW outptr;
-  register JSAMPROW inptr0, inptr1, inptr2, inptr3;
-  register JDIMENSION col;
-  JDIMENSION num_cols = cinfo->output_width;
-  /* copy these pointers into registers if possible */
-  register JSAMPLE * range_limit = cinfo->sample_range_limit;
-  register int * Crrtab = cconvert->Cr_r_tab;
-  register int * Cbbtab = cconvert->Cb_b_tab;
-  register INT32 * Crgtab = cconvert->Cr_g_tab;
-  register INT32 * Cbgtab = cconvert->Cb_g_tab;
-  SHIFT_TEMPS
-
-  while (--num_rows >= 0) {
-    inptr0 = input_buf[0][input_row];
-    inptr1 = input_buf[1][input_row];
-    inptr2 = input_buf[2][input_row];
-    inptr3 = input_buf[3][input_row];
-    input_row++;
-    outptr = *output_buf++;
-    for (col = 0; col < num_cols; col++) {
-      y  = GETJSAMPLE(inptr0[col]);
-      cb = GETJSAMPLE(inptr1[col]);
-      cr = GETJSAMPLE(inptr2[col]);
-      /* Range-limiting is essential due to noise introduced by DCT losses. */
-      outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])];	/* red */
-      outptr[1] = range_limit[MAXJSAMPLE - (y +			/* green */
-			      ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
-						 SCALEBITS)))];
-      outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])];	/* blue */
-      /* K passes through unchanged */
-      outptr[3] = inptr3[col];	/* don't need GETJSAMPLE here */
-      outptr += 4;
-    }
-  }
-}
-
-
-/*
- * Empty method for start_pass.
- */
-
-METHODDEF(void)
-start_pass_dcolor (j_decompress_ptr cinfo)
-{
-  /* no work needed */
-}
-
-
-/*
- * Module initialization routine for output colorspace conversion.
- */
-
-GLOBAL(void)
-jinit_color_deconverter (j_decompress_ptr cinfo)
-{
-  my_cconvert_ptr cconvert;
-  int ci;
-
-  cconvert = (my_cconvert_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_color_deconverter));
-  cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
-  cconvert->pub.start_pass = start_pass_dcolor;
-
-  /* Make sure num_components agrees with jpeg_color_space */
-  switch (cinfo->jpeg_color_space) {
-  case JCS_GRAYSCALE:
-    if (cinfo->num_components != 1)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    break;
-
-  case JCS_RGB:
-  case JCS_YCbCr:
-    if (cinfo->num_components != 3)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    break;
-
-  case JCS_CMYK:
-  case JCS_YCCK:
-    if (cinfo->num_components != 4)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    break;
-
-  default:			/* JCS_UNKNOWN can be anything */
-    if (cinfo->num_components < 1)
-      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
-    break;
-  }
-
-  /* Set out_color_components and conversion method based on requested space.
-   * Also clear the component_needed flags for any unused components,
-   * so that earlier pipeline stages can avoid useless computation.
-   */
-
-  switch (cinfo->out_color_space) {
-  case JCS_GRAYSCALE:
-    cinfo->out_color_components = 1;
-    if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
-	cinfo->jpeg_color_space == JCS_YCbCr) {
-      cconvert->pub.color_convert = grayscale_convert;
-      /* For color->grayscale conversion, only the Y (0) component is needed */
-      for (ci = 1; ci < cinfo->num_components; ci++)
-	cinfo->comp_info[ci].component_needed = FALSE;
-    } else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  case JCS_RGB:
-    cinfo->out_color_components = RGB_PIXELSIZE;
-    if (cinfo->jpeg_color_space == JCS_YCbCr) {
-      cconvert->pub.color_convert = ycc_rgb_convert;
-      build_ycc_rgb_table(cinfo);
-    } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
-      cconvert->pub.color_convert = gray_rgb_convert;
-    } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
-      cconvert->pub.color_convert = null_convert;
-    } else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  case JCS_CMYK:
-    cinfo->out_color_components = 4;
-    if (cinfo->jpeg_color_space == JCS_YCCK) {
-      cconvert->pub.color_convert = ycck_cmyk_convert;
-      build_ycc_rgb_table(cinfo);
-    } else if (cinfo->jpeg_color_space == JCS_CMYK) {
-      cconvert->pub.color_convert = null_convert;
-    } else
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-
-  default:
-    /* Permit null conversion to same output space */
-    if (cinfo->out_color_space == cinfo->jpeg_color_space) {
-      cinfo->out_color_components = cinfo->num_components;
-      cconvert->pub.color_convert = null_convert;
-    } else			/* unsupported non-null conversion */
-      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
-    break;
-  }
-
-  if (cinfo->quantize_colors)
-    cinfo->output_components = 1; /* single colormapped output component */
-  else
-    cinfo->output_components = cinfo->out_color_components;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdct.h ./Shared/jpeg-6b/jdct.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdct.h	Mon Dec  1 12:30:35 2003
+++ ./Shared/jpeg-6b/jdct.h	Wed Dec 31 19:00:00 1969
@@ -1,176 +0,0 @@
-/*
- * jdct.h
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This include file contains common declarations for the forward and
- * inverse DCT modules.  These declarations are private to the DCT managers
- * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms.
- * The individual DCT algorithms are kept in separate files to ease 
- * machine-dependent tuning (e.g., assembly coding).
- */
-
-
-/*
- * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
- * the DCT is to be performed in-place in that buffer.  Type DCTELEM is int
- * for 8-bit samples, INT32 for 12-bit samples.  (NOTE: Floating-point DCT
- * implementations use an array of type FAST_FLOAT, instead.)
- * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
- * The DCT outputs are returned scaled up by a factor of 8; they therefore
- * have a range of +-8K for 8-bit data, +-128K for 12-bit data.  This
- * convention improves accuracy in integer implementations and saves some
- * work in floating-point ones.
- * Quantization of the output coefficients is done by jcdctmgr.c.
- */
-
-#if BITS_IN_JSAMPLE == 8
-typedef int DCTELEM;		/* 16 or 32 bits is fine */
-#else
-typedef INT32 DCTELEM;		/* must have 32 bits */
-#endif
-
-typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
-typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
-
-
-/*
- * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
- * to an output sample array.  The routine must dequantize the input data as
- * well as perform the IDCT; for dequantization, it uses the multiplier table
- * pointed to by compptr->dct_table.  The output data is to be placed into the
- * sample array starting at a specified column.  (Any row offset needed will
- * be applied to the array pointer before it is passed to the IDCT code.)
- * Note that the number of samples emitted by the IDCT routine is
- * DCT_scaled_size * DCT_scaled_size.
- */
-
-/* typedef inverse_DCT_method_ptr is declared in jpegint.h */
-
-/*
- * Each IDCT routine has its own ideas about the best dct_table element type.
- */
-
-typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
-#if BITS_IN_JSAMPLE == 8
-typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
-#define IFAST_SCALE_BITS  2	/* fractional bits in scale factors */
-#else
-typedef INT32 IFAST_MULT_TYPE;	/* need 32 bits for scaled quantizers */
-#define IFAST_SCALE_BITS  13	/* fractional bits in scale factors */
-#endif
-typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
-
-
-/*
- * Each IDCT routine is responsible for range-limiting its results and
- * converting them to unsigned form (0..MAXJSAMPLE).  The raw outputs could
- * be quite far out of range if the input data is corrupt, so a bulletproof
- * range-limiting step is required.  We use a mask-and-table-lookup method
- * to do the combined operations quickly.  See the comments with
- * prepare_range_limit_table (in jdmaster.c) for more info.
- */
-
-#define IDCT_range_limit(cinfo)  ((cinfo)->sample_range_limit + CENTERJSAMPLE)
-
-#define RANGE_MASK  (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
-
-
-/* Short forms of external names for systems with brain-damaged linkers. */
-
-#ifdef NEED_SHORT_EXTERNAL_NAMES
-#define jpeg_fdct_islow		jFDislow
-#define jpeg_fdct_ifast		jFDifast
-#define jpeg_fdct_float		jFDfloat
-#define jpeg_idct_islow		jRDislow
-#define jpeg_idct_ifast		jRDifast
-#define jpeg_idct_float		jRDfloat
-#define jpeg_idct_4x4		jRD4x4
-#define jpeg_idct_2x2		jRD2x2
-#define jpeg_idct_1x1		jRD1x1
-#endif /* NEED_SHORT_EXTERNAL_NAMES */
-
-/* Extern declarations for the forward and inverse DCT routines. */
-
-EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
-EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
-EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
-
-EXTERN(void) jpeg_idct_islow
-    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
-EXTERN(void) jpeg_idct_ifast
-    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
-EXTERN(void) jpeg_idct_float
-    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
-EXTERN(void) jpeg_idct_4x4
-    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
-EXTERN(void) jpeg_idct_2x2
-    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
-EXTERN(void) jpeg_idct_1x1
-    JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	 JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
-
-
-/*
- * Macros for handling fixed-point arithmetic; these are used by many
- * but not all of the DCT/IDCT modules.
- *
- * All values are expected to be of type INT32.
- * Fractional constants are scaled left by CONST_BITS bits.
- * CONST_BITS is defined within each module using these macros,
- * and may differ from one module to the next.
- */
-
-#define ONE	((INT32) 1)
-#define CONST_SCALE (ONE << CONST_BITS)
-
-/* Convert a positive real constant to an integer scaled by CONST_SCALE.
- * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
- * thus causing a lot of useless floating-point operations at run time.
- */
-
-#define FIX(x)	((INT32) ((x) * CONST_SCALE + 0.5))
-
-/* Descale and correctly round an INT32 value that's scaled by N bits.
- * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
- * the fudge factor is correct for either sign of X.
- */
-
-#define DESCALE(x,n)  RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
-
-/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
- * This macro is used only when the two inputs will actually be no more than
- * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
- * full 32x32 multiply.  This provides a useful speedup on many machines.
- * Unfortunately there is no way to specify a 16x16->32 multiply portably
- * in C, but some C compilers will do the right thing if you provide the
- * correct combination of casts.
- */
-
-#ifdef SHORTxSHORT_32		/* may work if 'int' is 32 bits */
-#define MULTIPLY16C16(var,const)  (((INT16) (var)) * ((INT16) (const)))
-#endif
-#ifdef SHORTxLCONST_32		/* known to work with Microsoft C 6.0 */
-#define MULTIPLY16C16(var,const)  (((INT16) (var)) * ((INT32) (const)))
-#endif
-
-#ifndef MULTIPLY16C16		/* default definition */
-#define MULTIPLY16C16(var,const)  ((var) * (const))
-#endif
-
-/* Same except both inputs are variables. */
-
-#ifdef SHORTxSHORT_32		/* may work if 'int' is 32 bits */
-#define MULTIPLY16V16(var1,var2)  (((INT16) (var1)) * ((INT16) (var2)))
-#endif
-
-#ifndef MULTIPLY16V16		/* default definition */
-#define MULTIPLY16V16(var1,var2)  ((var1) * (var2))
-#endif
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jddctmgr.c ./Shared/jpeg-6b/jddctmgr.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jddctmgr.c	Mon Dec  1 12:30:35 2003
+++ ./Shared/jpeg-6b/jddctmgr.c	Wed Dec 31 19:00:00 1969
@@ -1,269 +0,0 @@
-/*
- * jddctmgr.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the inverse-DCT management logic.
- * This code selects a particular IDCT implementation to be used,
- * and it performs related housekeeping chores.  No code in this file
- * is executed per IDCT step, only during output pass setup.
- *
- * Note that the IDCT routines are responsible for performing coefficient
- * dequantization as well as the IDCT proper.  This module sets up the
- * dequantization multiplier table needed by the IDCT routine.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-
-/*
- * The decompressor input side (jdinput.c) saves away the appropriate
- * quantization table for each component at the start of the first scan
- * involving that component.  (This is necessary in order to correctly
- * decode files that reuse Q-table slots.)
- * When we are ready to make an output pass, the saved Q-table is converted
- * to a multiplier table that will actually be used by the IDCT routine.
- * The multiplier table contents are IDCT-method-dependent.  To support
- * application changes in IDCT method between scans, we can remake the
- * multiplier tables if necessary.
- * In buffered-image mode, the first output pass may occur before any data
- * has been seen for some components, and thus before their Q-tables have
- * been saved away.  To handle this case, multiplier tables are preset
- * to zeroes; the result of the IDCT will be a neutral gray level.
- */
-
-
-/* Private subobject for this module */
-
-typedef struct {
-  struct jpeg_inverse_dct pub;	/* public fields */
-
-  /* This array contains the IDCT method code that each multiplier table
-   * is currently set up for, or -1 if it's not yet set up.
-   * The actual multiplier tables are pointed to by dct_table in the
-   * per-component comp_info structures.
-   */
-  int cur_method[MAX_COMPONENTS];
-} my_idct_controller;
-
-typedef my_idct_controller * my_idct_ptr;
-
-
-/* Allocated multiplier tables: big enough for any supported variant */
-
-typedef union {
-  ISLOW_MULT_TYPE islow_array[DCTSIZE2];
-#ifdef DCT_IFAST_SUPPORTED
-  IFAST_MULT_TYPE ifast_array[DCTSIZE2];
-#endif
-#ifdef DCT_FLOAT_SUPPORTED
-  FLOAT_MULT_TYPE float_array[DCTSIZE2];
-#endif
-} multiplier_table;
-
-
-/* The current scaled-IDCT routines require ISLOW-style multiplier tables,
- * so be sure to compile that code if either ISLOW or SCALING is requested.
- */
-#ifdef DCT_ISLOW_SUPPORTED
-#define PROVIDE_ISLOW_TABLES
-#else
-#ifdef IDCT_SCALING_SUPPORTED
-#define PROVIDE_ISLOW_TABLES
-#endif
-#endif
-
-
-/*
- * Prepare for an output pass.
- * Here we select the proper IDCT routine for each component and build
- * a matching multiplier table.
- */
-
-METHODDEF(void)
-start_pass (j_decompress_ptr cinfo)
-{
-  my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
-  int ci, i;
-  jpeg_component_info *compptr;
-  int method = 0;
-  inverse_DCT_method_ptr method_ptr = NULL;
-  JQUANT_TBL * qtbl;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Select the proper IDCT routine for this component's scaling */
-    switch (compptr->DCT_scaled_size) {
-#ifdef IDCT_SCALING_SUPPORTED
-    case 1:
-      method_ptr = jpeg_idct_1x1;
-      method = JDCT_ISLOW;	/* jidctred uses islow-style table */
-      break;
-    case 2:
-      method_ptr = jpeg_idct_2x2;
-      method = JDCT_ISLOW;	/* jidctred uses islow-style table */
-      break;
-    case 4:
-      method_ptr = jpeg_idct_4x4;
-      method = JDCT_ISLOW;	/* jidctred uses islow-style table */
-      break;
-#endif
-    case DCTSIZE:
-      switch (cinfo->dct_method) {
-#ifdef DCT_ISLOW_SUPPORTED
-      case JDCT_ISLOW:
-	method_ptr = jpeg_idct_islow;
-	method = JDCT_ISLOW;
-	break;
-#endif
-#ifdef DCT_IFAST_SUPPORTED
-      case JDCT_IFAST:
-	method_ptr = jpeg_idct_ifast;
-	method = JDCT_IFAST;
-	break;
-#endif
-#ifdef DCT_FLOAT_SUPPORTED
-      case JDCT_FLOAT:
-	method_ptr = jpeg_idct_float;
-	method = JDCT_FLOAT;
-	break;
-#endif
-      default:
-	ERREXIT(cinfo, JERR_NOT_COMPILED);
-	break;
-      }
-      break;
-    default:
-      ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
-      break;
-    }
-    idct->pub.inverse_DCT[ci] = method_ptr;
-    /* Create multiplier table from quant table.
-     * However, we can skip this if the component is uninteresting
-     * or if we already built the table.  Also, if no quant table
-     * has yet been saved for the component, we leave the
-     * multiplier table all-zero; we'll be reading zeroes from the
-     * coefficient controller's buffer anyway.
-     */
-    if (! compptr->component_needed || idct->cur_method[ci] == method)
-      continue;
-    qtbl = compptr->quant_table;
-    if (qtbl == NULL)		/* happens if no data yet for component */
-      continue;
-    idct->cur_method[ci] = method;
-    switch (method) {
-#ifdef PROVIDE_ISLOW_TABLES
-    case JDCT_ISLOW:
-      {
-	/* For LL&M IDCT method, multipliers are equal to raw quantization
-	 * coefficients, but are stored as ints to ensure access efficiency.
-	 */
-	ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
-	for (i = 0; i < DCTSIZE2; i++) {
-	  ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
-	}
-      }
-      break;
-#endif
-#ifdef DCT_IFAST_SUPPORTED
-    case JDCT_IFAST:
-      {
-	/* For AA&N IDCT method, multipliers are equal to quantization
-	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
-	 *   scalefactor[0] = 1
-	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
-	 * For integer operation, the multiplier table is to be scaled by
-	 * IFAST_SCALE_BITS.
-	 */
-	IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
-#define CONST_BITS 14
-	static const INT16 aanscales[DCTSIZE2] = {
-	  /* precomputed values scaled up by 14 bits */
-	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
-	  22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
-	  21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
-	  19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
-	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
-	  12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
-	   8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
-	   4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
-	};
-	SHIFT_TEMPS
-
-	for (i = 0; i < DCTSIZE2; i++) {
-	  ifmtbl[i] = (IFAST_MULT_TYPE)
-	    DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
-				  (INT32) aanscales[i]),
-		    CONST_BITS-IFAST_SCALE_BITS);
-	}
-      }
-      break;
-#endif
-#ifdef DCT_FLOAT_SUPPORTED
-    case JDCT_FLOAT:
-      {
-	/* For float AA&N IDCT method, multipliers are equal to quantization
-	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
-	 *   scalefactor[0] = 1
-	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
-	 */
-	FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
-	int row, col;
-	static const double aanscalefactor[DCTSIZE] = {
-	  1.0, 1.387039845, 1.306562965, 1.175875602,
-	  1.0, 0.785694958, 0.541196100, 0.275899379
-	};
-
-	i = 0;
-	for (row = 0; row < DCTSIZE; row++) {
-	  for (col = 0; col < DCTSIZE; col++) {
-	    fmtbl[i] = (FLOAT_MULT_TYPE)
-	      ((double) qtbl->quantval[i] *
-	       aanscalefactor[row] * aanscalefactor[col]);
-	    i++;
-	  }
-	}
-      }
-      break;
-#endif
-    default:
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-      break;
-    }
-  }
-}
-
-
-/*
- * Initialize IDCT manager.
- */
-
-GLOBAL(void)
-jinit_inverse_dct (j_decompress_ptr cinfo)
-{
-  my_idct_ptr idct;
-  int ci;
-  jpeg_component_info *compptr;
-
-  idct = (my_idct_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_idct_controller));
-  cinfo->idct = (struct jpeg_inverse_dct *) idct;
-  idct->pub.start_pass = start_pass;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Allocate and pre-zero a multiplier table for each component */
-    compptr->dct_table =
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(multiplier_table));
-    MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
-    /* Mark multiplier table not yet set up for any method */
-    idct->cur_method[ci] = -1;
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdhuff.c ./Shared/jpeg-6b/jdhuff.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdhuff.c	Mon Dec  1 12:30:35 2003
+++ ./Shared/jpeg-6b/jdhuff.c	Wed Dec 31 19:00:00 1969
@@ -1,651 +0,0 @@
-/*
- * jdhuff.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains Huffman entropy decoding routines.
- *
- * Much of the complexity here has to do with supporting input suspension.
- * If the data source module demands suspension, we want to be able to back
- * up to the start of the current MCU.  To do this, we copy state variables
- * into local working storage, and update them back to the permanent
- * storage only upon successful completion of an MCU.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdhuff.h"		/* Declarations shared with jdphuff.c */
-
-
-/*
- * Expanded entropy decoder object for Huffman decoding.
- *
- * The savable_state subrecord contains fields that change within an MCU,
- * but must not be updated permanently until we complete the MCU.
- */
-
-typedef struct {
-  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
-} savable_state;
-
-/* This macro is to work around compilers with missing or broken
- * structure assignment.  You'll need to fix this code if you have
- * such a compiler and you change MAX_COMPS_IN_SCAN.
- */
-
-#ifndef NO_STRUCT_ASSIGN
-#define ASSIGN_STATE(dest,src)  ((dest) = (src))
-#else
-#if MAX_COMPS_IN_SCAN == 4
-#define ASSIGN_STATE(dest,src)  \
-	((dest).last_dc_val[0] = (src).last_dc_val[0], \
-	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
-	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
-	 (dest).last_dc_val[3] = (src).last_dc_val[3])
-#endif
-#endif
-
-
-typedef struct {
-  struct jpeg_entropy_decoder pub; /* public fields */
-
-  /* These fields are loaded into local variables at start of each MCU.
-   * In case of suspension, we exit WITHOUT updating them.
-   */
-  bitread_perm_state bitstate;	/* Bit buffer at start of MCU */
-  savable_state saved;		/* Other state at start of MCU */
-
-  /* These fields are NOT loaded into local working state. */
-  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
-
-  /* Pointers to derived tables (these workspaces have image lifespan) */
-  d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
-  d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
-
-  /* Precalculated info set up by start_pass for use in decode_mcu: */
-
-  /* Pointers to derived tables to be used for each block within an MCU */
-  d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
-  d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
-  /* Whether we care about the DC and AC coefficient values for each block */
-  boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
-  boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
-} huff_entropy_decoder;
-
-typedef huff_entropy_decoder * huff_entropy_ptr;
-
-
-/*
- * Initialize for a Huffman-compressed scan.
- */
-
-METHODDEF(void)
-start_pass_huff_decoder (j_decompress_ptr cinfo)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  int ci, blkn, dctbl, actbl;
-  jpeg_component_info * compptr;
-
-  /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
-   * This ought to be an error condition, but we make it a warning because
-   * there are some baseline files out there with all zeroes in these bytes.
-   */
-  if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
-      cinfo->Ah != 0 || cinfo->Al != 0)
-    WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
-
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    dctbl = compptr->dc_tbl_no;
-    actbl = compptr->ac_tbl_no;
-    /* Compute derived values for Huffman tables */
-    /* We may do this more than once for a table, but it's not expensive */
-    jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
-			    & entropy->dc_derived_tbls[dctbl]);
-    jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
-			    & entropy->ac_derived_tbls[actbl]);
-    /* Initialize DC predictions to 0 */
-    entropy->saved.last_dc_val[ci] = 0;
-  }
-
-  /* Precalculate decoding info for each block in an MCU of this scan */
-  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-    ci = cinfo->MCU_membership[blkn];
-    compptr = cinfo->cur_comp_info[ci];
-    /* Precalculate which table to use for each block */
-    entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
-    entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
-    /* Decide whether we really care about the coefficient values */
-    if (compptr->component_needed) {
-      entropy->dc_needed[blkn] = TRUE;
-      /* we don't need the ACs if producing a 1/8th-size image */
-      entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
-    } else {
-      entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
-    }
-  }
-
-  /* Initialize bitread state variables */
-  entropy->bitstate.bits_left = 0;
-  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
-  entropy->pub.insufficient_data = FALSE;
-
-  /* Initialize restart counter */
-  entropy->restarts_to_go = cinfo->restart_interval;
-}
-
-
-/*
- * Compute the derived values for a Huffman table.
- * This routine also performs some validation checks on the table.
- *
- * Note this is also used by jdphuff.c.
- */
-
-GLOBAL(void)
-jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
-			 d_derived_tbl ** pdtbl)
-{
-  JHUFF_TBL *htbl;
-  d_derived_tbl *dtbl;
-  int p, i, l, si, numsymbols;
-  int lookbits, ctr;
-  char huffsize[257];
-  unsigned int huffcode[257];
-  unsigned int code;
-
-  /* Note that huffsize[] and huffcode[] are filled in code-length order,
-   * paralleling the order of the symbols themselves in htbl->huffval[].
-   */
-
-  /* Find the input Huffman table */
-  if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
-    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
-  htbl =
-    isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
-  if (htbl == NULL)
-    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
-
-  /* Allocate a workspace if we haven't already done so. */
-  if (*pdtbl == NULL)
-    *pdtbl = (d_derived_tbl *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(d_derived_tbl));
-  dtbl = *pdtbl;
-  dtbl->pub = htbl;		/* fill in back link */
-  
-  /* Figure C.1: make table of Huffman code length for each symbol */
-
-  p = 0;
-  for (l = 1; l <= 16; l++) {
-    i = (int) htbl->bits[l];
-    if (i < 0 || p + i > 256)	/* protect against table overrun */
-      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-    while (i--)
-      huffsize[p++] = (char) l;
-  }
-  huffsize[p] = 0;
-  numsymbols = p;
-  
-  /* Figure C.2: generate the codes themselves */
-  /* We also validate that the counts represent a legal Huffman code tree. */
-  
-  code = 0;
-  si = huffsize[0];
-  p = 0;
-  while (huffsize[p]) {
-    while (((int) huffsize[p]) == si) {
-      huffcode[p++] = code;
-      code++;
-    }
-    /* code is now 1 more than the last code used for codelength si; but
-     * it must still fit in si bits, since no code is allowed to be all ones.
-     */
-    if (((INT32) code) >= (((INT32) 1) << si))
-      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-    code <<= 1;
-    si++;
-  }
-
-  /* Figure F.15: generate decoding tables for bit-sequential decoding */
-
-  p = 0;
-  for (l = 1; l <= 16; l++) {
-    if (htbl->bits[l]) {
-      /* valoffset[l] = huffval[] index of 1st symbol of code length l,
-       * minus the minimum code of length l
-       */
-      dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
-      p += htbl->bits[l];
-      dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
-    } else {
-      dtbl->maxcode[l] = -1;	/* -1 if no codes of this length */
-    }
-  }
-  dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
-
-  /* Compute lookahead tables to speed up decoding.
-   * First we set all the table entries to 0, indicating "too long";
-   * then we iterate through the Huffman codes that are short enough and
-   * fill in all the entries that correspond to bit sequences starting
-   * with that code.
-   */
-
-  MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
-
-  p = 0;
-  for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
-    for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
-      /* l = current code's length, p = its index in huffcode[] & huffval[]. */
-      /* Generate left-justified code followed by all possible bit sequences */
-      lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
-      for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
-	dtbl->look_nbits[lookbits] = l;
-	dtbl->look_sym[lookbits] = htbl->huffval[p];
-	lookbits++;
-      }
-    }
-  }
-
-  /* Validate symbols as being reasonable.
-   * For AC tables, we make no check, but accept all byte values 0..255.
-   * For DC tables, we require the symbols to be in range 0..15.
-   * (Tighter bounds could be applied depending on the data depth and mode,
-   * but this is sufficient to ensure safe decoding.)
-   */
-  if (isDC) {
-    for (i = 0; i < numsymbols; i++) {
-      int sym = htbl->huffval[i];
-      if (sym < 0 || sym > 15)
-	ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-    }
-  }
-}
-
-
-/*
- * Out-of-line code for bit fetching (shared with jdphuff.c).
- * See jdhuff.h for info about usage.
- * Note: current values of get_buffer and bits_left are passed as parameters,
- * but are returned in the corresponding fields of the state struct.
- *
- * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
- * of get_buffer to be used.  (On machines with wider words, an even larger
- * buffer could be used.)  However, on some machines 32-bit shifts are
- * quite slow and take time proportional to the number of places shifted.
- * (This is true with most PC compilers, for instance.)  In this case it may
- * be a win to set MIN_GET_BITS to the minimum value of 15.  This reduces the
- * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
- */
-
-#ifdef SLOW_SHIFT_32
-#define MIN_GET_BITS  15	/* minimum allowable value */
-#else
-#define MIN_GET_BITS  (BIT_BUF_SIZE-7)
-#endif
-
-
-GLOBAL(boolean)
-jpeg_fill_bit_buffer (bitread_working_state * state,
-		      register bit_buf_type get_buffer, register int bits_left,
-		      int nbits)
-/* Load up the bit buffer to a depth of at least nbits */
-{
-  /* Copy heavily used state fields into locals (hopefully registers) */
-  register const JOCTET * next_input_byte = state->next_input_byte;
-  register size_t bytes_in_buffer = state->bytes_in_buffer;
-  j_decompress_ptr cinfo = state->cinfo;
-
-  /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
-  /* (It is assumed that no request will be for more than that many bits.) */
-  /* We fail to do so only if we hit a marker or are forced to suspend. */
-
-  if (cinfo->unread_marker == 0) {	/* cannot advance past a marker */
-    while (bits_left < MIN_GET_BITS) {
-      register int c;
-
-      /* Attempt to read a byte */
-      if (bytes_in_buffer == 0) {
-	if (! (*cinfo->src->fill_input_buffer) (cinfo))
-	  return FALSE;
-	next_input_byte = cinfo->src->next_input_byte;
-	bytes_in_buffer = cinfo->src->bytes_in_buffer;
-      }
-      bytes_in_buffer--;
-      c = GETJOCTET(*next_input_byte++);
-
-      /* If it's 0xFF, check and discard stuffed zero byte */
-      if (c == 0xFF) {
-	/* Loop here to discard any padding FF's on terminating marker,
-	 * so that we can save a valid unread_marker value.  NOTE: we will
-	 * accept multiple FF's followed by a 0 as meaning a single FF data
-	 * byte.  This data pattern is not valid according to the standard.
-	 */
-	do {
-	  if (bytes_in_buffer == 0) {
-	    if (! (*cinfo->src->fill_input_buffer) (cinfo))
-	      return FALSE;
-	    next_input_byte = cinfo->src->next_input_byte;
-	    bytes_in_buffer = cinfo->src->bytes_in_buffer;
-	  }
-	  bytes_in_buffer--;
-	  c = GETJOCTET(*next_input_byte++);
-	} while (c == 0xFF);
-
-	if (c == 0) {
-	  /* Found FF/00, which represents an FF data byte */
-	  c = 0xFF;
-	} else {
-	  /* Oops, it's actually a marker indicating end of compressed data.
-	   * Save the marker code for later use.
-	   * Fine point: it might appear that we should save the marker into
-	   * bitread working state, not straight into permanent state.  But
-	   * once we have hit a marker, we cannot need to suspend within the
-	   * current MCU, because we will read no more bytes from the data
-	   * source.  So it is OK to update permanent state right away.
-	   */
-	  cinfo->unread_marker = c;
-	  /* See if we need to insert some fake zero bits. */
-	  goto no_more_bytes;
-	}
-      }
-
-      /* OK, load c into get_buffer */
-      get_buffer = (get_buffer << 8) | c;
-      bits_left += 8;
-    } /* end while */
-  } else {
-  no_more_bytes:
-    /* We get here if we've read the marker that terminates the compressed
-     * data segment.  There should be enough bits in the buffer register
-     * to satisfy the request; if so, no problem.
-     */
-    if (nbits > bits_left) {
-      /* Uh-oh.  Report corrupted data to user and stuff zeroes into
-       * the data stream, so that we can produce some kind of image.
-       * We use a nonvolatile flag to ensure that only one warning message
-       * appears per data segment.
-       */
-      if (! cinfo->entropy->insufficient_data) {
-	WARNMS(cinfo, JWRN_HIT_MARKER);
-	cinfo->entropy->insufficient_data = TRUE;
-      }
-      /* Fill the buffer with zero bits */
-      get_buffer <<= MIN_GET_BITS - bits_left;
-      bits_left = MIN_GET_BITS;
-    }
-  }
-
-  /* Unload the local registers */
-  state->next_input_byte = next_input_byte;
-  state->bytes_in_buffer = bytes_in_buffer;
-  state->get_buffer = get_buffer;
-  state->bits_left = bits_left;
-
-  return TRUE;
-}
-
-
-/*
- * Out-of-line code for Huffman code decoding.
- * See jdhuff.h for info about usage.
- */
-
-GLOBAL(int)
-jpeg_huff_decode (bitread_working_state * state,
-		  register bit_buf_type get_buffer, register int bits_left,
-		  d_derived_tbl * htbl, int min_bits)
-{
-  register int l = min_bits;
-  register INT32 code;
-
-  /* HUFF_DECODE has determined that the code is at least min_bits */
-  /* bits long, so fetch that many bits in one swoop. */
-
-  CHECK_BIT_BUFFER(*state, l, return -1);
-  code = GET_BITS(l);
-
-  /* Collect the rest of the Huffman code one bit at a time. */
-  /* This is per Figure F.16 in the JPEG spec. */
-
-  while (code > htbl->maxcode[l]) {
-    code <<= 1;
-    CHECK_BIT_BUFFER(*state, 1, return -1);
-    code |= GET_BITS(1);
-    l++;
-  }
-
-  /* Unload the local registers */
-  state->get_buffer = get_buffer;
-  state->bits_left = bits_left;
-
-  /* With garbage input we may reach the sentinel value l = 17. */
-
-  if (l > 16) {
-    WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
-    return 0;			/* fake a zero as the safest result */
-  }
-
-  return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
-}
-
-
-/*
- * Figure F.12: extend sign bit.
- * On some machines, a shift and add will be faster than a table lookup.
- */
-
-#ifdef AVOID_TABLES
-
-#define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
-
-#else
-
-#define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
-
-static const int extend_test[16] =   /* entry n is 2**(n-1) */
-  { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
-    0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
-
-static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
-  { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
-    ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
-    ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
-    ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
-
-#endif /* AVOID_TABLES */
-
-
-/*
- * Check for a restart marker & resynchronize decoder.
- * Returns FALSE if must suspend.
- */
-
-LOCAL(boolean)
-process_restart (j_decompress_ptr cinfo)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  int ci;
-
-  /* Throw away any unused bits remaining in bit buffer; */
-  /* include any full bytes in next_marker's count of discarded bytes */
-  cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
-  entropy->bitstate.bits_left = 0;
-
-  /* Advance past the RSTn marker */
-  if (! (*cinfo->marker->read_restart_marker) (cinfo))
-    return FALSE;
-
-  /* Re-initialize DC predictions to 0 */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
-    entropy->saved.last_dc_val[ci] = 0;
-
-  /* Reset restart counter */
-  entropy->restarts_to_go = cinfo->restart_interval;
-
-  /* Reset out-of-data flag, unless read_restart_marker left us smack up
-   * against a marker.  In that case we will end up treating the next data
-   * segment as empty, and we can avoid producing bogus output pixels by
-   * leaving the flag set.
-   */
-  if (cinfo->unread_marker == 0)
-    entropy->pub.insufficient_data = FALSE;
-
-  return TRUE;
-}
-
-
-/*
- * Decode and return one MCU's worth of Huffman-compressed coefficients.
- * The coefficients are reordered from zigzag order into natural array order,
- * but are not dequantized.
- *
- * The i'th block of the MCU is stored into the block pointed to by
- * MCU_data[i].  WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
- * (Wholesale zeroing is usually a little faster than retail...)
- *
- * Returns FALSE if data source requested suspension.  In that case no
- * changes have been made to permanent state.  (Exception: some output
- * coefficients may already have been assigned.  This is harmless for
- * this module, since we'll just re-assign them on the next call.)
- */
-
-METHODDEF(boolean)
-decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
-{
-  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
-  int blkn;
-  BITREAD_STATE_VARS;
-  savable_state state;
-
-  /* Process restart marker if needed; may have to suspend */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0)
-      if (! process_restart(cinfo))
-	return FALSE;
-  }
-
-  /* If we've run out of data, just leave the MCU set to zeroes.
-   * This way, we return uniform gray for the remainder of the segment.
-   */
-  if (! entropy->pub.insufficient_data) {
-
-    /* Load up working state */
-    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
-    ASSIGN_STATE(state, entropy->saved);
-
-    /* Outer loop handles each block in the MCU */
-
-    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-      JBLOCKROW block = MCU_data[blkn];
-      d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
-      d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
-      register int s, k, r;
-
-      /* Decode a single block's worth of coefficients */
-
-      /* Section F.2.2.1: decode the DC coefficient difference */
-      HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
-      if (s) {
-	CHECK_BIT_BUFFER(br_state, s, return FALSE);
-	r = GET_BITS(s);
-	s = HUFF_EXTEND(r, s);
-      }
-
-      if (entropy->dc_needed[blkn]) {
-	/* Convert DC difference to actual value, update last_dc_val */
-	int ci = cinfo->MCU_membership[blkn];
-	s += state.last_dc_val[ci];
-	state.last_dc_val[ci] = s;
-	/* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
-	(*block)[0] = (JCOEF) s;
-      }
-
-      if (entropy->ac_needed[blkn]) {
-
-	/* Section F.2.2.2: decode the AC coefficients */
-	/* Since zeroes are skipped, output area must be cleared beforehand */
-	for (k = 1; k < DCTSIZE2; k++) {
-	  HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
-      
-	  r = s >> 4;
-	  s &= 15;
-      
-	  if (s) {
-	    k += r;
-	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
-	    r = GET_BITS(s);
-	    s = HUFF_EXTEND(r, s);
-	    /* Output coefficient in natural (dezigzagged) order.
-	     * Note: the extra entries in jpeg_natural_order[] will save us
-	     * if k >= DCTSIZE2, which could happen if the data is corrupted.
-	     */
-	    (*block)[jpeg_natural_order[k]] = (JCOEF) s;
-	  } else {
-	    if (r != 15)
-	      break;
-	    k += 15;
-	  }
-	}
-
-      } else {
-
-	/* Section F.2.2.2: decode the AC coefficients */
-	/* In this path we just discard the values */
-	for (k = 1; k < DCTSIZE2; k++) {
-	  HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
-      
-	  r = s >> 4;
-	  s &= 15;
-      
-	  if (s) {
-	    k += r;
-	    CHECK_BIT_BUFFER(br_state, s, return FALSE);
-	    DROP_BITS(s);
-	  } else {
-	    if (r != 15)
-	      break;
-	    k += 15;
-	  }
-	}
-
-      }
-    }
-
-    /* Completed MCU, so update state */
-    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
-    ASSIGN_STATE(entropy->saved, state);
-  }
-
-  /* Account for restart interval (no-op if not using restarts) */
-  entropy->restarts_to_go--;
-
-  return TRUE;
-}
-
-
-/*
- * Module initialization routine for Huffman entropy decoding.
- */
-
-GLOBAL(void)
-jinit_huff_decoder (j_decompress_ptr cinfo)
-{
-  huff_entropy_ptr entropy;
-  int i;
-
-  entropy = (huff_entropy_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(huff_entropy_decoder));
-  cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
-  entropy->pub.start_pass = start_pass_huff_decoder;
-  entropy->pub.decode_mcu = decode_mcu;
-
-  /* Mark tables unallocated */
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdhuff.h ./Shared/jpeg-6b/jdhuff.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdhuff.h	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdhuff.h	Wed Dec 31 19:00:00 1969
@@ -1,201 +0,0 @@
-/*
- * jdhuff.h
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains declarations for Huffman entropy decoding routines
- * that are shared between the sequential decoder (jdhuff.c) and the
- * progressive decoder (jdphuff.c).  No other modules need to see these.
- */
-
-/* Short forms of external names for systems with brain-damaged linkers. */
-
-#ifdef NEED_SHORT_EXTERNAL_NAMES
-#define jpeg_make_d_derived_tbl	jMkDDerived
-#define jpeg_fill_bit_buffer	jFilBitBuf
-#define jpeg_huff_decode	jHufDecode
-#endif /* NEED_SHORT_EXTERNAL_NAMES */
-
-
-/* Derived data constructed for each Huffman table */
-
-#define HUFF_LOOKAHEAD	8	/* # of bits of lookahead */
-
-typedef struct {
-  /* Basic tables: (element [0] of each array is unused) */
-  INT32 maxcode[18];		/* largest code of length k (-1 if none) */
-  /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
-  INT32 valoffset[17];		/* huffval[] offset for codes of length k */
-  /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
-   * the smallest code of length k; so given a code of length k, the
-   * corresponding symbol is huffval[code + valoffset[k]]
-   */
-
-  /* Link to public Huffman table (needed only in jpeg_huff_decode) */
-  JHUFF_TBL *pub;
-
-  /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
-   * the input data stream.  If the next Huffman code is no more
-   * than HUFF_LOOKAHEAD bits long, we can obtain its length and
-   * the corresponding symbol directly from these tables.
-   */
-  int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
-  UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
-} d_derived_tbl;
-
-/* Expand a Huffman table definition into the derived format */
-EXTERN(void) jpeg_make_d_derived_tbl
-	JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
-	     d_derived_tbl ** pdtbl));
-
-
-/*
- * Fetching the next N bits from the input stream is a time-critical operation
- * for the Huffman decoders.  We implement it with a combination of inline
- * macros and out-of-line subroutines.  Note that N (the number of bits
- * demanded at one time) never exceeds 15 for JPEG use.
- *
- * We read source bytes into get_buffer and dole out bits as needed.
- * If get_buffer already contains enough bits, they are fetched in-line
- * by the macros CHECK_BIT_BUFFER and GET_BITS.  When there aren't enough
- * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
- * as full as possible (not just to the number of bits needed; this
- * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
- * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
- * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
- * at least the requested number of bits --- dummy zeroes are inserted if
- * necessary.
- */
-
-typedef INT32 bit_buf_type;	/* type of bit-extraction buffer */
-#define BIT_BUF_SIZE  32	/* size of buffer in bits */
-
-/* If long is > 32 bits on your machine, and shifting/masking longs is
- * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
- * appropriately should be a win.  Unfortunately we can't define the size
- * with something like  #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
- * because not all machines measure sizeof in 8-bit bytes.
- */
-
-typedef struct {		/* Bitreading state saved across MCUs */
-  bit_buf_type get_buffer;	/* current bit-extraction buffer */
-  int bits_left;		/* # of unused bits in it */
-} bitread_perm_state;
-
-typedef struct {		/* Bitreading working state within an MCU */
-  /* Current data source location */
-  /* We need a copy, rather than munging the original, in case of suspension */
-  const JOCTET * next_input_byte; /* => next byte to read from source */
-  size_t bytes_in_buffer;	/* # of bytes remaining in source buffer */
-  /* Bit input buffer --- note these values are kept in register variables,
-   * not in this struct, inside the inner loops.
-   */
-  bit_buf_type get_buffer;	/* current bit-extraction buffer */
-  int bits_left;		/* # of unused bits in it */
-  /* Pointer needed by jpeg_fill_bit_buffer. */
-  j_decompress_ptr cinfo;	/* back link to decompress master record */
-} bitread_working_state;
-
-/* Macros to declare and load/save bitread local variables. */
-#define BITREAD_STATE_VARS  \
-	register bit_buf_type get_buffer;  \
-	register int bits_left;  \
-	bitread_working_state br_state
-
-#define BITREAD_LOAD_STATE(cinfop,permstate)  \
-	br_state.cinfo = cinfop; \
-	br_state.next_input_byte = cinfop->src->next_input_byte; \
-	br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
-	get_buffer = permstate.get_buffer; \
-	bits_left = permstate.bits_left;
-
-#define BITREAD_SAVE_STATE(cinfop,permstate)  \
-	cinfop->src->next_input_byte = br_state.next_input_byte; \
-	cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
-	permstate.get_buffer = get_buffer; \
-	permstate.bits_left = bits_left
-
-/*
- * These macros provide the in-line portion of bit fetching.
- * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
- * before using GET_BITS, PEEK_BITS, or DROP_BITS.
- * The variables get_buffer and bits_left are assumed to be locals,
- * but the state struct might not be (jpeg_huff_decode needs this).
- *	CHECK_BIT_BUFFER(state,n,action);
- *		Ensure there are N bits in get_buffer; if suspend, take action.
- *      val = GET_BITS(n);
- *		Fetch next N bits.
- *      val = PEEK_BITS(n);
- *		Fetch next N bits without removing them from the buffer.
- *	DROP_BITS(n);
- *		Discard next N bits.
- * The value N should be a simple variable, not an expression, because it
- * is evaluated multiple times.
- */
-
-#define CHECK_BIT_BUFFER(state,nbits,action) \
-	{ if (bits_left < (nbits)) {  \
-	    if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits))  \
-	      { action; }  \
-	    get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
-
-#define GET_BITS(nbits) \
-	(((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
-
-#define PEEK_BITS(nbits) \
-	(((int) (get_buffer >> (bits_left -  (nbits)))) & ((1<<(nbits))-1))
-
-#define DROP_BITS(nbits) \
-	(bits_left -= (nbits))
-
-/* Load up the bit buffer to a depth of at least nbits */
-EXTERN(boolean) jpeg_fill_bit_buffer
-	JPP((bitread_working_state * state, register bit_buf_type get_buffer,
-	     register int bits_left, int nbits));
-
-
-/*
- * Code for extracting next Huffman-coded symbol from input bit stream.
- * Again, this is time-critical and we make the main paths be macros.
- *
- * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
- * without looping.  Usually, more than 95% of the Huffman codes will be 8
- * or fewer bits long.  The few overlength codes are handled with a loop,
- * which need not be inline code.
- *
- * Notes about the HUFF_DECODE macro:
- * 1. Near the end of the data segment, we may fail to get enough bits
- *    for a lookahead.  In that case, we do it the hard way.
- * 2. If the lookahead table contains no entry, the next code must be
- *    more than HUFF_LOOKAHEAD bits long.
- * 3. jpeg_huff_decode returns -1 if forced to suspend.
- */
-
-#define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
-{ register int nb, look; \
-  if (bits_left < HUFF_LOOKAHEAD) { \
-    if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
-    get_buffer = state.get_buffer; bits_left = state.bits_left; \
-    if (bits_left < HUFF_LOOKAHEAD) { \
-      nb = 1; goto slowlabel; \
-    } \
-  } \
-  look = PEEK_BITS(HUFF_LOOKAHEAD); \
-  if ((nb = htbl->look_nbits[look]) != 0) { \
-    DROP_BITS(nb); \
-    result = htbl->look_sym[look]; \
-  } else { \
-    nb = HUFF_LOOKAHEAD+1; \
-slowlabel: \
-    if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
-	{ failaction; } \
-    get_buffer = state.get_buffer; bits_left = state.bits_left; \
-  } \
-}
-
-/* Out-of-line case for Huffman code fetching */
-EXTERN(int) jpeg_huff_decode
-	JPP((bitread_working_state * state, register bit_buf_type get_buffer,
-	     register int bits_left, d_derived_tbl * htbl, int min_bits));
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdinput.c ./Shared/jpeg-6b/jdinput.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdinput.c	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdinput.c	Wed Dec 31 19:00:00 1969
@@ -1,381 +0,0 @@
-/*
- * jdinput.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains input control logic for the JPEG decompressor.
- * These routines are concerned with controlling the decompressor's input
- * processing (marker reading and coefficient decoding).  The actual input
- * reading is done in jdmarker.c, jdhuff.c, and jdphuff.c.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Private state */
-
-typedef struct {
-  struct jpeg_input_controller pub; /* public fields */
-
-  boolean inheaders;		/* TRUE until first SOS is reached */
-} my_input_controller;
-
-typedef my_input_controller * my_inputctl_ptr;
-
-
-/* Forward declarations */
-METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
-
-
-/*
- * Routines to calculate various quantities related to the size of the image.
- */
-
-LOCAL(void)
-initial_setup (j_decompress_ptr cinfo)
-/* Called once, when first SOS marker is reached */
-{
-  int ci;
-  jpeg_component_info *compptr;
-
-  /* Make sure image isn't bigger than I can handle */
-  if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
-      (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
-    ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
-
-  /* For now, precision must match compiled-in value... */
-  if (cinfo->data_precision != BITS_IN_JSAMPLE)
-    ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
-
-  /* Check that number of components won't exceed internal array sizes */
-  if (cinfo->num_components > MAX_COMPONENTS)
-    ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
-	     MAX_COMPONENTS);
-
-  /* Compute maximum sampling factors; check factor validity */
-  cinfo->max_h_samp_factor = 1;
-  cinfo->max_v_samp_factor = 1;
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
-	compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
-      ERREXIT(cinfo, JERR_BAD_SAMPLING);
-    cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
-				   compptr->h_samp_factor);
-    cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
-				   compptr->v_samp_factor);
-  }
-
-  /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
-   * In the full decompressor, this will be overridden by jdmaster.c;
-   * but in the transcoder, jdmaster.c is not used, so we must do it here.
-   */
-  cinfo->min_DCT_scaled_size = DCTSIZE;
-
-  /* Compute dimensions of components */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    compptr->DCT_scaled_size = DCTSIZE;
-    /* Size in DCT blocks */
-    compptr->width_in_blocks = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
-		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
-    compptr->height_in_blocks = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
-		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
-    /* downsampled_width and downsampled_height will also be overridden by
-     * jdmaster.c if we are doing full decompression.  The transcoder library
-     * doesn't use these values, but the calling application might.
-     */
-    /* Size in samples */
-    compptr->downsampled_width = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
-		    (long) cinfo->max_h_samp_factor);
-    compptr->downsampled_height = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
-		    (long) cinfo->max_v_samp_factor);
-    /* Mark component needed, until color conversion says otherwise */
-    compptr->component_needed = TRUE;
-    /* Mark no quantization table yet saved for component */
-    compptr->quant_table = NULL;
-  }
-
-  /* Compute number of fully interleaved MCU rows. */
-  cinfo->total_iMCU_rows = (JDIMENSION)
-    jdiv_round_up((long) cinfo->image_height,
-		  (long) (cinfo->max_v_samp_factor*DCTSIZE));
-
-  /* Decide whether file contains multiple scans */
-  if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
-    cinfo->inputctl->has_multiple_scans = TRUE;
-  else
-    cinfo->inputctl->has_multiple_scans = FALSE;
-}
-
-
-LOCAL(void)
-per_scan_setup (j_decompress_ptr cinfo)
-/* Do computations that are needed before processing a JPEG scan */
-/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
-{
-  int ci, mcublks, tmp;
-  jpeg_component_info *compptr;
-  
-  if (cinfo->comps_in_scan == 1) {
-    
-    /* Noninterleaved (single-component) scan */
-    compptr = cinfo->cur_comp_info[0];
-    
-    /* Overall image size in MCUs */
-    cinfo->MCUs_per_row = compptr->width_in_blocks;
-    cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
-    
-    /* For noninterleaved scan, always one block per MCU */
-    compptr->MCU_width = 1;
-    compptr->MCU_height = 1;
-    compptr->MCU_blocks = 1;
-    compptr->MCU_sample_width = compptr->DCT_scaled_size;
-    compptr->last_col_width = 1;
-    /* For noninterleaved scans, it is convenient to define last_row_height
-     * as the number of block rows present in the last iMCU row.
-     */
-    tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
-    if (tmp == 0) tmp = compptr->v_samp_factor;
-    compptr->last_row_height = tmp;
-    
-    /* Prepare array describing MCU composition */
-    cinfo->blocks_in_MCU = 1;
-    cinfo->MCU_membership[0] = 0;
-    
-  } else {
-    
-    /* Interleaved (multi-component) scan */
-    if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
-      ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
-	       MAX_COMPS_IN_SCAN);
-    
-    /* Overall image size in MCUs */
-    cinfo->MCUs_per_row = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width,
-		    (long) (cinfo->max_h_samp_factor*DCTSIZE));
-    cinfo->MCU_rows_in_scan = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height,
-		    (long) (cinfo->max_v_samp_factor*DCTSIZE));
-    
-    cinfo->blocks_in_MCU = 0;
-    
-    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-      compptr = cinfo->cur_comp_info[ci];
-      /* Sampling factors give # of blocks of component in each MCU */
-      compptr->MCU_width = compptr->h_samp_factor;
-      compptr->MCU_height = compptr->v_samp_factor;
-      compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
-      compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
-      /* Figure number of non-dummy blocks in last MCU column & row */
-      tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
-      if (tmp == 0) tmp = compptr->MCU_width;
-      compptr->last_col_width = tmp;
-      tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
-      if (tmp == 0) tmp = compptr->MCU_height;
-      compptr->last_row_height = tmp;
-      /* Prepare array describing MCU composition */
-      mcublks = compptr->MCU_blocks;
-      if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
-	ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
-      while (mcublks-- > 0) {
-	cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
-      }
-    }
-    
-  }
-}
-
-
-/*
- * Save away a copy of the Q-table referenced by each component present
- * in the current scan, unless already saved during a prior scan.
- *
- * In a multiple-scan JPEG file, the encoder could assign different components
- * the same Q-table slot number, but change table definitions between scans
- * so that each component uses a different Q-table.  (The IJG encoder is not
- * currently capable of doing this, but other encoders might.)  Since we want
- * to be able to dequantize all the components at the end of the file, this
- * means that we have to save away the table actually used for each component.
- * We do this by copying the table at the start of the first scan containing
- * the component.
- * The JPEG spec prohibits the encoder from changing the contents of a Q-table
- * slot between scans of a component using that slot.  If the encoder does so
- * anyway, this decoder will simply use the Q-table values that were current
- * at the start of the first scan for the component.
- *
- * The decompressor output side looks only at the saved quant tables,
- * not at the current Q-table slots.
- */
-
-LOCAL(void)
-latch_quant_tables (j_decompress_ptr cinfo)
-{
-  int ci, qtblno;
-  jpeg_component_info *compptr;
-  JQUANT_TBL * qtbl;
-
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    /* No work if we already saved Q-table for this component */
-    if (compptr->quant_table != NULL)
-      continue;
-    /* Make sure specified quantization table is present */
-    qtblno = compptr->quant_tbl_no;
-    if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
-	cinfo->quant_tbl_ptrs[qtblno] == NULL)
-      ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
-    /* OK, save away the quantization table */
-    qtbl = (JQUANT_TBL *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(JQUANT_TBL));
-    MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
-    compptr->quant_table = qtbl;
-  }
-}
-
-
-/*
- * Initialize the input modules to read a scan of compressed data.
- * The first call to this is done by jdmaster.c after initializing
- * the entire decompressor (during jpeg_start_decompress).
- * Subsequent calls come from consume_markers, below.
- */
-
-METHODDEF(void)
-start_input_pass (j_decompress_ptr cinfo)
-{
-  per_scan_setup(cinfo);
-  latch_quant_tables(cinfo);
-  (*cinfo->entropy->start_pass) (cinfo);
-  (*cinfo->coef->start_input_pass) (cinfo);
-  cinfo->inputctl->consume_input = cinfo->coef->consume_data;
-}
-
-
-/*
- * Finish up after inputting a compressed-data scan.
- * This is called by the coefficient controller after it's read all
- * the expected data of the scan.
- */
-
-METHODDEF(void)
-finish_input_pass (j_decompress_ptr cinfo)
-{
-  cinfo->inputctl->consume_input = consume_markers;
-}
-
-
-/*
- * Read JPEG markers before, between, or after compressed-data scans.
- * Change state as necessary when a new scan is reached.
- * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
- *
- * The consume_input method pointer points either here or to the
- * coefficient controller's consume_data routine, depending on whether
- * we are reading a compressed data segment or inter-segment markers.
- */
-
-METHODDEF(int)
-consume_markers (j_decompress_ptr cinfo)
-{
-  my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
-  int val;
-
-  if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
-    return JPEG_REACHED_EOI;
-
-  val = (*cinfo->marker->read_markers) (cinfo);
-
-  switch (val) {
-  case JPEG_REACHED_SOS:	/* Found SOS */
-    if (inputctl->inheaders) {	/* 1st SOS */
-      initial_setup(cinfo);
-      inputctl->inheaders = FALSE;
-      /* Note: start_input_pass must be called by jdmaster.c
-       * before any more input can be consumed.  jdapimin.c is
-       * responsible for enforcing this sequencing.
-       */
-    } else {			/* 2nd or later SOS marker */
-      if (! inputctl->pub.has_multiple_scans)
-	ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
-      start_input_pass(cinfo);
-    }
-    break;
-  case JPEG_REACHED_EOI:	/* Found EOI */
-    inputctl->pub.eoi_reached = TRUE;
-    if (inputctl->inheaders) {	/* Tables-only datastream, apparently */
-      if (cinfo->marker->saw_SOF)
-	ERREXIT(cinfo, JERR_SOF_NO_SOS);
-    } else {
-      /* Prevent infinite loop in coef ctlr's decompress_data routine
-       * if user set output_scan_number larger than number of scans.
-       */
-      if (cinfo->output_scan_number > cinfo->input_scan_number)
-	cinfo->output_scan_number = cinfo->input_scan_number;
-    }
-    break;
-  case JPEG_SUSPENDED:
-    break;
-  }
-
-  return val;
-}
-
-
-/*
- * Reset state to begin a fresh datastream.
- */
-
-METHODDEF(void)
-reset_input_controller (j_decompress_ptr cinfo)
-{
-  my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
-
-  inputctl->pub.consume_input = consume_markers;
-  inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
-  inputctl->pub.eoi_reached = FALSE;
-  inputctl->inheaders = TRUE;
-  /* Reset other modules */
-  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
-  (*cinfo->marker->reset_marker_reader) (cinfo);
-  /* Reset progression state -- would be cleaner if entropy decoder did this */
-  cinfo->coef_bits = NULL;
-}
-
-
-/*
- * Initialize the input controller module.
- * This is called only once, when the decompression object is created.
- */
-
-GLOBAL(void)
-jinit_input_controller (j_decompress_ptr cinfo)
-{
-  my_inputctl_ptr inputctl;
-
-  /* Create subobject in permanent pool */
-  inputctl = (my_inputctl_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
-				SIZEOF(my_input_controller));
-  cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
-  /* Initialize method pointers */
-  inputctl->pub.consume_input = consume_markers;
-  inputctl->pub.reset_input_controller = reset_input_controller;
-  inputctl->pub.start_input_pass = start_input_pass;
-  inputctl->pub.finish_input_pass = finish_input_pass;
-  /* Initialize state: can't use reset_input_controller since we don't
-   * want to try to reset other modules yet.
-   */
-  inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
-  inputctl->pub.eoi_reached = FALSE;
-  inputctl->inheaders = TRUE;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdmainct.c ./Shared/jpeg-6b/jdmainct.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdmainct.c	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdmainct.c	Wed Dec 31 19:00:00 1969
@@ -1,512 +0,0 @@
-/*
- * jdmainct.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the main buffer controller for decompression.
- * The main buffer lies between the JPEG decompressor proper and the
- * post-processor; it holds downsampled data in the JPEG colorspace.
- *
- * Note that this code is bypassed in raw-data mode, since the application
- * supplies the equivalent of the main buffer in that case.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * In the current system design, the main buffer need never be a full-image
- * buffer; any full-height buffers will be found inside the coefficient or
- * postprocessing controllers.  Nonetheless, the main controller is not
- * trivial.  Its responsibility is to provide context rows for upsampling/
- * rescaling, and doing this in an efficient fashion is a bit tricky.
- *
- * Postprocessor input data is counted in "row groups".  A row group
- * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
- * sample rows of each component.  (We require DCT_scaled_size values to be
- * chosen such that these numbers are integers.  In practice DCT_scaled_size
- * values will likely be powers of two, so we actually have the stronger
- * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
- * Upsampling will typically produce max_v_samp_factor pixel rows from each
- * row group (times any additional scale factor that the upsampler is
- * applying).
- *
- * The coefficient controller will deliver data to us one iMCU row at a time;
- * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
- * exactly min_DCT_scaled_size row groups.  (This amount of data corresponds
- * to one row of MCUs when the image is fully interleaved.)  Note that the
- * number of sample rows varies across components, but the number of row
- * groups does not.  Some garbage sample rows may be included in the last iMCU
- * row at the bottom of the image.
- *
- * Depending on the vertical scaling algorithm used, the upsampler may need
- * access to the sample row(s) above and below its current input row group.
- * The upsampler is required to set need_context_rows TRUE at global selection
- * time if so.  When need_context_rows is FALSE, this controller can simply
- * obtain one iMCU row at a time from the coefficient controller and dole it
- * out as row groups to the postprocessor.
- *
- * When need_context_rows is TRUE, this controller guarantees that the buffer
- * passed to postprocessing contains at least one row group's worth of samples
- * above and below the row group(s) being processed.  Note that the context
- * rows "above" the first passed row group appear at negative row offsets in
- * the passed buffer.  At the top and bottom of the image, the required
- * context rows are manufactured by duplicating the first or last real sample
- * row; this avoids having special cases in the upsampling inner loops.
- *
- * The amount of context is fixed at one row group just because that's a
- * convenient number for this controller to work with.  The existing
- * upsamplers really only need one sample row of context.  An upsampler
- * supporting arbitrary output rescaling might wish for more than one row
- * group of context when shrinking the image; tough, we don't handle that.
- * (This is justified by the assumption that downsizing will be handled mostly
- * by adjusting the DCT_scaled_size values, so that the actual scale factor at
- * the upsample step needn't be much less than one.)
- *
- * To provide the desired context, we have to retain the last two row groups
- * of one iMCU row while reading in the next iMCU row.  (The last row group
- * can't be processed until we have another row group for its below-context,
- * and so we have to save the next-to-last group too for its above-context.)
- * We could do this most simply by copying data around in our buffer, but
- * that'd be very slow.  We can avoid copying any data by creating a rather
- * strange pointer structure.  Here's how it works.  We allocate a workspace
- * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
- * of row groups per iMCU row).  We create two sets of redundant pointers to
- * the workspace.  Labeling the physical row groups 0 to M+1, the synthesized
- * pointer lists look like this:
- *                   M+1                          M-1
- * master pointer --> 0         master pointer --> 0
- *                    1                            1
- *                   ...                          ...
- *                   M-3                          M-3
- *                   M-2                           M
- *                   M-1                          M+1
- *                    M                           M-2
- *                   M+1                          M-1
- *                    0                            0
- * We read alternate iMCU rows using each master pointer; thus the last two
- * row groups of the previous iMCU row remain un-overwritten in the workspace.
- * The pointer lists are set up so that the required context rows appear to
- * be adjacent to the proper places when we pass the pointer lists to the
- * upsampler.
- *
- * The above pictures describe the normal state of the pointer lists.
- * At top and bottom of the image, we diddle the pointer lists to duplicate
- * the first or last sample row as necessary (this is cheaper than copying
- * sample rows around).
- *
- * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1.  In that
- * situation each iMCU row provides only one row group so the buffering logic
- * must be different (eg, we must read two iMCU rows before we can emit the
- * first row group).  For now, we simply do not support providing context
- * rows when min_DCT_scaled_size is 1.  That combination seems unlikely to
- * be worth providing --- if someone wants a 1/8th-size preview, they probably
- * want it quick and dirty, so a context-free upsampler is sufficient.
- */
-
-
-/* Private buffer controller object */
-
-typedef struct {
-  struct jpeg_d_main_controller pub; /* public fields */
-
-  /* Pointer to allocated workspace (M or M+2 row groups). */
-  JSAMPARRAY buffer[MAX_COMPONENTS];
-
-  boolean buffer_full;		/* Have we gotten an iMCU row from decoder? */
-  JDIMENSION rowgroup_ctr;	/* counts row groups output to postprocessor */
-
-  /* Remaining fields are only used in the context case. */
-
-  /* These are the master pointers to the funny-order pointer lists. */
-  JSAMPIMAGE xbuffer[2];	/* pointers to weird pointer lists */
-
-  int whichptr;			/* indicates which pointer set is now in use */
-  int context_state;		/* process_data state machine status */
-  JDIMENSION rowgroups_avail;	/* row groups available to postprocessor */
-  JDIMENSION iMCU_row_ctr;	/* counts iMCU rows to detect image top/bot */
-} my_main_controller;
-
-typedef my_main_controller * my_main_ptr;
-
-/* context_state values: */
-#define CTX_PREPARE_FOR_IMCU	0	/* need to prepare for MCU row */
-#define CTX_PROCESS_IMCU	1	/* feeding iMCU to postprocessor */
-#define CTX_POSTPONED_ROW	2	/* feeding postponed row group */
-
-
-/* Forward declarations */
-METHODDEF(void) process_data_simple_main
-	JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
-	     JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
-METHODDEF(void) process_data_context_main
-	JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
-	     JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
-#ifdef QUANT_2PASS_SUPPORTED
-METHODDEF(void) process_data_crank_post
-	JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
-	     JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
-#endif
-
-
-LOCAL(void)
-alloc_funny_pointers (j_decompress_ptr cinfo)
-/* Allocate space for the funny pointer lists.
- * This is done only once, not once per pass.
- */
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-  int ci, rgroup;
-  int M = cinfo->min_DCT_scaled_size;
-  jpeg_component_info *compptr;
-  JSAMPARRAY xbuf;
-
-  /* Get top-level space for component array pointers.
-   * We alloc both arrays with one call to save a few cycles.
-   */
-  main->xbuffer[0] = (JSAMPIMAGE)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
-  main->xbuffer[1] = main->xbuffer[0] + cinfo->num_components;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
-      cinfo->min_DCT_scaled_size; /* height of a row group of component */
-    /* Get space for pointer lists --- M+4 row groups in each list.
-     * We alloc both pointer lists with one call to save a few cycles.
-     */
-    xbuf = (JSAMPARRAY)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
-    xbuf += rgroup;		/* want one row group at negative offsets */
-    main->xbuffer[0][ci] = xbuf;
-    xbuf += rgroup * (M + 4);
-    main->xbuffer[1][ci] = xbuf;
-  }
-}
-
-
-LOCAL(void)
-make_funny_pointers (j_decompress_ptr cinfo)
-/* Create the funny pointer lists discussed in the comments above.
- * The actual workspace is already allocated (in main->buffer),
- * and the space for the pointer lists is allocated too.
- * This routine just fills in the curiously ordered lists.
- * This will be repeated at the beginning of each pass.
- */
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-  int ci, i, rgroup;
-  int M = cinfo->min_DCT_scaled_size;
-  jpeg_component_info *compptr;
-  JSAMPARRAY buf, xbuf0, xbuf1;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
-      cinfo->min_DCT_scaled_size; /* height of a row group of component */
-    xbuf0 = main->xbuffer[0][ci];
-    xbuf1 = main->xbuffer[1][ci];
-    /* First copy the workspace pointers as-is */
-    buf = main->buffer[ci];
-    for (i = 0; i < rgroup * (M + 2); i++) {
-      xbuf0[i] = xbuf1[i] = buf[i];
-    }
-    /* In the second list, put the last four row groups in swapped order */
-    for (i = 0; i < rgroup * 2; i++) {
-      xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
-      xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
-    }
-    /* The wraparound pointers at top and bottom will be filled later
-     * (see set_wraparound_pointers, below).  Initially we want the "above"
-     * pointers to duplicate the first actual data line.  This only needs
-     * to happen in xbuffer[0].
-     */
-    for (i = 0; i < rgroup; i++) {
-      xbuf0[i - rgroup] = xbuf0[0];
-    }
-  }
-}
-
-
-LOCAL(void)
-set_wraparound_pointers (j_decompress_ptr cinfo)
-/* Set up the "wraparound" pointers at top and bottom of the pointer lists.
- * This changes the pointer list state from top-of-image to the normal state.
- */
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-  int ci, i, rgroup;
-  int M = cinfo->min_DCT_scaled_size;
-  jpeg_component_info *compptr;
-  JSAMPARRAY xbuf0, xbuf1;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
-      cinfo->min_DCT_scaled_size; /* height of a row group of component */
-    xbuf0 = main->xbuffer[0][ci];
-    xbuf1 = main->xbuffer[1][ci];
-    for (i = 0; i < rgroup; i++) {
-      xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
-      xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
-      xbuf0[rgroup*(M+2) + i] = xbuf0[i];
-      xbuf1[rgroup*(M+2) + i] = xbuf1[i];
-    }
-  }
-}
-
-
-LOCAL(void)
-set_bottom_pointers (j_decompress_ptr cinfo)
-/* Change the pointer lists to duplicate the last sample row at the bottom
- * of the image.  whichptr indicates which xbuffer holds the final iMCU row.
- * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
- */
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-  int ci, i, rgroup, iMCUheight, rows_left;
-  jpeg_component_info *compptr;
-  JSAMPARRAY xbuf;
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Count sample rows in one iMCU row and in one row group */
-    iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
-    rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
-    /* Count nondummy sample rows remaining for this component */
-    rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
-    if (rows_left == 0) rows_left = iMCUheight;
-    /* Count nondummy row groups.  Should get same answer for each component,
-     * so we need only do it once.
-     */
-    if (ci == 0) {
-      main->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
-    }
-    /* Duplicate the last real sample row rgroup*2 times; this pads out the
-     * last partial rowgroup and ensures at least one full rowgroup of context.
-     */
-    xbuf = main->xbuffer[main->whichptr][ci];
-    for (i = 0; i < rgroup * 2; i++) {
-      xbuf[rows_left + i] = xbuf[rows_left-1];
-    }
-  }
-}
-
-
-/*
- * Initialize for a processing pass.
- */
-
-METHODDEF(void)
-start_pass_main (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-
-  switch (pass_mode) {
-  case JBUF_PASS_THRU:
-    if (cinfo->upsample->need_context_rows) {
-      main->pub.process_data = process_data_context_main;
-      make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
-      main->whichptr = 0;	/* Read first iMCU row into xbuffer[0] */
-      main->context_state = CTX_PREPARE_FOR_IMCU;
-      main->iMCU_row_ctr = 0;
-    } else {
-      /* Simple case with no context needed */
-      main->pub.process_data = process_data_simple_main;
-    }
-    main->buffer_full = FALSE;	/* Mark buffer empty */
-    main->rowgroup_ctr = 0;
-    break;
-#ifdef QUANT_2PASS_SUPPORTED
-  case JBUF_CRANK_DEST:
-    /* For last pass of 2-pass quantization, just crank the postprocessor */
-    main->pub.process_data = process_data_crank_post;
-    break;
-#endif
-  default:
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    break;
-  }
-}
-
-
-/*
- * Process some data.
- * This handles the simple case where no context is required.
- */
-
-METHODDEF(void)
-process_data_simple_main (j_decompress_ptr cinfo,
-			  JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-			  JDIMENSION out_rows_avail)
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-  JDIMENSION rowgroups_avail;
-
-  /* Read input data if we haven't filled the main buffer yet */
-  if (! main->buffer_full) {
-    if (! (*cinfo->coef->decompress_data) (cinfo, main->buffer))
-      return;			/* suspension forced, can do nothing more */
-    main->buffer_full = TRUE;	/* OK, we have an iMCU row to work with */
-  }
-
-  /* There are always min_DCT_scaled_size row groups in an iMCU row. */
-  rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
-  /* Note: at the bottom of the image, we may pass extra garbage row groups
-   * to the postprocessor.  The postprocessor has to check for bottom
-   * of image anyway (at row resolution), so no point in us doing it too.
-   */
-
-  /* Feed the postprocessor */
-  (*cinfo->post->post_process_data) (cinfo, main->buffer,
-				     &main->rowgroup_ctr, rowgroups_avail,
-				     output_buf, out_row_ctr, out_rows_avail);
-
-  /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
-  if (main->rowgroup_ctr >= rowgroups_avail) {
-    main->buffer_full = FALSE;
-    main->rowgroup_ctr = 0;
-  }
-}
-
-
-/*
- * Process some data.
- * This handles the case where context rows must be provided.
- */
-
-METHODDEF(void)
-process_data_context_main (j_decompress_ptr cinfo,
-			   JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-			   JDIMENSION out_rows_avail)
-{
-  my_main_ptr main = (my_main_ptr) cinfo->main;
-
-  /* Read input data if we haven't filled the main buffer yet */
-  if (! main->buffer_full) {
-    if (! (*cinfo->coef->decompress_data) (cinfo,
-					   main->xbuffer[main->whichptr]))
-      return;			/* suspension forced, can do nothing more */
-    main->buffer_full = TRUE;	/* OK, we have an iMCU row to work with */
-    main->iMCU_row_ctr++;	/* count rows received */
-  }
-
-  /* Postprocessor typically will not swallow all the input data it is handed
-   * in one call (due to filling the output buffer first).  Must be prepared
-   * to exit and restart.  This switch lets us keep track of how far we got.
-   * Note that each case falls through to the next on successful completion.
-   */
-  switch (main->context_state) {
-  case CTX_POSTPONED_ROW:
-    /* Call postprocessor using previously set pointers for postponed row */
-    (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr],
-			&main->rowgroup_ctr, main->rowgroups_avail,
-			output_buf, out_row_ctr, out_rows_avail);
-    if (main->rowgroup_ctr < main->rowgroups_avail)
-      return;			/* Need to suspend */
-    main->context_state = CTX_PREPARE_FOR_IMCU;
-    if (*out_row_ctr >= out_rows_avail)
-      return;			/* Postprocessor exactly filled output buf */
-    /*FALLTHROUGH*/
-  case CTX_PREPARE_FOR_IMCU:
-    /* Prepare to process first M-1 row groups of this iMCU row */
-    main->rowgroup_ctr = 0;
-    main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
-    /* Check for bottom of image: if so, tweak pointers to "duplicate"
-     * the last sample row, and adjust rowgroups_avail to ignore padding rows.
-     */
-    if (main->iMCU_row_ctr == cinfo->total_iMCU_rows)
-      set_bottom_pointers(cinfo);
-    main->context_state = CTX_PROCESS_IMCU;
-    /*FALLTHROUGH*/
-  case CTX_PROCESS_IMCU:
-    /* Call postprocessor using previously set pointers */
-    (*cinfo->post->post_process_data) (cinfo, main->xbuffer[main->whichptr],
-			&main->rowgroup_ctr, main->rowgroups_avail,
-			output_buf, out_row_ctr, out_rows_avail);
-    if (main->rowgroup_ctr < main->rowgroups_avail)
-      return;			/* Need to suspend */
-    /* After the first iMCU, change wraparound pointers to normal state */
-    if (main->iMCU_row_ctr == 1)
-      set_wraparound_pointers(cinfo);
-    /* Prepare to load new iMCU row using other xbuffer list */
-    main->whichptr ^= 1;	/* 0=>1 or 1=>0 */
-    main->buffer_full = FALSE;
-    /* Still need to process last row group of this iMCU row, */
-    /* which is saved at index M+1 of the other xbuffer */
-    main->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
-    main->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
-    main->context_state = CTX_POSTPONED_ROW;
-  }
-}
-
-
-/*
- * Process some data.
- * Final pass of two-pass quantization: just call the postprocessor.
- * Source data will be the postprocessor controller's internal buffer.
- */
-
-#ifdef QUANT_2PASS_SUPPORTED
-
-METHODDEF(void)
-process_data_crank_post (j_decompress_ptr cinfo,
-			 JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-			 JDIMENSION out_rows_avail)
-{
-  (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
-				     (JDIMENSION *) NULL, (JDIMENSION) 0,
-				     output_buf, out_row_ctr, out_rows_avail);
-}
-
-#endif /* QUANT_2PASS_SUPPORTED */
-
-
-/*
- * Initialize main buffer controller.
- */
-
-GLOBAL(void)
-jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
-{
-  my_main_ptr main;
-  int ci, rgroup, ngroups;
-  jpeg_component_info *compptr;
-
-  main = (my_main_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_main_controller));
-  cinfo->main = (struct jpeg_d_main_controller *) main;
-  main->pub.start_pass = start_pass_main;
-
-  if (need_full_buffer)		/* shouldn't happen */
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-
-  /* Allocate the workspace.
-   * ngroups is the number of row groups we need.
-   */
-  if (cinfo->upsample->need_context_rows) {
-    if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
-      ERREXIT(cinfo, JERR_NOTIMPL);
-    alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
-    ngroups = cinfo->min_DCT_scaled_size + 2;
-  } else {
-    ngroups = cinfo->min_DCT_scaled_size;
-  }
-
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
-      cinfo->min_DCT_scaled_size; /* height of a row group of component */
-    main->buffer[ci] = (*cinfo->mem->alloc_sarray)
-			((j_common_ptr) cinfo, JPOOL_IMAGE,
-			 compptr->width_in_blocks * compptr->DCT_scaled_size,
-			 (JDIMENSION) (rgroup * ngroups));
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdmarker.c ./Shared/jpeg-6b/jdmarker.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdmarker.c	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdmarker.c	Wed Dec 31 19:00:00 1969
@@ -1,1360 +0,0 @@
-/*
- * jdmarker.c
- *
- * Copyright (C) 1991-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to decode JPEG datastream markers.
- * Most of the complexity arises from our desire to support input
- * suspension: if not all of the data for a marker is available,
- * we must exit back to the application.  On resumption, we reprocess
- * the marker.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-typedef enum {			/* JPEG marker codes */
-  M_SOF0  = 0xc0,
-  M_SOF1  = 0xc1,
-  M_SOF2  = 0xc2,
-  M_SOF3  = 0xc3,
-  
-  M_SOF5  = 0xc5,
-  M_SOF6  = 0xc6,
-  M_SOF7  = 0xc7,
-  
-  M_JPG   = 0xc8,
-  M_SOF9  = 0xc9,
-  M_SOF10 = 0xca,
-  M_SOF11 = 0xcb,
-  
-  M_SOF13 = 0xcd,
-  M_SOF14 = 0xce,
-  M_SOF15 = 0xcf,
-  
-  M_DHT   = 0xc4,
-  
-  M_DAC   = 0xcc,
-  
-  M_RST0  = 0xd0,
-  M_RST1  = 0xd1,
-  M_RST2  = 0xd2,
-  M_RST3  = 0xd3,
-  M_RST4  = 0xd4,
-  M_RST5  = 0xd5,
-  M_RST6  = 0xd6,
-  M_RST7  = 0xd7,
-  
-  M_SOI   = 0xd8,
-  M_EOI   = 0xd9,
-  M_SOS   = 0xda,
-  M_DQT   = 0xdb,
-  M_DNL   = 0xdc,
-  M_DRI   = 0xdd,
-  M_DHP   = 0xde,
-  M_EXP   = 0xdf,
-  
-  M_APP0  = 0xe0,
-  M_APP1  = 0xe1,
-  M_APP2  = 0xe2,
-  M_APP3  = 0xe3,
-  M_APP4  = 0xe4,
-  M_APP5  = 0xe5,
-  M_APP6  = 0xe6,
-  M_APP7  = 0xe7,
-  M_APP8  = 0xe8,
-  M_APP9  = 0xe9,
-  M_APP10 = 0xea,
-  M_APP11 = 0xeb,
-  M_APP12 = 0xec,
-  M_APP13 = 0xed,
-  M_APP14 = 0xee,
-  M_APP15 = 0xef,
-  
-  M_JPG0  = 0xf0,
-  M_JPG13 = 0xfd,
-  M_COM   = 0xfe,
-  
-  M_TEM   = 0x01,
-  
-  M_ERROR = 0x100
-} JPEG_MARKER;
-
-
-/* Private state */
-
-typedef struct {
-  struct jpeg_marker_reader pub; /* public fields */
-
-  /* Application-overridable marker processing methods */
-  jpeg_marker_parser_method process_COM;
-  jpeg_marker_parser_method process_APPn[16];
-
-  /* Limit on marker data length to save for each marker type */
-  unsigned int length_limit_COM;
-  unsigned int length_limit_APPn[16];
-
-  /* Status of COM/APPn marker saving */
-  jpeg_saved_marker_ptr cur_marker;	/* NULL if not processing a marker */
-  unsigned int bytes_read;		/* data bytes read so far in marker */
-  /* Note: cur_marker is not linked into marker_list until it's all read. */
-} my_marker_reader;
-
-typedef my_marker_reader * my_marker_ptr;
-
-
-/*
- * Macros for fetching data from the data source module.
- *
- * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
- * the current restart point; we update them only when we have reached a
- * suitable place to restart if a suspension occurs.
- */
-
-/* Declare and initialize local copies of input pointer/count */
-#define INPUT_VARS(cinfo)  \
-	struct jpeg_source_mgr * datasrc = (cinfo)->src;  \
-	const JOCTET * next_input_byte = datasrc->next_input_byte;  \
-	size_t bytes_in_buffer = datasrc->bytes_in_buffer
-
-/* Unload the local copies --- do this only at a restart boundary */
-#define INPUT_SYNC(cinfo)  \
-	( datasrc->next_input_byte = next_input_byte,  \
-	  datasrc->bytes_in_buffer = bytes_in_buffer )
-
-/* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
-#define INPUT_RELOAD(cinfo)  \
-	( next_input_byte = datasrc->next_input_byte,  \
-	  bytes_in_buffer = datasrc->bytes_in_buffer )
-
-/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
- * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
- * but we must reload the local copies after a successful fill.
- */
-#define MAKE_BYTE_AVAIL(cinfo,action)  \
-	if (bytes_in_buffer == 0) {  \
-	  if (! (*datasrc->fill_input_buffer) (cinfo))  \
-	    { action; }  \
-	  INPUT_RELOAD(cinfo);  \
-	}
-
-/* Read a byte into variable V.
- * If must suspend, take the specified action (typically "return FALSE").
- */
-#define INPUT_BYTE(cinfo,V,action)  \
-	MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
-		  bytes_in_buffer--; \
-		  V = GETJOCTET(*next_input_byte++); )
-
-/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
- * V should be declared unsigned int or perhaps INT32.
- */
-#define INPUT_2BYTES(cinfo,V,action)  \
-	MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
-		  bytes_in_buffer--; \
-		  V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
-		  MAKE_BYTE_AVAIL(cinfo,action); \
-		  bytes_in_buffer--; \
-		  V += GETJOCTET(*next_input_byte++); )
-
-
-/*
- * Routines to process JPEG markers.
- *
- * Entry condition: JPEG marker itself has been read and its code saved
- *   in cinfo->unread_marker; input restart point is just after the marker.
- *
- * Exit: if return TRUE, have read and processed any parameters, and have
- *   updated the restart point to point after the parameters.
- *   If return FALSE, was forced to suspend before reaching end of
- *   marker parameters; restart point has not been moved.  Same routine
- *   will be called again after application supplies more input data.
- *
- * This approach to suspension assumes that all of a marker's parameters
- * can fit into a single input bufferload.  This should hold for "normal"
- * markers.  Some COM/APPn markers might have large parameter segments
- * that might not fit.  If we are simply dropping such a marker, we use
- * skip_input_data to get past it, and thereby put the problem on the
- * source manager's shoulders.  If we are saving the marker's contents
- * into memory, we use a slightly different convention: when forced to
- * suspend, the marker processor updates the restart point to the end of
- * what it's consumed (ie, the end of the buffer) before returning FALSE.
- * On resumption, cinfo->unread_marker still contains the marker code,
- * but the data source will point to the next chunk of marker data.
- * The marker processor must retain internal state to deal with this.
- *
- * Note that we don't bother to avoid duplicate trace messages if a
- * suspension occurs within marker parameters.  Other side effects
- * require more care.
- */
-
-
-LOCAL(boolean)
-get_soi (j_decompress_ptr cinfo)
-/* Process an SOI marker */
-{
-  int i;
-  
-  TRACEMS(cinfo, 1, JTRC_SOI);
-
-  if (cinfo->marker->saw_SOI)
-    ERREXIT(cinfo, JERR_SOI_DUPLICATE);
-
-  /* Reset all parameters that are defined to be reset by SOI */
-
-  for (i = 0; i < NUM_ARITH_TBLS; i++) {
-    cinfo->arith_dc_L[i] = 0;
-    cinfo->arith_dc_U[i] = 1;
-    cinfo->arith_ac_K[i] = 5;
-  }
-  cinfo->restart_interval = 0;
-
-  /* Set initial assumptions for colorspace etc */
-
-  cinfo->jpeg_color_space = JCS_UNKNOWN;
-  cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
-
-  cinfo->saw_JFIF_marker = FALSE;
-  cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
-  cinfo->JFIF_minor_version = 1;
-  cinfo->density_unit = 0;
-  cinfo->X_density = 1;
-  cinfo->Y_density = 1;
-  cinfo->saw_Adobe_marker = FALSE;
-  cinfo->Adobe_transform = 0;
-
-  cinfo->marker->saw_SOI = TRUE;
-
-  return TRUE;
-}
-
-
-LOCAL(boolean)
-get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
-/* Process a SOFn marker */
-{
-  INT32 length;
-  int c, ci;
-  jpeg_component_info * compptr;
-  INPUT_VARS(cinfo);
-
-  cinfo->progressive_mode = is_prog;
-  cinfo->arith_code = is_arith;
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-
-  INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
-  INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
-  INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
-  INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
-
-  length -= 8;
-
-  TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
-	   (int) cinfo->image_width, (int) cinfo->image_height,
-	   cinfo->num_components);
-
-  if (cinfo->marker->saw_SOF)
-    ERREXIT(cinfo, JERR_SOF_DUPLICATE);
-
-  /* We don't support files in which the image height is initially specified */
-  /* as 0 and is later redefined by DNL.  As long as we have to check that,  */
-  /* might as well have a general sanity check. */
-  if (cinfo->image_height <= 0 || cinfo->image_width <= 0
-      || cinfo->num_components <= 0)
-    ERREXIT(cinfo, JERR_EMPTY_IMAGE);
-
-  if (length != (cinfo->num_components * 3))
-    ERREXIT(cinfo, JERR_BAD_LENGTH);
-
-  if (cinfo->comp_info == NULL)	/* do only once, even if suspend */
-    cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
-			((j_common_ptr) cinfo, JPOOL_IMAGE,
-			 cinfo->num_components * SIZEOF(jpeg_component_info));
-  
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    compptr->component_index = ci;
-    INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
-    INPUT_BYTE(cinfo, c, return FALSE);
-    compptr->h_samp_factor = (c >> 4) & 15;
-    compptr->v_samp_factor = (c     ) & 15;
-    INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
-
-    TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
-	     compptr->component_id, compptr->h_samp_factor,
-	     compptr->v_samp_factor, compptr->quant_tbl_no);
-  }
-
-  cinfo->marker->saw_SOF = TRUE;
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-
-LOCAL(boolean)
-get_sos (j_decompress_ptr cinfo)
-/* Process a SOS marker */
-{
-  INT32 length;
-  int i, ci, n, c, cc;
-  jpeg_component_info * compptr;
-  INPUT_VARS(cinfo);
-
-  if (! cinfo->marker->saw_SOF)
-    ERREXIT(cinfo, JERR_SOS_NO_SOF);
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-
-  INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
-
-  TRACEMS1(cinfo, 1, JTRC_SOS, n);
-
-  if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
-    ERREXIT(cinfo, JERR_BAD_LENGTH);
-
-  cinfo->comps_in_scan = n;
-
-  /* Collect the component-spec parameters */
-
-  for (i = 0; i < n; i++) {
-    INPUT_BYTE(cinfo, cc, return FALSE);
-    INPUT_BYTE(cinfo, c, return FALSE);
-    
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      if (cc == compptr->component_id)
-	goto id_found;
-    }
-
-    ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
-
-  id_found:
-
-    cinfo->cur_comp_info[i] = compptr;
-    compptr->dc_tbl_no = (c >> 4) & 15;
-    compptr->ac_tbl_no = (c     ) & 15;
-    
-    TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
-	     compptr->dc_tbl_no, compptr->ac_tbl_no);
-  }
-
-  /* Collect the additional scan parameters Ss, Se, Ah/Al. */
-  INPUT_BYTE(cinfo, c, return FALSE);
-  cinfo->Ss = c;
-  INPUT_BYTE(cinfo, c, return FALSE);
-  cinfo->Se = c;
-  INPUT_BYTE(cinfo, c, return FALSE);
-  cinfo->Ah = (c >> 4) & 15;
-  cinfo->Al = (c     ) & 15;
-
-  TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
-	   cinfo->Ah, cinfo->Al);
-
-  /* Prepare to scan data & restart markers */
-  cinfo->marker->next_restart_num = 0;
-
-  /* Count another SOS marker */
-  cinfo->input_scan_number++;
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-
-#ifdef D_ARITH_CODING_SUPPORTED
-
-LOCAL(boolean)
-get_dac (j_decompress_ptr cinfo)
-/* Process a DAC marker */
-{
-  INT32 length;
-  int index, val;
-  INPUT_VARS(cinfo);
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-  length -= 2;
-  
-  while (length > 0) {
-    INPUT_BYTE(cinfo, index, return FALSE);
-    INPUT_BYTE(cinfo, val, return FALSE);
-
-    length -= 2;
-
-    TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
-
-    if (index < 0 || index >= (2*NUM_ARITH_TBLS))
-      ERREXIT1(cinfo, JERR_DAC_INDEX, index);
-
-    if (index >= NUM_ARITH_TBLS) { /* define AC table */
-      cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
-    } else {			/* define DC table */
-      cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
-      cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
-      if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
-	ERREXIT1(cinfo, JERR_DAC_VALUE, val);
-    }
-  }
-
-  if (length != 0)
-    ERREXIT(cinfo, JERR_BAD_LENGTH);
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-#else /* ! D_ARITH_CODING_SUPPORTED */
-
-#define get_dac(cinfo)  skip_variable(cinfo)
-
-#endif /* D_ARITH_CODING_SUPPORTED */
-
-
-LOCAL(boolean)
-get_dht (j_decompress_ptr cinfo)
-/* Process a DHT marker */
-{
-  INT32 length;
-  UINT8 bits[17];
-  UINT8 huffval[256];
-  int i, index, count;
-  JHUFF_TBL **htblptr;
-  INPUT_VARS(cinfo);
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-  length -= 2;
-  
-  while (length > 16) {
-    INPUT_BYTE(cinfo, index, return FALSE);
-
-    TRACEMS1(cinfo, 1, JTRC_DHT, index);
-      
-    bits[0] = 0;
-    count = 0;
-    for (i = 1; i <= 16; i++) {
-      INPUT_BYTE(cinfo, bits[i], return FALSE);
-      count += bits[i];
-    }
-
-    length -= 1 + 16;
-
-    TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
-	     bits[1], bits[2], bits[3], bits[4],
-	     bits[5], bits[6], bits[7], bits[8]);
-    TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
-	     bits[9], bits[10], bits[11], bits[12],
-	     bits[13], bits[14], bits[15], bits[16]);
-
-    /* Here we just do minimal validation of the counts to avoid walking
-     * off the end of our table space.  jdhuff.c will check more carefully.
-     */
-    if (count > 256 || ((INT32) count) > length)
-      ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
-
-    for (i = 0; i < count; i++)
-      INPUT_BYTE(cinfo, huffval[i], return FALSE);
-
-    length -= count;
-
-    if (index & 0x10) {		/* AC table definition */
-      index -= 0x10;
-      htblptr = &cinfo->ac_huff_tbl_ptrs[index];
-    } else {			/* DC table definition */
-      htblptr = &cinfo->dc_huff_tbl_ptrs[index];
-    }
-
-    if (index < 0 || index >= NUM_HUFF_TBLS)
-      ERREXIT1(cinfo, JERR_DHT_INDEX, index);
-
-    if (*htblptr == NULL)
-      *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
-  
-    MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
-    MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
-  }
-
-  if (length != 0)
-    ERREXIT(cinfo, JERR_BAD_LENGTH);
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-
-LOCAL(boolean)
-get_dqt (j_decompress_ptr cinfo)
-/* Process a DQT marker */
-{
-  INT32 length;
-  int n, i, prec;
-  unsigned int tmp;
-  JQUANT_TBL *quant_ptr;
-  INPUT_VARS(cinfo);
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-  length -= 2;
-
-  while (length > 0) {
-    INPUT_BYTE(cinfo, n, return FALSE);
-    prec = n >> 4;
-    n &= 0x0F;
-
-    TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
-
-    if (n >= NUM_QUANT_TBLS)
-      ERREXIT1(cinfo, JERR_DQT_INDEX, n);
-      
-    if (cinfo->quant_tbl_ptrs[n] == NULL)
-      cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
-    quant_ptr = cinfo->quant_tbl_ptrs[n];
-
-    for (i = 0; i < DCTSIZE2; i++) {
-      if (prec)
-	INPUT_2BYTES(cinfo, tmp, return FALSE);
-      else
-	INPUT_BYTE(cinfo, tmp, return FALSE);
-      /* We convert the zigzag-order table to natural array order. */
-      quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
-    }
-
-    if (cinfo->err->trace_level >= 2) {
-      for (i = 0; i < DCTSIZE2; i += 8) {
-	TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
-		 quant_ptr->quantval[i],   quant_ptr->quantval[i+1],
-		 quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
-		 quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
-		 quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
-      }
-    }
-
-    length -= DCTSIZE2+1;
-    if (prec) length -= DCTSIZE2;
-  }
-
-  if (length != 0)
-    ERREXIT(cinfo, JERR_BAD_LENGTH);
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-
-LOCAL(boolean)
-get_dri (j_decompress_ptr cinfo)
-/* Process a DRI marker */
-{
-  INT32 length;
-  unsigned int tmp;
-  INPUT_VARS(cinfo);
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-  
-  if (length != 4)
-    ERREXIT(cinfo, JERR_BAD_LENGTH);
-
-  INPUT_2BYTES(cinfo, tmp, return FALSE);
-
-  TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
-
-  cinfo->restart_interval = tmp;
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-
-/*
- * Routines for processing APPn and COM markers.
- * These are either saved in memory or discarded, per application request.
- * APP0 and APP14 are specially checked to see if they are
- * JFIF and Adobe markers, respectively.
- */
-
-#define APP0_DATA_LEN	14	/* Length of interesting data in APP0 */
-#define APP14_DATA_LEN	12	/* Length of interesting data in APP14 */
-#define APPN_DATA_LEN	14	/* Must be the largest of the above!! */
-
-
-LOCAL(void)
-examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
-	      unsigned int datalen, INT32 remaining)
-/* Examine first few bytes from an APP0.
- * Take appropriate action if it is a JFIF marker.
- * datalen is # of bytes at data[], remaining is length of rest of marker data.
- */
-{
-  INT32 totallen = (INT32) datalen + remaining;
-
-  if (datalen >= APP0_DATA_LEN &&
-      GETJOCTET(data[0]) == 0x4A &&
-      GETJOCTET(data[1]) == 0x46 &&
-      GETJOCTET(data[2]) == 0x49 &&
-      GETJOCTET(data[3]) == 0x46 &&
-      GETJOCTET(data[4]) == 0) {
-    /* Found JFIF APP0 marker: save info */
-    cinfo->saw_JFIF_marker = TRUE;
-    cinfo->JFIF_major_version = GETJOCTET(data[5]);
-    cinfo->JFIF_minor_version = GETJOCTET(data[6]);
-    cinfo->density_unit = GETJOCTET(data[7]);
-    cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
-    cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
-    /* Check version.
-     * Major version must be 1, anything else signals an incompatible change.
-     * (We used to treat this as an error, but now it's a nonfatal warning,
-     * because some bozo at Hijaak couldn't read the spec.)
-     * Minor version should be 0..2, but process anyway if newer.
-     */
-    if (cinfo->JFIF_major_version != 1)
-      WARNMS2(cinfo, JWRN_JFIF_MAJOR,
-	      cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
-    /* Generate trace messages */
-    TRACEMS5(cinfo, 1, JTRC_JFIF,
-	     cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
-	     cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
-    /* Validate thumbnail dimensions and issue appropriate messages */
-    if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
-      TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
-	       GETJOCTET(data[12]), GETJOCTET(data[13]));
-    totallen -= APP0_DATA_LEN;
-    if (totallen !=
-	((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
-      TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
-  } else if (datalen >= 6 &&
-      GETJOCTET(data[0]) == 0x4A &&
-      GETJOCTET(data[1]) == 0x46 &&
-      GETJOCTET(data[2]) == 0x58 &&
-      GETJOCTET(data[3]) == 0x58 &&
-      GETJOCTET(data[4]) == 0) {
-    /* Found JFIF "JFXX" extension APP0 marker */
-    /* The library doesn't actually do anything with these,
-     * but we try to produce a helpful trace message.
-     */
-    switch (GETJOCTET(data[5])) {
-    case 0x10:
-      TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
-      break;
-    case 0x11:
-      TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
-      break;
-    case 0x13:
-      TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
-      break;
-    default:
-      TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
-	       GETJOCTET(data[5]), (int) totallen);
-      break;
-    }
-  } else {
-    /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
-    TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
-  }
-}
-
-
-LOCAL(void)
-examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
-	       unsigned int datalen, INT32 remaining)
-/* Examine first few bytes from an APP14.
- * Take appropriate action if it is an Adobe marker.
- * datalen is # of bytes at data[], remaining is length of rest of marker data.
- */
-{
-  unsigned int version, flags0, flags1, transform;
-
-  if (datalen >= APP14_DATA_LEN &&
-      GETJOCTET(data[0]) == 0x41 &&
-      GETJOCTET(data[1]) == 0x64 &&
-      GETJOCTET(data[2]) == 0x6F &&
-      GETJOCTET(data[3]) == 0x62 &&
-      GETJOCTET(data[4]) == 0x65) {
-    /* Found Adobe APP14 marker */
-    version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
-    flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
-    flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
-    transform = GETJOCTET(data[11]);
-    TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
-    cinfo->saw_Adobe_marker = TRUE;
-    cinfo->Adobe_transform = (UINT8) transform;
-  } else {
-    /* Start of APP14 does not match "Adobe", or too short */
-    TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
-  }
-}
-
-
-METHODDEF(boolean)
-get_interesting_appn (j_decompress_ptr cinfo)
-/* Process an APP0 or APP14 marker without saving it */
-{
-  INT32 length;
-  JOCTET b[APPN_DATA_LEN];
-  unsigned int i, numtoread;
-  INPUT_VARS(cinfo);
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-  length -= 2;
-
-  /* get the interesting part of the marker data */
-  if (length >= APPN_DATA_LEN)
-    numtoread = APPN_DATA_LEN;
-  else if (length > 0)
-    numtoread = (unsigned int) length;
-  else
-    numtoread = 0;
-  for (i = 0; i < numtoread; i++)
-    INPUT_BYTE(cinfo, b[i], return FALSE);
-  length -= numtoread;
-
-  /* process it */
-  switch (cinfo->unread_marker) {
-  case M_APP0:
-    examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
-    break;
-  case M_APP14:
-    examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
-    break;
-  default:
-    /* can't get here unless jpeg_save_markers chooses wrong processor */
-    ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
-    break;
-  }
-
-  /* skip any remaining data -- could be lots */
-  INPUT_SYNC(cinfo);
-  if (length > 0)
-    (*cinfo->src->skip_input_data) (cinfo, (long) length);
-
-  return TRUE;
-}
-
-
-#ifdef SAVE_MARKERS_SUPPORTED
-
-METHODDEF(boolean)
-save_marker (j_decompress_ptr cinfo)
-/* Save an APPn or COM marker into the marker list */
-{
-  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
-  jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
-  unsigned int bytes_read, data_length;
-  JOCTET FAR * data;
-  INT32 length = 0;
-  INPUT_VARS(cinfo);
-
-  if (cur_marker == NULL) {
-    /* begin reading a marker */
-    INPUT_2BYTES(cinfo, length, return FALSE);
-    length -= 2;
-    if (length >= 0) {		/* watch out for bogus length word */
-      /* figure out how much we want to save */
-      unsigned int limit;
-      if (cinfo->unread_marker == (int) M_COM)
-	limit = marker->length_limit_COM;
-      else
-	limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
-      if ((unsigned int) length < limit)
-	limit = (unsigned int) length;
-      /* allocate and initialize the marker item */
-      cur_marker = (jpeg_saved_marker_ptr)
-	(*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				    SIZEOF(struct jpeg_marker_struct) + limit);
-      cur_marker->next = NULL;
-      cur_marker->marker = (UINT8) cinfo->unread_marker;
-      cur_marker->original_length = (unsigned int) length;
-      cur_marker->data_length = limit;
-      /* data area is just beyond the jpeg_marker_struct */
-      data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
-      marker->cur_marker = cur_marker;
-      marker->bytes_read = 0;
-      bytes_read = 0;
-      data_length = limit;
-    } else {
-      /* deal with bogus length word */
-      bytes_read = data_length = 0;
-      data = NULL;
-    }
-  } else {
-    /* resume reading a marker */
-    bytes_read = marker->bytes_read;
-    data_length = cur_marker->data_length;
-    data = cur_marker->data + bytes_read;
-  }
-
-  while (bytes_read < data_length) {
-    INPUT_SYNC(cinfo);		/* move the restart point to here */
-    marker->bytes_read = bytes_read;
-    /* If there's not at least one byte in buffer, suspend */
-    MAKE_BYTE_AVAIL(cinfo, return FALSE);
-    /* Copy bytes with reasonable rapidity */
-    while (bytes_read < data_length && bytes_in_buffer > 0) {
-      *data++ = *next_input_byte++;
-      bytes_in_buffer--;
-      bytes_read++;
-    }
-  }
-
-  /* Done reading what we want to read */
-  if (cur_marker != NULL) {	/* will be NULL if bogus length word */
-    /* Add new marker to end of list */
-    if (cinfo->marker_list == NULL) {
-      cinfo->marker_list = cur_marker;
-    } else {
-      jpeg_saved_marker_ptr prev = cinfo->marker_list;
-      while (prev->next != NULL)
-	prev = prev->next;
-      prev->next = cur_marker;
-    }
-    /* Reset pointer & calc remaining data length */
-    data = cur_marker->data;
-    length = cur_marker->original_length - data_length;
-  }
-  /* Reset to initial state for next marker */
-  marker->cur_marker = NULL;
-
-  /* Process the marker if interesting; else just make a generic trace msg */
-  switch (cinfo->unread_marker) {
-  case M_APP0:
-    examine_app0(cinfo, data, data_length, length);
-    break;
-  case M_APP14:
-    examine_app14(cinfo, data, data_length, length);
-    break;
-  default:
-    TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
-	     (int) (data_length + length));
-    break;
-  }
-
-  /* skip any remaining data -- could be lots */
-  INPUT_SYNC(cinfo);		/* do before skip_input_data */
-  if (length > 0)
-    (*cinfo->src->skip_input_data) (cinfo, (long) length);
-
-  return TRUE;
-}
-
-#endif /* SAVE_MARKERS_SUPPORTED */
-
-
-METHODDEF(boolean)
-skip_variable (j_decompress_ptr cinfo)
-/* Skip over an unknown or uninteresting variable-length marker */
-{
-  INT32 length;
-  INPUT_VARS(cinfo);
-
-  INPUT_2BYTES(cinfo, length, return FALSE);
-  length -= 2;
-  
-  TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
-
-  INPUT_SYNC(cinfo);		/* do before skip_input_data */
-  if (length > 0)
-    (*cinfo->src->skip_input_data) (cinfo, (long) length);
-
-  return TRUE;
-}
-
-
-/*
- * Find the next JPEG marker, save it in cinfo->unread_marker.
- * Returns FALSE if had to suspend before reaching a marker;
- * in that case cinfo->unread_marker is unchanged.
- *
- * Note that the result might not be a valid marker code,
- * but it will never be 0 or FF.
- */
-
-LOCAL(boolean)
-next_marker (j_decompress_ptr cinfo)
-{
-  int c;
-  INPUT_VARS(cinfo);
-
-  for (;;) {
-    INPUT_BYTE(cinfo, c, return FALSE);
-    /* Skip any non-FF bytes.
-     * This may look a bit inefficient, but it will not occur in a valid file.
-     * We sync after each discarded byte so that a suspending data source
-     * can discard the byte from its buffer.
-     */
-    while (c != 0xFF) {
-      cinfo->marker->discarded_bytes++;
-      INPUT_SYNC(cinfo);
-      INPUT_BYTE(cinfo, c, return FALSE);
-    }
-    /* This loop swallows any duplicate FF bytes.  Extra FFs are legal as
-     * pad bytes, so don't count them in discarded_bytes.  We assume there
-     * will not be so many consecutive FF bytes as to overflow a suspending
-     * data source's input buffer.
-     */
-    do {
-      INPUT_BYTE(cinfo, c, return FALSE);
-    } while (c == 0xFF);
-    if (c != 0)
-      break;			/* found a valid marker, exit loop */
-    /* Reach here if we found a stuffed-zero data sequence (FF/00).
-     * Discard it and loop back to try again.
-     */
-    cinfo->marker->discarded_bytes += 2;
-    INPUT_SYNC(cinfo);
-  }
-
-  if (cinfo->marker->discarded_bytes != 0) {
-    WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
-    cinfo->marker->discarded_bytes = 0;
-  }
-
-  cinfo->unread_marker = c;
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-
-LOCAL(boolean)
-first_marker (j_decompress_ptr cinfo)
-/* Like next_marker, but used to obtain the initial SOI marker. */
-/* For this marker, we do not allow preceding garbage or fill; otherwise,
- * we might well scan an entire input file before realizing it ain't JPEG.
- * If an application wants to process non-JFIF files, it must seek to the
- * SOI before calling the JPEG library.
- */
-{
-  int c, c2;
-  INPUT_VARS(cinfo);
-
-  INPUT_BYTE(cinfo, c, return FALSE);
-  INPUT_BYTE(cinfo, c2, return FALSE);
-  if (c != 0xFF || c2 != (int) M_SOI)
-    ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
-
-  cinfo->unread_marker = c2;
-
-  INPUT_SYNC(cinfo);
-  return TRUE;
-}
-
-
-/*
- * Read markers until SOS or EOI.
- *
- * Returns same codes as are defined for jpeg_consume_input:
- * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
- */
-
-METHODDEF(int)
-read_markers (j_decompress_ptr cinfo)
-{
-  /* Outer loop repeats once for each marker. */
-  for (;;) {
-    /* Collect the marker proper, unless we already did. */
-    /* NB: first_marker() enforces the requirement that SOI appear first. */
-    if (cinfo->unread_marker == 0) {
-      if (! cinfo->marker->saw_SOI) {
-	if (! first_marker(cinfo))
-	  return JPEG_SUSPENDED;
-      } else {
-	if (! next_marker(cinfo))
-	  return JPEG_SUSPENDED;
-      }
-    }
-    /* At this point cinfo->unread_marker contains the marker code and the
-     * input point is just past the marker proper, but before any parameters.
-     * A suspension will cause us to return with this state still true.
-     */
-    switch (cinfo->unread_marker) {
-    case M_SOI:
-      if (! get_soi(cinfo))
-	return JPEG_SUSPENDED;
-      break;
-
-    case M_SOF0:		/* Baseline */
-    case M_SOF1:		/* Extended sequential, Huffman */
-      if (! get_sof(cinfo, FALSE, FALSE))
-	return JPEG_SUSPENDED;
-      break;
-
-    case M_SOF2:		/* Progressive, Huffman */
-      if (! get_sof(cinfo, TRUE, FALSE))
-	return JPEG_SUSPENDED;
-      break;
-
-    case M_SOF9:		/* Extended sequential, arithmetic */
-      if (! get_sof(cinfo, FALSE, TRUE))
-	return JPEG_SUSPENDED;
-      break;
-
-    case M_SOF10:		/* Progressive, arithmetic */
-      if (! get_sof(cinfo, TRUE, TRUE))
-	return JPEG_SUSPENDED;
-      break;
-
-    /* Currently unsupported SOFn types */
-    case M_SOF3:		/* Lossless, Huffman */
-    case M_SOF5:		/* Differential sequential, Huffman */
-    case M_SOF6:		/* Differential progressive, Huffman */
-    case M_SOF7:		/* Differential lossless, Huffman */
-    case M_JPG:			/* Reserved for JPEG extensions */
-    case M_SOF11:		/* Lossless, arithmetic */
-    case M_SOF13:		/* Differential sequential, arithmetic */
-    case M_SOF14:		/* Differential progressive, arithmetic */
-    case M_SOF15:		/* Differential lossless, arithmetic */
-      ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
-      break;
-
-    case M_SOS:
-      if (! get_sos(cinfo))
-	return JPEG_SUSPENDED;
-      cinfo->unread_marker = 0;	/* processed the marker */
-      return JPEG_REACHED_SOS;
-    
-    case M_EOI:
-      TRACEMS(cinfo, 1, JTRC_EOI);
-      cinfo->unread_marker = 0;	/* processed the marker */
-      return JPEG_REACHED_EOI;
-      
-    case M_DAC:
-      if (! get_dac(cinfo))
-	return JPEG_SUSPENDED;
-      break;
-      
-    case M_DHT:
-      if (! get_dht(cinfo))
-	return JPEG_SUSPENDED;
-      break;
-      
-    case M_DQT:
-      if (! get_dqt(cinfo))
-	return JPEG_SUSPENDED;
-      break;
-      
-    case M_DRI:
-      if (! get_dri(cinfo))
-	return JPEG_SUSPENDED;
-      break;
-      
-    case M_APP0:
-    case M_APP1:
-    case M_APP2:
-    case M_APP3:
-    case M_APP4:
-    case M_APP5:
-    case M_APP6:
-    case M_APP7:
-    case M_APP8:
-    case M_APP9:
-    case M_APP10:
-    case M_APP11:
-    case M_APP12:
-    case M_APP13:
-    case M_APP14:
-    case M_APP15:
-      if (! (*((my_marker_ptr) cinfo->marker)->process_APPn[
-		cinfo->unread_marker - (int) M_APP0]) (cinfo))
-	return JPEG_SUSPENDED;
-      break;
-      
-    case M_COM:
-      if (! (*((my_marker_ptr) cinfo->marker)->process_COM) (cinfo))
-	return JPEG_SUSPENDED;
-      break;
-
-    case M_RST0:		/* these are all parameterless */
-    case M_RST1:
-    case M_RST2:
-    case M_RST3:
-    case M_RST4:
-    case M_RST5:
-    case M_RST6:
-    case M_RST7:
-    case M_TEM:
-      TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
-      break;
-
-    case M_DNL:			/* Ignore DNL ... perhaps the wrong thing */
-      if (! skip_variable(cinfo))
-	return JPEG_SUSPENDED;
-      break;
-
-    default:			/* must be DHP, EXP, JPGn, or RESn */
-      /* For now, we treat the reserved markers as fatal errors since they are
-       * likely to be used to signal incompatible JPEG Part 3 extensions.
-       * Once the JPEG 3 version-number marker is well defined, this code
-       * ought to change!
-       */
-      ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
-      break;
-    }
-    /* Successfully processed marker, so reset state variable */
-    cinfo->unread_marker = 0;
-  } /* end loop */
-}
-
-
-/*
- * Read a restart marker, which is expected to appear next in the datastream;
- * if the marker is not there, take appropriate recovery action.
- * Returns FALSE if suspension is required.
- *
- * This is called by the entropy decoder after it has read an appropriate
- * number of MCUs.  cinfo->unread_marker may be nonzero if the entropy decoder
- * has already read a marker from the data source.  Under normal conditions
- * cinfo->unread_marker will be reset to 0 before returning; if not reset,
- * it holds a marker which the decoder will be unable to read past.
- */
-
-METHODDEF(boolean)
-read_restart_marker (j_decompress_ptr cinfo)
-{
-  /* Obtain a marker unless we already did. */
-  /* Note that next_marker will complain if it skips any data. */
-  if (cinfo->unread_marker == 0) {
-    if (! next_marker(cinfo))
-      return FALSE;
-  }
-
-  if (cinfo->unread_marker ==
-      ((int) M_RST0 + cinfo->marker->next_restart_num)) {
-    /* Normal case --- swallow the marker and let entropy decoder continue */
-    TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
-    cinfo->unread_marker = 0;
-  } else {
-    /* Uh-oh, the restart markers have been messed up. */
-    /* Let the data source manager determine how to resync. */
-    if (! (*cinfo->src->resync_to_restart) (cinfo,
-					    cinfo->marker->next_restart_num))
-      return FALSE;
-  }
-
-  /* Update next-restart state */
-  cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
-
-  return TRUE;
-}
-
-
-/*
- * This is the default resync_to_restart method for data source managers
- * to use if they don't have any better approach.  Some data source managers
- * may be able to back up, or may have additional knowledge about the data
- * which permits a more intelligent recovery strategy; such managers would
- * presumably supply their own resync method.
- *
- * read_restart_marker calls resync_to_restart if it finds a marker other than
- * the restart marker it was expecting.  (This code is *not* used unless
- * a nonzero restart interval has been declared.)  cinfo->unread_marker is
- * the marker code actually found (might be anything, except 0 or FF).
- * The desired restart marker number (0..7) is passed as a parameter.
- * This routine is supposed to apply whatever error recovery strategy seems
- * appropriate in order to position the input stream to the next data segment.
- * Note that cinfo->unread_marker is treated as a marker appearing before
- * the current data-source input point; usually it should be reset to zero
- * before returning.
- * Returns FALSE if suspension is required.
- *
- * This implementation is substantially constrained by wanting to treat the
- * input as a data stream; this means we can't back up.  Therefore, we have
- * only the following actions to work with:
- *   1. Simply discard the marker and let the entropy decoder resume at next
- *      byte of file.
- *   2. Read forward until we find another marker, discarding intervening
- *      data.  (In theory we could look ahead within the current bufferload,
- *      without having to discard data if we don't find the desired marker.
- *      This idea is not implemented here, in part because it makes behavior
- *      dependent on buffer size and chance buffer-boundary positions.)
- *   3. Leave the marker unread (by failing to zero cinfo->unread_marker).
- *      This will cause the entropy decoder to process an empty data segment,
- *      inserting dummy zeroes, and then we will reprocess the marker.
- *
- * #2 is appropriate if we think the desired marker lies ahead, while #3 is
- * appropriate if the found marker is a future restart marker (indicating
- * that we have missed the desired restart marker, probably because it got
- * corrupted).
- * We apply #2 or #3 if the found marker is a restart marker no more than
- * two counts behind or ahead of the expected one.  We also apply #2 if the
- * found marker is not a legal JPEG marker code (it's certainly bogus data).
- * If the found marker is a restart marker more than 2 counts away, we do #1
- * (too much risk that the marker is erroneous; with luck we will be able to
- * resync at some future point).
- * For any valid non-restart JPEG marker, we apply #3.  This keeps us from
- * overrunning the end of a scan.  An implementation limited to single-scan
- * files might find it better to apply #2 for markers other than EOI, since
- * any other marker would have to be bogus data in that case.
- */
-
-GLOBAL(boolean)
-jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
-{
-  int marker = cinfo->unread_marker;
-  int action = 1;
-  
-  /* Always put up a warning. */
-  WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
-  
-  /* Outer loop handles repeated decision after scanning forward. */
-  for (;;) {
-    if (marker < (int) M_SOF0)
-      action = 2;		/* invalid marker */
-    else if (marker < (int) M_RST0 || marker > (int) M_RST7)
-      action = 3;		/* valid non-restart marker */
-    else {
-      if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
-	  marker == ((int) M_RST0 + ((desired+2) & 7)))
-	action = 3;		/* one of the next two expected restarts */
-      else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
-	       marker == ((int) M_RST0 + ((desired-2) & 7)))
-	action = 2;		/* a prior restart, so advance */
-      else
-	action = 1;		/* desired restart or too far away */
-    }
-    TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
-    switch (action) {
-    case 1:
-      /* Discard marker and let entropy decoder resume processing. */
-      cinfo->unread_marker = 0;
-      return TRUE;
-    case 2:
-      /* Scan to the next marker, and repeat the decision loop. */
-      if (! next_marker(cinfo))
-	return FALSE;
-      marker = cinfo->unread_marker;
-      break;
-    case 3:
-      /* Return without advancing past this marker. */
-      /* Entropy decoder will be forced to process an empty segment. */
-      return TRUE;
-    }
-  } /* end loop */
-}
-
-
-/*
- * Reset marker processing state to begin a fresh datastream.
- */
-
-METHODDEF(void)
-reset_marker_reader (j_decompress_ptr cinfo)
-{
-  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
-
-  cinfo->comp_info = NULL;		/* until allocated by get_sof */
-  cinfo->input_scan_number = 0;		/* no SOS seen yet */
-  cinfo->unread_marker = 0;		/* no pending marker */
-  marker->pub.saw_SOI = FALSE;		/* set internal state too */
-  marker->pub.saw_SOF = FALSE;
-  marker->pub.discarded_bytes = 0;
-  marker->cur_marker = NULL;
-}
-
-
-/*
- * Initialize the marker reader module.
- * This is called only once, when the decompression object is created.
- */
-
-GLOBAL(void)
-jinit_marker_reader (j_decompress_ptr cinfo)
-{
-  my_marker_ptr marker;
-  int i;
-
-  /* Create subobject in permanent pool */
-  marker = (my_marker_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
-				SIZEOF(my_marker_reader));
-  cinfo->marker = (struct jpeg_marker_reader *) marker;
-  /* Initialize public method pointers */
-  marker->pub.reset_marker_reader = reset_marker_reader;
-  marker->pub.read_markers = read_markers;
-  marker->pub.read_restart_marker = read_restart_marker;
-  /* Initialize COM/APPn processing.
-   * By default, we examine and then discard APP0 and APP14,
-   * but simply discard COM and all other APPn.
-   */
-  marker->process_COM = skip_variable;
-  marker->length_limit_COM = 0;
-  for (i = 0; i < 16; i++) {
-    marker->process_APPn[i] = skip_variable;
-    marker->length_limit_APPn[i] = 0;
-  }
-  marker->process_APPn[0] = get_interesting_appn;
-  marker->process_APPn[14] = get_interesting_appn;
-  /* Reset marker processing state */
-  reset_marker_reader(cinfo);
-}
-
-
-/*
- * Control saving of COM and APPn markers into marker_list.
- */
-
-#ifdef SAVE_MARKERS_SUPPORTED
-
-GLOBAL(void)
-jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
-		   unsigned int length_limit)
-{
-  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
-  long maxlength;
-  jpeg_marker_parser_method processor;
-
-  /* Length limit mustn't be larger than what we can allocate
-   * (should only be a concern in a 16-bit environment).
-   */
-  maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
-  if (((long) length_limit) > maxlength)
-    length_limit = (unsigned int) maxlength;
-
-  /* Choose processor routine to use.
-   * APP0/APP14 have special requirements.
-   */
-  if (length_limit) {
-    processor = save_marker;
-    /* If saving APP0/APP14, save at least enough for our internal use. */
-    if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
-      length_limit = APP0_DATA_LEN;
-    else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
-      length_limit = APP14_DATA_LEN;
-  } else {
-    processor = skip_variable;
-    /* If discarding APP0/APP14, use our regular on-the-fly processor. */
-    if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
-      processor = get_interesting_appn;
-  }
-
-  if (marker_code == (int) M_COM) {
-    marker->process_COM = processor;
-    marker->length_limit_COM = length_limit;
-  } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
-    marker->process_APPn[marker_code - (int) M_APP0] = processor;
-    marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
-  } else
-    ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
-}
-
-#endif /* SAVE_MARKERS_SUPPORTED */
-
-
-/*
- * Install a special processing method for COM or APPn markers.
- */
-
-GLOBAL(void)
-jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
-			   jpeg_marker_parser_method routine)
-{
-  my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
-
-  if (marker_code == (int) M_COM)
-    marker->process_COM = routine;
-  else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
-    marker->process_APPn[marker_code - (int) M_APP0] = routine;
-  else
-    ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdmaster.c ./Shared/jpeg-6b/jdmaster.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdmaster.c	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdmaster.c	Wed Dec 31 19:00:00 1969
@@ -1,557 +0,0 @@
-/*
- * jdmaster.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains master control logic for the JPEG decompressor.
- * These routines are concerned with selecting the modules to be executed
- * and with determining the number of passes and the work to be done in each
- * pass.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Private state */
-
-typedef struct {
-  struct jpeg_decomp_master pub; /* public fields */
-
-  int pass_number;		/* # of passes completed */
-
-  boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
-
-  /* Saved references to initialized quantizer modules,
-   * in case we need to switch modes.
-   */
-  struct jpeg_color_quantizer * quantizer_1pass;
-  struct jpeg_color_quantizer * quantizer_2pass;
-} my_decomp_master;
-
-typedef my_decomp_master * my_master_ptr;
-
-
-/*
- * Determine whether merged upsample/color conversion should be used.
- * CRUCIAL: this must match the actual capabilities of jdmerge.c!
- */
-
-LOCAL(boolean)
-use_merged_upsample (j_decompress_ptr cinfo)
-{
-#ifdef UPSAMPLE_MERGING_SUPPORTED
-  /* Merging is the equivalent of plain box-filter upsampling */
-  if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
-    return FALSE;
-  /* jdmerge.c only supports YCC=>RGB color conversion */
-  if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
-      cinfo->out_color_space != JCS_RGB ||
-      cinfo->out_color_components != RGB_PIXELSIZE)
-    return FALSE;
-  /* and it only handles 2h1v or 2h2v sampling ratios */
-  if (cinfo->comp_info[0].h_samp_factor != 2 ||
-      cinfo->comp_info[1].h_samp_factor != 1 ||
-      cinfo->comp_info[2].h_samp_factor != 1 ||
-      cinfo->comp_info[0].v_samp_factor >  2 ||
-      cinfo->comp_info[1].v_samp_factor != 1 ||
-      cinfo->comp_info[2].v_samp_factor != 1)
-    return FALSE;
-  /* furthermore, it doesn't work if we've scaled the IDCTs differently */
-  if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
-      cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
-      cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
-    return FALSE;
-  /* ??? also need to test for upsample-time rescaling, when & if supported */
-  return TRUE;			/* by golly, it'll work... */
-#else
-  return FALSE;
-#endif
-}
-
-
-/*
- * Compute output image dimensions and related values.
- * NOTE: this is exported for possible use by application.
- * Hence it mustn't do anything that can't be done twice.
- * Also note that it may be called before the master module is initialized!
- */
-
-GLOBAL(void)
-jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
-/* Do computations that are needed before master selection phase */
-{
-#ifdef IDCT_SCALING_SUPPORTED
-  int ci;
-  jpeg_component_info *compptr;
-#endif
-
-  /* Prevent application from calling me at wrong times */
-  if (cinfo->global_state != DSTATE_READY)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-#ifdef IDCT_SCALING_SUPPORTED
-
-  /* Compute actual output image dimensions and DCT scaling choices. */
-  if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
-    /* Provide 1/8 scaling */
-    cinfo->output_width = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width, 8L);
-    cinfo->output_height = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height, 8L);
-    cinfo->min_DCT_scaled_size = 1;
-  } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
-    /* Provide 1/4 scaling */
-    cinfo->output_width = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width, 4L);
-    cinfo->output_height = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height, 4L);
-    cinfo->min_DCT_scaled_size = 2;
-  } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
-    /* Provide 1/2 scaling */
-    cinfo->output_width = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width, 2L);
-    cinfo->output_height = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height, 2L);
-    cinfo->min_DCT_scaled_size = 4;
-  } else {
-    /* Provide 1/1 scaling */
-    cinfo->output_width = cinfo->image_width;
-    cinfo->output_height = cinfo->image_height;
-    cinfo->min_DCT_scaled_size = DCTSIZE;
-  }
-  /* In selecting the actual DCT scaling for each component, we try to
-   * scale up the chroma components via IDCT scaling rather than upsampling.
-   * This saves time if the upsampler gets to use 1:1 scaling.
-   * Note this code assumes that the supported DCT scalings are powers of 2.
-   */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    int ssize = cinfo->min_DCT_scaled_size;
-    while (ssize < DCTSIZE &&
-	   (compptr->h_samp_factor * ssize * 2 <=
-	    cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
-	   (compptr->v_samp_factor * ssize * 2 <=
-	    cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
-      ssize = ssize * 2;
-    }
-    compptr->DCT_scaled_size = ssize;
-  }
-
-  /* Recompute downsampled dimensions of components;
-   * application needs to know these if using raw downsampled data.
-   */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Size in samples, after IDCT scaling */
-    compptr->downsampled_width = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_width *
-		    (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
-		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
-    compptr->downsampled_height = (JDIMENSION)
-      jdiv_round_up((long) cinfo->image_height *
-		    (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
-		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
-  }
-
-#else /* !IDCT_SCALING_SUPPORTED */
-
-  /* Hardwire it to "no scaling" */
-  cinfo->output_width = cinfo->image_width;
-  cinfo->output_height = cinfo->image_height;
-  /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
-   * and has computed unscaled downsampled_width and downsampled_height.
-   */
-
-#endif /* IDCT_SCALING_SUPPORTED */
-
-  /* Report number of components in selected colorspace. */
-  /* Probably this should be in the color conversion module... */
-  switch (cinfo->out_color_space) {
-  case JCS_GRAYSCALE:
-    cinfo->out_color_components = 1;
-    break;
-  case JCS_RGB:
-#if RGB_PIXELSIZE != 3
-    cinfo->out_color_components = RGB_PIXELSIZE;
-    break;
-#endif /* else share code with YCbCr */
-  case JCS_YCbCr:
-    cinfo->out_color_components = 3;
-    break;
-  case JCS_CMYK:
-  case JCS_YCCK:
-    cinfo->out_color_components = 4;
-    break;
-  default:			/* else must be same colorspace as in file */
-    cinfo->out_color_components = cinfo->num_components;
-    break;
-  }
-  cinfo->output_components = (cinfo->quantize_colors ? 1 :
-			      cinfo->out_color_components);
-
-  /* See if upsampler will want to emit more than one row at a time */
-  if (use_merged_upsample(cinfo))
-    cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
-  else
-    cinfo->rec_outbuf_height = 1;
-}
-
-
-/*
- * Several decompression processes need to range-limit values to the range
- * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
- * due to noise introduced by quantization, roundoff error, etc.  These
- * processes are inner loops and need to be as fast as possible.  On most
- * machines, particularly CPUs with pipelines or instruction prefetch,
- * a (subscript-check-less) C table lookup
- *		x = sample_range_limit[x];
- * is faster than explicit tests
- *		if (x < 0)  x = 0;
- *		else if (x > MAXJSAMPLE)  x = MAXJSAMPLE;
- * These processes all use a common table prepared by the routine below.
- *
- * For most steps we can mathematically guarantee that the initial value
- * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
- * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient.  But for the initial
- * limiting step (just after the IDCT), a wildly out-of-range value is 
- * possible if the input data is corrupt.  To avoid any chance of indexing
- * off the end of memory and getting a bad-pointer trap, we perform the
- * post-IDCT limiting thus:
- *		x = range_limit[x & MASK];
- * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
- * samples.  Under normal circumstances this is more than enough range and
- * a correct output will be generated; with bogus input data the mask will
- * cause wraparound, and we will safely generate a bogus-but-in-range output.
- * For the post-IDCT step, we want to convert the data from signed to unsigned
- * representation by adding CENTERJSAMPLE at the same time that we limit it.
- * So the post-IDCT limiting table ends up looking like this:
- *   CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
- *   MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
- *   0          (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
- *   0,1,...,CENTERJSAMPLE-1
- * Negative inputs select values from the upper half of the table after
- * masking.
- *
- * We can save some space by overlapping the start of the post-IDCT table
- * with the simpler range limiting table.  The post-IDCT table begins at
- * sample_range_limit + CENTERJSAMPLE.
- *
- * Note that the table is allocated in near data space on PCs; it's small
- * enough and used often enough to justify this.
- */
-
-LOCAL(void)
-prepare_range_limit_table (j_decompress_ptr cinfo)
-/* Allocate and fill in the sample_range_limit table */
-{
-  JSAMPLE * table;
-  int i;
-
-  table = (JSAMPLE *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-		(5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
-  table += (MAXJSAMPLE+1);	/* allow negative subscripts of simple table */
-  cinfo->sample_range_limit = table;
-  /* First segment of "simple" table: limit[x] = 0 for x < 0 */
-  MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
-  /* Main part of "simple" table: limit[x] = x */
-  for (i = 0; i <= MAXJSAMPLE; i++)
-    table[i] = (JSAMPLE) i;
-  table += CENTERJSAMPLE;	/* Point to where post-IDCT table starts */
-  /* End of simple table, rest of first half of post-IDCT table */
-  for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
-    table[i] = MAXJSAMPLE;
-  /* Second half of post-IDCT table */
-  MEMZERO(table + (2 * (MAXJSAMPLE+1)),
-	  (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
-  MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
-	  cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
-}
-
-
-/*
- * Master selection of decompression modules.
- * This is done once at jpeg_start_decompress time.  We determine
- * which modules will be used and give them appropriate initialization calls.
- * We also initialize the decompressor input side to begin consuming data.
- *
- * Since jpeg_read_header has finished, we know what is in the SOF
- * and (first) SOS markers.  We also have all the application parameter
- * settings.
- */
-
-LOCAL(void)
-master_selection (j_decompress_ptr cinfo)
-{
-  my_master_ptr master = (my_master_ptr) cinfo->master;
-  boolean use_c_buffer;
-  long samplesperrow;
-  JDIMENSION jd_samplesperrow;
-
-  /* Initialize dimensions and other stuff */
-  jpeg_calc_output_dimensions(cinfo);
-  prepare_range_limit_table(cinfo);
-
-  /* Width of an output scanline must be representable as JDIMENSION. */
-  samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
-  jd_samplesperrow = (JDIMENSION) samplesperrow;
-  if ((long) jd_samplesperrow != samplesperrow)
-    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
-
-  /* Initialize my private state */
-  master->pass_number = 0;
-  master->using_merged_upsample = use_merged_upsample(cinfo);
-
-  /* Color quantizer selection */
-  master->quantizer_1pass = NULL;
-  master->quantizer_2pass = NULL;
-  /* No mode changes if not using buffered-image mode. */
-  if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
-    cinfo->enable_1pass_quant = FALSE;
-    cinfo->enable_external_quant = FALSE;
-    cinfo->enable_2pass_quant = FALSE;
-  }
-  if (cinfo->quantize_colors) {
-    if (cinfo->raw_data_out)
-      ERREXIT(cinfo, JERR_NOTIMPL);
-    /* 2-pass quantizer only works in 3-component color space. */
-    if (cinfo->out_color_components != 3) {
-      cinfo->enable_1pass_quant = TRUE;
-      cinfo->enable_external_quant = FALSE;
-      cinfo->enable_2pass_quant = FALSE;
-      cinfo->colormap = NULL;
-    } else if (cinfo->colormap != NULL) {
-      cinfo->enable_external_quant = TRUE;
-    } else if (cinfo->two_pass_quantize) {
-      cinfo->enable_2pass_quant = TRUE;
-    } else {
-      cinfo->enable_1pass_quant = TRUE;
-    }
-
-    if (cinfo->enable_1pass_quant) {
-#ifdef QUANT_1PASS_SUPPORTED
-      jinit_1pass_quantizer(cinfo);
-      master->quantizer_1pass = cinfo->cquantize;
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-    }
-
-    /* We use the 2-pass code to map to external colormaps. */
-    if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
-#ifdef QUANT_2PASS_SUPPORTED
-      jinit_2pass_quantizer(cinfo);
-      master->quantizer_2pass = cinfo->cquantize;
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-    }
-    /* If both quantizers are initialized, the 2-pass one is left active;
-     * this is necessary for starting with quantization to an external map.
-     */
-  }
-
-  /* Post-processing: in particular, color conversion first */
-  if (! cinfo->raw_data_out) {
-    if (master->using_merged_upsample) {
-#ifdef UPSAMPLE_MERGING_SUPPORTED
-      jinit_merged_upsampler(cinfo); /* does color conversion too */
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-    } else {
-      jinit_color_deconverter(cinfo);
-      jinit_upsampler(cinfo);
-    }
-    jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
-  }
-  /* Inverse DCT */
-  jinit_inverse_dct(cinfo);
-  /* Entropy decoding: either Huffman or arithmetic coding. */
-  if (cinfo->arith_code) {
-    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
-  } else {
-    if (cinfo->progressive_mode) {
-#ifdef D_PROGRESSIVE_SUPPORTED
-      jinit_phuff_decoder(cinfo);
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-    } else
-      jinit_huff_decoder(cinfo);
-  }
-
-  /* Initialize principal buffer controllers. */
-  use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
-  jinit_d_coef_controller(cinfo, use_c_buffer);
-
-  if (! cinfo->raw_data_out)
-    jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
-
-  /* We can now tell the memory manager to allocate virtual arrays. */
-  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
-
-  /* Initialize input side of decompressor to consume first scan. */
-  (*cinfo->inputctl->start_input_pass) (cinfo);
-
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-  /* If jpeg_start_decompress will read the whole file, initialize
-   * progress monitoring appropriately.  The input step is counted
-   * as one pass.
-   */
-  if (cinfo->progress != NULL && ! cinfo->buffered_image &&
-      cinfo->inputctl->has_multiple_scans) {
-    int nscans;
-    /* Estimate number of scans to set pass_limit. */
-    if (cinfo->progressive_mode) {
-      /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
-      nscans = 2 + 3 * cinfo->num_components;
-    } else {
-      /* For a nonprogressive multiscan file, estimate 1 scan per component. */
-      nscans = cinfo->num_components;
-    }
-    cinfo->progress->pass_counter = 0L;
-    cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
-    cinfo->progress->completed_passes = 0;
-    cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
-    /* Count the input pass as done */
-    master->pass_number++;
-  }
-#endif /* D_MULTISCAN_FILES_SUPPORTED */
-}
-
-
-/*
- * Per-pass setup.
- * This is called at the beginning of each output pass.  We determine which
- * modules will be active during this pass and give them appropriate
- * start_pass calls.  We also set is_dummy_pass to indicate whether this
- * is a "real" output pass or a dummy pass for color quantization.
- * (In the latter case, jdapistd.c will crank the pass to completion.)
- */
-
-METHODDEF(void)
-prepare_for_output_pass (j_decompress_ptr cinfo)
-{
-  my_master_ptr master = (my_master_ptr) cinfo->master;
-
-  if (master->pub.is_dummy_pass) {
-#ifdef QUANT_2PASS_SUPPORTED
-    /* Final pass of 2-pass quantization */
-    master->pub.is_dummy_pass = FALSE;
-    (*cinfo->cquantize->start_pass) (cinfo, FALSE);
-    (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
-    (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
-#else
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif /* QUANT_2PASS_SUPPORTED */
-  } else {
-    if (cinfo->quantize_colors && cinfo->colormap == NULL) {
-      /* Select new quantization method */
-      if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
-	cinfo->cquantize = master->quantizer_2pass;
-	master->pub.is_dummy_pass = TRUE;
-      } else if (cinfo->enable_1pass_quant) {
-	cinfo->cquantize = master->quantizer_1pass;
-      } else {
-	ERREXIT(cinfo, JERR_MODE_CHANGE);
-      }
-    }
-    (*cinfo->idct->start_pass) (cinfo);
-    (*cinfo->coef->start_output_pass) (cinfo);
-    if (! cinfo->raw_data_out) {
-      if (! master->using_merged_upsample)
-	(*cinfo->cconvert->start_pass) (cinfo);
-      (*cinfo->upsample->start_pass) (cinfo);
-      if (cinfo->quantize_colors)
-	(*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
-      (*cinfo->post->start_pass) (cinfo,
-	    (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
-      (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
-    }
-  }
-
-  /* Set up progress monitor's pass info if present */
-  if (cinfo->progress != NULL) {
-    cinfo->progress->completed_passes = master->pass_number;
-    cinfo->progress->total_passes = master->pass_number +
-				    (master->pub.is_dummy_pass ? 2 : 1);
-    /* In buffered-image mode, we assume one more output pass if EOI not
-     * yet reached, but no more passes if EOI has been reached.
-     */
-    if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
-      cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
-    }
-  }
-}
-
-
-/*
- * Finish up at end of an output pass.
- */
-
-METHODDEF(void)
-finish_output_pass (j_decompress_ptr cinfo)
-{
-  my_master_ptr master = (my_master_ptr) cinfo->master;
-
-  if (cinfo->quantize_colors)
-    (*cinfo->cquantize->finish_pass) (cinfo);
-  master->pass_number++;
-}
-
-
-#ifdef D_MULTISCAN_FILES_SUPPORTED
-
-/*
- * Switch to a new external colormap between output passes.
- */
-
-GLOBAL(void)
-jpeg_new_colormap (j_decompress_ptr cinfo)
-{
-  my_master_ptr master = (my_master_ptr) cinfo->master;
-
-  /* Prevent application from calling me at wrong times */
-  if (cinfo->global_state != DSTATE_BUFIMAGE)
-    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-
-  if (cinfo->quantize_colors && cinfo->enable_external_quant &&
-      cinfo->colormap != NULL) {
-    /* Select 2-pass quantizer for external colormap use */
-    cinfo->cquantize = master->quantizer_2pass;
-    /* Notify quantizer of colormap change */
-    (*cinfo->cquantize->new_color_map) (cinfo);
-    master->pub.is_dummy_pass = FALSE; /* just in case */
-  } else
-    ERREXIT(cinfo, JERR_MODE_CHANGE);
-}
-
-#endif /* D_MULTISCAN_FILES_SUPPORTED */
-
-
-/*
- * Initialize master decompression control and select active modules.
- * This is performed at the start of jpeg_start_decompress.
- */
-
-GLOBAL(void)
-jinit_master_decompress (j_decompress_ptr cinfo)
-{
-  my_master_ptr master;
-
-  master = (my_master_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(my_decomp_master));
-  cinfo->master = (struct jpeg_decomp_master *) master;
-  master->pub.prepare_for_output_pass = prepare_for_output_pass;
-  master->pub.finish_output_pass = finish_output_pass;
-
-  master->pub.is_dummy_pass = FALSE;
-
-  master_selection(cinfo);
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdmerge.c ./Shared/jpeg-6b/jdmerge.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdmerge.c	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdmerge.c	Wed Dec 31 19:00:00 1969
@@ -1,400 +0,0 @@
-/*
- * jdmerge.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains code for merged upsampling/color conversion.
- *
- * This file combines functions from jdsample.c and jdcolor.c;
- * read those files first to understand what's going on.
- *
- * When the chroma components are to be upsampled by simple replication
- * (ie, box filtering), we can save some work in color conversion by
- * calculating all the output pixels corresponding to a pair of chroma
- * samples at one time.  In the conversion equations
- *	R = Y           + K1 * Cr
- *	G = Y + K2 * Cb + K3 * Cr
- *	B = Y + K4 * Cb
- * only the Y term varies among the group of pixels corresponding to a pair
- * of chroma samples, so the rest of the terms can be calculated just once.
- * At typical sampling ratios, this eliminates half or three-quarters of the
- * multiplications needed for color conversion.
- *
- * This file currently provides implementations for the following cases:
- *	YCbCr => RGB color conversion only.
- *	Sampling ratios of 2h1v or 2h2v.
- *	No scaling needed at upsample time.
- *	Corner-aligned (non-CCIR601) sampling alignment.
- * Other special cases could be added, but in most applications these are
- * the only common cases.  (For uncommon cases we fall back on the more
- * general code in jdsample.c and jdcolor.c.)
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-#ifdef UPSAMPLE_MERGING_SUPPORTED
-
-
-/* Private subobject */
-
-typedef struct {
-  struct jpeg_upsampler pub;	/* public fields */
-
-  /* Pointer to routine to do actual upsampling/conversion of one row group */
-  JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
-			   JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
-			   JSAMPARRAY output_buf));
-
-  /* Private state for YCC->RGB conversion */
-  int * Cr_r_tab;		/* => table for Cr to R conversion */
-  int * Cb_b_tab;		/* => table for Cb to B conversion */
-  INT32 * Cr_g_tab;		/* => table for Cr to G conversion */
-  INT32 * Cb_g_tab;		/* => table for Cb to G conversion */
-
-  /* For 2:1 vertical sampling, we produce two output rows at a time.
-   * We need a "spare" row buffer to hold the second output row if the
-   * application provides just a one-row buffer; we also use the spare
-   * to discard the dummy last row if the image height is odd.
-   */
-  JSAMPROW spare_row;
-  boolean spare_full;		/* T if spare buffer is occupied */
-
-  JDIMENSION out_row_width;	/* samples per output row */
-  JDIMENSION rows_to_go;	/* counts rows remaining in image */
-} my_upsampler;
-
-typedef my_upsampler * my_upsample_ptr;
-
-#define SCALEBITS	16	/* speediest right-shift on some machines */
-#define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
-#define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
-
-
-/*
- * Initialize tables for YCC->RGB colorspace conversion.
- * This is taken directly from jdcolor.c; see that file for more info.
- */
-
-LOCAL(void)
-build_ycc_rgb_table (j_decompress_ptr cinfo)
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-  int i;
-  INT32 x;
-  SHIFT_TEMPS
-
-  upsample->Cr_r_tab = (int *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(int));
-  upsample->Cb_b_tab = (int *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(int));
-  upsample->Cr_g_tab = (INT32 *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(INT32));
-  upsample->Cb_g_tab = (INT32 *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(MAXJSAMPLE+1) * SIZEOF(INT32));
-
-  for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
-    /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
-    /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
-    /* Cr=>R value is nearest int to 1.40200 * x */
-    upsample->Cr_r_tab[i] = (int)
-		    RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
-    /* Cb=>B value is nearest int to 1.77200 * x */
-    upsample->Cb_b_tab[i] = (int)
-		    RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
-    /* Cr=>G value is scaled-up -0.71414 * x */
-    upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
-    /* Cb=>G value is scaled-up -0.34414 * x */
-    /* We also add in ONE_HALF so that need not do it in inner loop */
-    upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
-  }
-}
-
-
-/*
- * Initialize for an upsampling pass.
- */
-
-METHODDEF(void)
-start_pass_merged_upsample (j_decompress_ptr cinfo)
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-
-  /* Mark the spare buffer empty */
-  upsample->spare_full = FALSE;
-  /* Initialize total-height counter for detecting bottom of image */
-  upsample->rows_to_go = cinfo->output_height;
-}
-
-
-/*
- * Control routine to do upsampling (and color conversion).
- *
- * The control routine just handles the row buffering considerations.
- */
-
-METHODDEF(void)
-merged_2v_upsample (j_decompress_ptr cinfo,
-		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-		    JDIMENSION in_row_groups_avail,
-		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-		    JDIMENSION out_rows_avail)
-/* 2:1 vertical sampling case: may need a spare row. */
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-  JSAMPROW work_ptrs[2];
-  JDIMENSION num_rows;		/* number of rows returned to caller */
-
-  if (upsample->spare_full) {
-    /* If we have a spare row saved from a previous cycle, just return it. */
-    jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
-		      1, upsample->out_row_width);
-    num_rows = 1;
-    upsample->spare_full = FALSE;
-  } else {
-    /* Figure number of rows to return to caller. */
-    num_rows = 2;
-    /* Not more than the distance to the end of the image. */
-    if (num_rows > upsample->rows_to_go)
-      num_rows = upsample->rows_to_go;
-    /* And not more than what the client can accept: */
-    out_rows_avail -= *out_row_ctr;
-    if (num_rows > out_rows_avail)
-      num_rows = out_rows_avail;
-    /* Create output pointer array for upsampler. */
-    work_ptrs[0] = output_buf[*out_row_ctr];
-    if (num_rows > 1) {
-      work_ptrs[1] = output_buf[*out_row_ctr + 1];
-    } else {
-      work_ptrs[1] = upsample->spare_row;
-      upsample->spare_full = TRUE;
-    }
-    /* Now do the upsampling. */
-    (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
-  }
-
-  /* Adjust counts */
-  *out_row_ctr += num_rows;
-  upsample->rows_to_go -= num_rows;
-  /* When the buffer is emptied, declare this input row group consumed */
-  if (! upsample->spare_full)
-    (*in_row_group_ctr)++;
-}
-
-
-METHODDEF(void)
-merged_1v_upsample (j_decompress_ptr cinfo,
-		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-		    JDIMENSION in_row_groups_avail,
-		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-		    JDIMENSION out_rows_avail)
-/* 1:1 vertical sampling case: much easier, never need a spare row. */
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-
-  /* Just do the upsampling. */
-  (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
-			 output_buf + *out_row_ctr);
-  /* Adjust counts */
-  (*out_row_ctr)++;
-  (*in_row_group_ctr)++;
-}
-
-
-/*
- * These are the routines invoked by the control routines to do
- * the actual upsampling/conversion.  One row group is processed per call.
- *
- * Note: since we may be writing directly into application-supplied buffers,
- * we have to be honest about the output width; we can't assume the buffer
- * has been rounded up to an even width.
- */
-
-
-/*
- * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
- */
-
-METHODDEF(void)
-h2v1_merged_upsample (j_decompress_ptr cinfo,
-		      JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
-		      JSAMPARRAY output_buf)
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-  register int y, cred, cgreen, cblue;
-  int cb, cr;
-  register JSAMPROW outptr;
-  JSAMPROW inptr0, inptr1, inptr2;
-  JDIMENSION col;
-  /* copy these pointers into registers if possible */
-  register JSAMPLE * range_limit = cinfo->sample_range_limit;
-  int * Crrtab = upsample->Cr_r_tab;
-  int * Cbbtab = upsample->Cb_b_tab;
-  INT32 * Crgtab = upsample->Cr_g_tab;
-  INT32 * Cbgtab = upsample->Cb_g_tab;
-  SHIFT_TEMPS
-
-  inptr0 = input_buf[0][in_row_group_ctr];
-  inptr1 = input_buf[1][in_row_group_ctr];
-  inptr2 = input_buf[2][in_row_group_ctr];
-  outptr = output_buf[0];
-  /* Loop for each pair of output pixels */
-  for (col = cinfo->output_width >> 1; col > 0; col--) {
-    /* Do the chroma part of the calculation */
-    cb = GETJSAMPLE(*inptr1++);
-    cr = GETJSAMPLE(*inptr2++);
-    cred = Crrtab[cr];
-    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
-    cblue = Cbbtab[cb];
-    /* Fetch 2 Y values and emit 2 pixels */
-    y  = GETJSAMPLE(*inptr0++);
-    outptr[RGB_RED] =   range_limit[y + cred];
-    outptr[RGB_GREEN] = range_limit[y + cgreen];
-    outptr[RGB_BLUE] =  range_limit[y + cblue];
-    outptr += RGB_PIXELSIZE;
-    y  = GETJSAMPLE(*inptr0++);
-    outptr[RGB_RED] =   range_limit[y + cred];
-    outptr[RGB_GREEN] = range_limit[y + cgreen];
-    outptr[RGB_BLUE] =  range_limit[y + cblue];
-    outptr += RGB_PIXELSIZE;
-  }
-  /* If image width is odd, do the last output column separately */
-  if (cinfo->output_width & 1) {
-    cb = GETJSAMPLE(*inptr1);
-    cr = GETJSAMPLE(*inptr2);
-    cred = Crrtab[cr];
-    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
-    cblue = Cbbtab[cb];
-    y  = GETJSAMPLE(*inptr0);
-    outptr[RGB_RED] =   range_limit[y + cred];
-    outptr[RGB_GREEN] = range_limit[y + cgreen];
-    outptr[RGB_BLUE] =  range_limit[y + cblue];
-  }
-}
-
-
-/*
- * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
- */
-
-METHODDEF(void)
-h2v2_merged_upsample (j_decompress_ptr cinfo,
-		      JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
-		      JSAMPARRAY output_buf)
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-  register int y, cred, cgreen, cblue;
-  int cb, cr;
-  register JSAMPROW outptr0, outptr1;
-  JSAMPROW inptr00, inptr01, inptr1, inptr2;
-  JDIMENSION col;
-  /* copy these pointers into registers if possible */
-  register JSAMPLE * range_limit = cinfo->sample_range_limit;
-  int * Crrtab = upsample->Cr_r_tab;
-  int * Cbbtab = upsample->Cb_b_tab;
-  INT32 * Crgtab = upsample->Cr_g_tab;
-  INT32 * Cbgtab = upsample->Cb_g_tab;
-  SHIFT_TEMPS
-
-  inptr00 = input_buf[0][in_row_group_ctr*2];
-  inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
-  inptr1 = input_buf[1][in_row_group_ctr];
-  inptr2 = input_buf[2][in_row_group_ctr];
-  outptr0 = output_buf[0];
-  outptr1 = output_buf[1];
-  /* Loop for each group of output pixels */
-  for (col = cinfo->output_width >> 1; col > 0; col--) {
-    /* Do the chroma part of the calculation */
-    cb = GETJSAMPLE(*inptr1++);
-    cr = GETJSAMPLE(*inptr2++);
-    cred = Crrtab[cr];
-    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
-    cblue = Cbbtab[cb];
-    /* Fetch 4 Y values and emit 4 pixels */
-    y  = GETJSAMPLE(*inptr00++);
-    outptr0[RGB_RED] =   range_limit[y + cred];
-    outptr0[RGB_GREEN] = range_limit[y + cgreen];
-    outptr0[RGB_BLUE] =  range_limit[y + cblue];
-    outptr0 += RGB_PIXELSIZE;
-    y  = GETJSAMPLE(*inptr00++);
-    outptr0[RGB_RED] =   range_limit[y + cred];
-    outptr0[RGB_GREEN] = range_limit[y + cgreen];
-    outptr0[RGB_BLUE] =  range_limit[y + cblue];
-    outptr0 += RGB_PIXELSIZE;
-    y  = GETJSAMPLE(*inptr01++);
-    outptr1[RGB_RED] =   range_limit[y + cred];
-    outptr1[RGB_GREEN] = range_limit[y + cgreen];
-    outptr1[RGB_BLUE] =  range_limit[y + cblue];
-    outptr1 += RGB_PIXELSIZE;
-    y  = GETJSAMPLE(*inptr01++);
-    outptr1[RGB_RED] =   range_limit[y + cred];
-    outptr1[RGB_GREEN] = range_limit[y + cgreen];
-    outptr1[RGB_BLUE] =  range_limit[y + cblue];
-    outptr1 += RGB_PIXELSIZE;
-  }
-  /* If image width is odd, do the last output column separately */
-  if (cinfo->output_width & 1) {
-    cb = GETJSAMPLE(*inptr1);
-    cr = GETJSAMPLE(*inptr2);
-    cred = Crrtab[cr];
-    cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
-    cblue = Cbbtab[cb];
-    y  = GETJSAMPLE(*inptr00);
-    outptr0[RGB_RED] =   range_limit[y + cred];
-    outptr0[RGB_GREEN] = range_limit[y + cgreen];
-    outptr0[RGB_BLUE] =  range_limit[y + cblue];
-    y  = GETJSAMPLE(*inptr01);
-    outptr1[RGB_RED] =   range_limit[y + cred];
-    outptr1[RGB_GREEN] = range_limit[y + cgreen];
-    outptr1[RGB_BLUE] =  range_limit[y + cblue];
-  }
-}
-
-
-/*
- * Module initialization routine for merged upsampling/color conversion.
- *
- * NB: this is called under the conditions determined by use_merged_upsample()
- * in jdmaster.c.  That routine MUST correspond to the actual capabilities
- * of this module; no safety checks are made here.
- */
-
-GLOBAL(void)
-jinit_merged_upsampler (j_decompress_ptr cinfo)
-{
-  my_upsample_ptr upsample;
-
-  upsample = (my_upsample_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_upsampler));
-  cinfo->upsample = (struct jpeg_upsampler *) upsample;
-  upsample->pub.start_pass = start_pass_merged_upsample;
-  upsample->pub.need_context_rows = FALSE;
-
-  upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
-
-  if (cinfo->max_v_samp_factor == 2) {
-    upsample->pub.upsample = merged_2v_upsample;
-    upsample->upmethod = h2v2_merged_upsample;
-    /* Allocate a spare row buffer */
-    upsample->spare_row = (JSAMPROW)
-      (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-		(size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
-  } else {
-    upsample->pub.upsample = merged_1v_upsample;
-    upsample->upmethod = h2v1_merged_upsample;
-    /* No spare row needed */
-    upsample->spare_row = NULL;
-  }
-
-  build_ycc_rgb_table(cinfo);
-}
-
-#endif /* UPSAMPLE_MERGING_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdphuff.c ./Shared/jpeg-6b/jdphuff.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdphuff.c	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdphuff.c	Wed Dec 31 19:00:00 1969
@@ -1,668 +0,0 @@
-/*
- * jdphuff.c
- *
- * Copyright (C) 1995-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains Huffman entropy decoding routines for progressive JPEG.
- *
- * Much of the complexity here has to do with supporting input suspension.
- * If the data source module demands suspension, we want to be able to back
- * up to the start of the current MCU.  To do this, we copy state variables
- * into local working storage, and update them back to the permanent
- * storage only upon successful completion of an MCU.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdhuff.h"		/* Declarations shared with jdhuff.c */
-
-
-#ifdef D_PROGRESSIVE_SUPPORTED
-
-/*
- * Expanded entropy decoder object for progressive Huffman decoding.
- *
- * The savable_state subrecord contains fields that change within an MCU,
- * but must not be updated permanently until we complete the MCU.
- */
-
-typedef struct {
-  unsigned int EOBRUN;			/* remaining EOBs in EOBRUN */
-  int last_dc_val[MAX_COMPS_IN_SCAN];	/* last DC coef for each component */
-} savable_state;
-
-/* This macro is to work around compilers with missing or broken
- * structure assignment.  You'll need to fix this code if you have
- * such a compiler and you change MAX_COMPS_IN_SCAN.
- */
-
-#ifndef NO_STRUCT_ASSIGN
-#define ASSIGN_STATE(dest,src)  ((dest) = (src))
-#else
-#if MAX_COMPS_IN_SCAN == 4
-#define ASSIGN_STATE(dest,src)  \
-	((dest).EOBRUN = (src).EOBRUN, \
-	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
-	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
-	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
-	 (dest).last_dc_val[3] = (src).last_dc_val[3])
-#endif
-#endif
-
-
-typedef struct {
-  struct jpeg_entropy_decoder pub; /* public fields */
-
-  /* These fields are loaded into local variables at start of each MCU.
-   * In case of suspension, we exit WITHOUT updating them.
-   */
-  bitread_perm_state bitstate;	/* Bit buffer at start of MCU */
-  savable_state saved;		/* Other state at start of MCU */
-
-  /* These fields are NOT loaded into local working state. */
-  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
-
-  /* Pointers to derived tables (these workspaces have image lifespan) */
-  d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
-
-  d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
-} phuff_entropy_decoder;
-
-typedef phuff_entropy_decoder * phuff_entropy_ptr;
-
-/* Forward declarations */
-METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
-					    JBLOCKROW *MCU_data));
-METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
-					    JBLOCKROW *MCU_data));
-METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
-					     JBLOCKROW *MCU_data));
-METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
-					     JBLOCKROW *MCU_data));
-
-
-/*
- * Initialize for a Huffman-compressed scan.
- */
-
-METHODDEF(void)
-start_pass_phuff_decoder (j_decompress_ptr cinfo)
-{
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  boolean is_DC_band, bad;
-  int ci, coefi, tbl;
-  int *coef_bit_ptr;
-  jpeg_component_info * compptr;
-
-  is_DC_band = (cinfo->Ss == 0);
-
-  /* Validate scan parameters */
-  bad = FALSE;
-  if (is_DC_band) {
-    if (cinfo->Se != 0)
-      bad = TRUE;
-  } else {
-    /* need not check Ss/Se < 0 since they came from unsigned bytes */
-    if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
-      bad = TRUE;
-    /* AC scans may have only one component */
-    if (cinfo->comps_in_scan != 1)
-      bad = TRUE;
-  }
-  if (cinfo->Ah != 0) {
-    /* Successive approximation refinement scan: must have Al = Ah-1. */
-    if (cinfo->Al != cinfo->Ah-1)
-      bad = TRUE;
-  }
-  if (cinfo->Al > 13)		/* need not check for < 0 */
-    bad = TRUE;
-  /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
-   * but the spec doesn't say so, and we try to be liberal about what we
-   * accept.  Note: large Al values could result in out-of-range DC
-   * coefficients during early scans, leading to bizarre displays due to
-   * overflows in the IDCT math.  But we won't crash.
-   */
-  if (bad)
-    ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
-	     cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
-  /* Update progression status, and verify that scan order is legal.
-   * Note that inter-scan inconsistencies are treated as warnings
-   * not fatal errors ... not clear if this is right way to behave.
-   */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    int cindex = cinfo->cur_comp_info[ci]->component_index;
-    coef_bit_ptr = & cinfo->coef_bits[cindex][0];
-    if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
-      WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
-    for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
-      int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
-      if (cinfo->Ah != expected)
-	WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
-      coef_bit_ptr[coefi] = cinfo->Al;
-    }
-  }
-
-  /* Select MCU decoding routine */
-  if (cinfo->Ah == 0) {
-    if (is_DC_band)
-      entropy->pub.decode_mcu = decode_mcu_DC_first;
-    else
-      entropy->pub.decode_mcu = decode_mcu_AC_first;
-  } else {
-    if (is_DC_band)
-      entropy->pub.decode_mcu = decode_mcu_DC_refine;
-    else
-      entropy->pub.decode_mcu = decode_mcu_AC_refine;
-  }
-
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    /* Make sure requested tables are present, and compute derived tables.
-     * We may build same derived table more than once, but it's not expensive.
-     */
-    if (is_DC_band) {
-      if (cinfo->Ah == 0) {	/* DC refinement needs no table */
-	tbl = compptr->dc_tbl_no;
-	jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
-				& entropy->derived_tbls[tbl]);
-      }
-    } else {
-      tbl = compptr->ac_tbl_no;
-      jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
-			      & entropy->derived_tbls[tbl]);
-      /* remember the single active table */
-      entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
-    }
-    /* Initialize DC predictions to 0 */
-    entropy->saved.last_dc_val[ci] = 0;
-  }
-
-  /* Initialize bitread state variables */
-  entropy->bitstate.bits_left = 0;
-  entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
-  entropy->pub.insufficient_data = FALSE;
-
-  /* Initialize private state variables */
-  entropy->saved.EOBRUN = 0;
-
-  /* Initialize restart counter */
-  entropy->restarts_to_go = cinfo->restart_interval;
-}
-
-
-/*
- * Figure F.12: extend sign bit.
- * On some machines, a shift and add will be faster than a table lookup.
- */
-
-#ifdef AVOID_TABLES
-
-#define HUFF_EXTEND(x,s)  ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
-
-#else
-
-#define HUFF_EXTEND(x,s)  ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
-
-static const int extend_test[16] =   /* entry n is 2**(n-1) */
-  { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
-    0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
-
-static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
-  { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
-    ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
-    ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
-    ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
-
-#endif /* AVOID_TABLES */
-
-
-/*
- * Check for a restart marker & resynchronize decoder.
- * Returns FALSE if must suspend.
- */
-
-LOCAL(boolean)
-process_restart (j_decompress_ptr cinfo)
-{
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  int ci;
-
-  /* Throw away any unused bits remaining in bit buffer; */
-  /* include any full bytes in next_marker's count of discarded bytes */
-  cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
-  entropy->bitstate.bits_left = 0;
-
-  /* Advance past the RSTn marker */
-  if (! (*cinfo->marker->read_restart_marker) (cinfo))
-    return FALSE;
-
-  /* Re-initialize DC predictions to 0 */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
-    entropy->saved.last_dc_val[ci] = 0;
-  /* Re-init EOB run count, too */
-  entropy->saved.EOBRUN = 0;
-
-  /* Reset restart counter */
-  entropy->restarts_to_go = cinfo->restart_interval;
-
-  /* Reset out-of-data flag, unless read_restart_marker left us smack up
-   * against a marker.  In that case we will end up treating the next data
-   * segment as empty, and we can avoid producing bogus output pixels by
-   * leaving the flag set.
-   */
-  if (cinfo->unread_marker == 0)
-    entropy->pub.insufficient_data = FALSE;
-
-  return TRUE;
-}
-
-
-/*
- * Huffman MCU decoding.
- * Each of these routines decodes and returns one MCU's worth of
- * Huffman-compressed coefficients. 
- * The coefficients are reordered from zigzag order into natural array order,
- * but are not dequantized.
- *
- * The i'th block of the MCU is stored into the block pointed to by
- * MCU_data[i].  WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
- *
- * We return FALSE if data source requested suspension.  In that case no
- * changes have been made to permanent state.  (Exception: some output
- * coefficients may already have been assigned.  This is harmless for
- * spectral selection, since we'll just re-assign them on the next call.
- * Successive approximation AC refinement has to be more careful, however.)
- */
-
-/*
- * MCU decoding for DC initial scan (either spectral selection,
- * or first pass of successive approximation).
- */
-
-METHODDEF(boolean)
-decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
-{   
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  int Al = cinfo->Al;
-  register int s, r;
-  int blkn, ci;
-  JBLOCKROW block;
-  BITREAD_STATE_VARS;
-  savable_state state;
-  d_derived_tbl * tbl;
-  jpeg_component_info * compptr;
-
-  /* Process restart marker if needed; may have to suspend */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0)
-      if (! process_restart(cinfo))
-	return FALSE;
-  }
-
-  /* If we've run out of data, just leave the MCU set to zeroes.
-   * This way, we return uniform gray for the remainder of the segment.
-   */
-  if (! entropy->pub.insufficient_data) {
-
-    /* Load up working state */
-    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
-    ASSIGN_STATE(state, entropy->saved);
-
-    /* Outer loop handles each block in the MCU */
-
-    for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-      block = MCU_data[blkn];
-      ci = cinfo->MCU_membership[blkn];
-      compptr = cinfo->cur_comp_info[ci];
-      tbl = entropy->derived_tbls[compptr->dc_tbl_no];
-
-      /* Decode a single block's worth of coefficients */
-
-      /* Section F.2.2.1: decode the DC coefficient difference */
-      HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
-      if (s) {
-	CHECK_BIT_BUFFER(br_state, s, return FALSE);
-	r = GET_BITS(s);
-	s = HUFF_EXTEND(r, s);
-      }
-
-      /* Convert DC difference to actual value, update last_dc_val */
-      s += state.last_dc_val[ci];
-      state.last_dc_val[ci] = s;
-      /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
-      (*block)[0] = (JCOEF) (s << Al);
-    }
-
-    /* Completed MCU, so update state */
-    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
-    ASSIGN_STATE(entropy->saved, state);
-  }
-
-  /* Account for restart interval (no-op if not using restarts) */
-  entropy->restarts_to_go--;
-
-  return TRUE;
-}
-
-
-/*
- * MCU decoding for AC initial scan (either spectral selection,
- * or first pass of successive approximation).
- */
-
-METHODDEF(boolean)
-decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
-{   
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  int Se = cinfo->Se;
-  int Al = cinfo->Al;
-  register int s, k, r;
-  unsigned int EOBRUN;
-  JBLOCKROW block;
-  BITREAD_STATE_VARS;
-  d_derived_tbl * tbl;
-
-  /* Process restart marker if needed; may have to suspend */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0)
-      if (! process_restart(cinfo))
-	return FALSE;
-  }
-
-  /* If we've run out of data, just leave the MCU set to zeroes.
-   * This way, we return uniform gray for the remainder of the segment.
-   */
-  if (! entropy->pub.insufficient_data) {
-
-    /* Load up working state.
-     * We can avoid loading/saving bitread state if in an EOB run.
-     */
-    EOBRUN = entropy->saved.EOBRUN;	/* only part of saved state we need */
-
-    /* There is always only one block per MCU */
-
-    if (EOBRUN > 0)		/* if it's a band of zeroes... */
-      EOBRUN--;			/* ...process it now (we do nothing) */
-    else {
-      BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
-      block = MCU_data[0];
-      tbl = entropy->ac_derived_tbl;
-
-      for (k = cinfo->Ss; k <= Se; k++) {
-	HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
-	r = s >> 4;
-	s &= 15;
-	if (s) {
-	  k += r;
-	  CHECK_BIT_BUFFER(br_state, s, return FALSE);
-	  r = GET_BITS(s);
-	  s = HUFF_EXTEND(r, s);
-	  /* Scale and output coefficient in natural (dezigzagged) order */
-	  (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
-	} else {
-	  if (r == 15) {	/* ZRL */
-	    k += 15;		/* skip 15 zeroes in band */
-	  } else {		/* EOBr, run length is 2^r + appended bits */
-	    EOBRUN = 1 << r;
-	    if (r) {		/* EOBr, r > 0 */
-	      CHECK_BIT_BUFFER(br_state, r, return FALSE);
-	      r = GET_BITS(r);
-	      EOBRUN += r;
-	    }
-	    EOBRUN--;		/* this band is processed at this moment */
-	    break;		/* force end-of-band */
-	  }
-	}
-      }
-
-      BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
-    }
-
-    /* Completed MCU, so update state */
-    entropy->saved.EOBRUN = EOBRUN;	/* only part of saved state we need */
-  }
-
-  /* Account for restart interval (no-op if not using restarts) */
-  entropy->restarts_to_go--;
-
-  return TRUE;
-}
-
-
-/*
- * MCU decoding for DC successive approximation refinement scan.
- * Note: we assume such scans can be multi-component, although the spec
- * is not very clear on the point.
- */
-
-METHODDEF(boolean)
-decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
-{   
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
-  int blkn;
-  JBLOCKROW block;
-  BITREAD_STATE_VARS;
-
-  /* Process restart marker if needed; may have to suspend */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0)
-      if (! process_restart(cinfo))
-	return FALSE;
-  }
-
-  /* Not worth the cycles to check insufficient_data here,
-   * since we will not change the data anyway if we read zeroes.
-   */
-
-  /* Load up working state */
-  BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
-
-  /* Outer loop handles each block in the MCU */
-
-  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-    block = MCU_data[blkn];
-
-    /* Encoded data is simply the next bit of the two's-complement DC value */
-    CHECK_BIT_BUFFER(br_state, 1, return FALSE);
-    if (GET_BITS(1))
-      (*block)[0] |= p1;
-    /* Note: since we use |=, repeating the assignment later is safe */
-  }
-
-  /* Completed MCU, so update state */
-  BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
-
-  /* Account for restart interval (no-op if not using restarts) */
-  entropy->restarts_to_go--;
-
-  return TRUE;
-}
-
-
-/*
- * MCU decoding for AC successive approximation refinement scan.
- */
-
-METHODDEF(boolean)
-decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
-{   
-  phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
-  int Se = cinfo->Se;
-  int p1 = 1 << cinfo->Al;	/* 1 in the bit position being coded */
-  int m1 = (-1) << cinfo->Al;	/* -1 in the bit position being coded */
-  register int s, k, r;
-  unsigned int EOBRUN;
-  JBLOCKROW block;
-  JCOEFPTR thiscoef;
-  BITREAD_STATE_VARS;
-  d_derived_tbl * tbl;
-  int num_newnz;
-  int newnz_pos[DCTSIZE2];
-
-  /* Process restart marker if needed; may have to suspend */
-  if (cinfo->restart_interval) {
-    if (entropy->restarts_to_go == 0)
-      if (! process_restart(cinfo))
-	return FALSE;
-  }
-
-  /* If we've run out of data, don't modify the MCU.
-   */
-  if (! entropy->pub.insufficient_data) {
-
-    /* Load up working state */
-    BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
-    EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
-
-    /* There is always only one block per MCU */
-    block = MCU_data[0];
-    tbl = entropy->ac_derived_tbl;
-
-    /* If we are forced to suspend, we must undo the assignments to any newly
-     * nonzero coefficients in the block, because otherwise we'd get confused
-     * next time about which coefficients were already nonzero.
-     * But we need not undo addition of bits to already-nonzero coefficients;
-     * instead, we can test the current bit to see if we already did it.
-     */
-    num_newnz = 0;
-
-    /* initialize coefficient loop counter to start of band */
-    k = cinfo->Ss;
-
-    if (EOBRUN == 0) {
-      for (; k <= Se; k++) {
-	HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
-	r = s >> 4;
-	s &= 15;
-	if (s) {
-	  if (s != 1)		/* size of new coef should always be 1 */
-	    WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
-	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
-	  if (GET_BITS(1))
-	    s = p1;		/* newly nonzero coef is positive */
-	  else
-	    s = m1;		/* newly nonzero coef is negative */
-	} else {
-	  if (r != 15) {
-	    EOBRUN = 1 << r;	/* EOBr, run length is 2^r + appended bits */
-	    if (r) {
-	      CHECK_BIT_BUFFER(br_state, r, goto undoit);
-	      r = GET_BITS(r);
-	      EOBRUN += r;
-	    }
-	    break;		/* rest of block is handled by EOB logic */
-	  }
-	  /* note s = 0 for processing ZRL */
-	}
-	/* Advance over already-nonzero coefs and r still-zero coefs,
-	 * appending correction bits to the nonzeroes.  A correction bit is 1
-	 * if the absolute value of the coefficient must be increased.
-	 */
-	do {
-	  thiscoef = *block + jpeg_natural_order[k];
-	  if (*thiscoef != 0) {
-	    CHECK_BIT_BUFFER(br_state, 1, goto undoit);
-	    if (GET_BITS(1)) {
-	      if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
-		if (*thiscoef >= 0)
-		  *thiscoef += p1;
-		else
-		  *thiscoef += m1;
-	      }
-	    }
-	  } else {
-	    if (--r < 0)
-	      break;		/* reached target zero coefficient */
-	  }
-	  k++;
-	} while (k <= Se);
-	if (s) {
-	  int pos = jpeg_natural_order[k];
-	  /* Output newly nonzero coefficient */
-	  (*block)[pos] = (JCOEF) s;
-	  /* Remember its position in case we have to suspend */
-	  newnz_pos[num_newnz++] = pos;
-	}
-      }
-    }
-
-    if (EOBRUN > 0) {
-      /* Scan any remaining coefficient positions after the end-of-band
-       * (the last newly nonzero coefficient, if any).  Append a correction
-       * bit to each already-nonzero coefficient.  A correction bit is 1
-       * if the absolute value of the coefficient must be increased.
-       */
-      for (; k <= Se; k++) {
-	thiscoef = *block + jpeg_natural_order[k];
-	if (*thiscoef != 0) {
-	  CHECK_BIT_BUFFER(br_state, 1, goto undoit);
-	  if (GET_BITS(1)) {
-	    if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
-	      if (*thiscoef >= 0)
-		*thiscoef += p1;
-	      else
-		*thiscoef += m1;
-	    }
-	  }
-	}
-      }
-      /* Count one block completed in EOB run */
-      EOBRUN--;
-    }
-
-    /* Completed MCU, so update state */
-    BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
-    entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
-  }
-
-  /* Account for restart interval (no-op if not using restarts) */
-  entropy->restarts_to_go--;
-
-  return TRUE;
-
-undoit:
-  /* Re-zero any output coefficients that we made newly nonzero */
-  while (num_newnz > 0)
-    (*block)[newnz_pos[--num_newnz]] = 0;
-
-  return FALSE;
-}
-
-
-/*
- * Module initialization routine for progressive Huffman entropy decoding.
- */
-
-GLOBAL(void)
-jinit_phuff_decoder (j_decompress_ptr cinfo)
-{
-  phuff_entropy_ptr entropy;
-  int *coef_bit_ptr;
-  int ci, i;
-
-  entropy = (phuff_entropy_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(phuff_entropy_decoder));
-  cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
-  entropy->pub.start_pass = start_pass_phuff_decoder;
-
-  /* Mark derived tables unallocated */
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    entropy->derived_tbls[i] = NULL;
-  }
-
-  /* Create progression status table */
-  cinfo->coef_bits = (int (*)[DCTSIZE2])
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				cinfo->num_components*DCTSIZE2*SIZEOF(int));
-  coef_bit_ptr = & cinfo->coef_bits[0][0];
-  for (ci = 0; ci < cinfo->num_components; ci++) 
-    for (i = 0; i < DCTSIZE2; i++)
-      *coef_bit_ptr++ = -1;
-}
-
-#endif /* D_PROGRESSIVE_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdpostct.c ./Shared/jpeg-6b/jdpostct.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdpostct.c	Mon Dec  1 12:30:36 2003
+++ ./Shared/jpeg-6b/jdpostct.c	Wed Dec 31 19:00:00 1969
@@ -1,290 +0,0 @@
-/*
- * jdpostct.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the decompression postprocessing controller.
- * This controller manages the upsampling, color conversion, and color
- * quantization/reduction steps; specifically, it controls the buffering
- * between upsample/color conversion and color quantization/reduction.
- *
- * If no color quantization/reduction is required, then this module has no
- * work to do, and it just hands off to the upsample/color conversion code.
- * An integrated upsample/convert/quantize process would replace this module
- * entirely.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Private buffer controller object */
-
-typedef struct {
-  struct jpeg_d_post_controller pub; /* public fields */
-
-  /* Color quantization source buffer: this holds output data from
-   * the upsample/color conversion step to be passed to the quantizer.
-   * For two-pass color quantization, we need a full-image buffer;
-   * for one-pass operation, a strip buffer is sufficient.
-   */
-  jvirt_sarray_ptr whole_image;	/* virtual array, or NULL if one-pass */
-  JSAMPARRAY buffer;		/* strip buffer, or current strip of virtual */
-  JDIMENSION strip_height;	/* buffer size in rows */
-  /* for two-pass mode only: */
-  JDIMENSION starting_row;	/* row # of first row in current strip */
-  JDIMENSION next_row;		/* index of next row to fill/empty in strip */
-} my_post_controller;
-
-typedef my_post_controller * my_post_ptr;
-
-
-/* Forward declarations */
-METHODDEF(void) post_process_1pass
-	JPP((j_decompress_ptr cinfo,
-	     JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-	     JDIMENSION in_row_groups_avail,
-	     JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-	     JDIMENSION out_rows_avail));
-#ifdef QUANT_2PASS_SUPPORTED
-METHODDEF(void) post_process_prepass
-	JPP((j_decompress_ptr cinfo,
-	     JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-	     JDIMENSION in_row_groups_avail,
-	     JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-	     JDIMENSION out_rows_avail));
-METHODDEF(void) post_process_2pass
-	JPP((j_decompress_ptr cinfo,
-	     JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-	     JDIMENSION in_row_groups_avail,
-	     JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-	     JDIMENSION out_rows_avail));
-#endif
-
-
-/*
- * Initialize for a processing pass.
- */
-
-METHODDEF(void)
-start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
-{
-  my_post_ptr post = (my_post_ptr) cinfo->post;
-
-  switch (pass_mode) {
-  case JBUF_PASS_THRU:
-    if (cinfo->quantize_colors) {
-      /* Single-pass processing with color quantization. */
-      post->pub.post_process_data = post_process_1pass;
-      /* We could be doing buffered-image output before starting a 2-pass
-       * color quantization; in that case, jinit_d_post_controller did not
-       * allocate a strip buffer.  Use the virtual-array buffer as workspace.
-       */
-      if (post->buffer == NULL) {
-	post->buffer = (*cinfo->mem->access_virt_sarray)
-	  ((j_common_ptr) cinfo, post->whole_image,
-	   (JDIMENSION) 0, post->strip_height, TRUE);
-      }
-    } else {
-      /* For single-pass processing without color quantization,
-       * I have no work to do; just call the upsampler directly.
-       */
-      post->pub.post_process_data = cinfo->upsample->upsample;
-    }
-    break;
-#ifdef QUANT_2PASS_SUPPORTED
-  case JBUF_SAVE_AND_PASS:
-    /* First pass of 2-pass quantization */
-    if (post->whole_image == NULL)
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    post->pub.post_process_data = post_process_prepass;
-    break;
-  case JBUF_CRANK_DEST:
-    /* Second pass of 2-pass quantization */
-    if (post->whole_image == NULL)
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    post->pub.post_process_data = post_process_2pass;
-    break;
-#endif /* QUANT_2PASS_SUPPORTED */
-  default:
-    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-    break;
-  }
-  post->starting_row = post->next_row = 0;
-}
-
-
-/*
- * Process some data in the one-pass (strip buffer) case.
- * This is used for color precision reduction as well as one-pass quantization.
- */
-
-METHODDEF(void)
-post_process_1pass (j_decompress_ptr cinfo,
-		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-		    JDIMENSION in_row_groups_avail,
-		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-		    JDIMENSION out_rows_avail)
-{
-  my_post_ptr post = (my_post_ptr) cinfo->post;
-  JDIMENSION num_rows, max_rows;
-
-  /* Fill the buffer, but not more than what we can dump out in one go. */
-  /* Note we rely on the upsampler to detect bottom of image. */
-  max_rows = out_rows_avail - *out_row_ctr;
-  if (max_rows > post->strip_height)
-    max_rows = post->strip_height;
-  num_rows = 0;
-  (*cinfo->upsample->upsample) (cinfo,
-		input_buf, in_row_group_ctr, in_row_groups_avail,
-		post->buffer, &num_rows, max_rows);
-  /* Quantize and emit data. */
-  (*cinfo->cquantize->color_quantize) (cinfo,
-		post->buffer, output_buf + *out_row_ctr, (int) num_rows);
-  *out_row_ctr += num_rows;
-}
-
-
-#ifdef QUANT_2PASS_SUPPORTED
-
-/*
- * Process some data in the first pass of 2-pass quantization.
- */
-
-METHODDEF(void)
-post_process_prepass (j_decompress_ptr cinfo,
-		      JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-		      JDIMENSION in_row_groups_avail,
-		      JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-		      JDIMENSION out_rows_avail)
-{
-  my_post_ptr post = (my_post_ptr) cinfo->post;
-  JDIMENSION old_next_row, num_rows;
-
-  /* Reposition virtual buffer if at start of strip. */
-  if (post->next_row == 0) {
-    post->buffer = (*cinfo->mem->access_virt_sarray)
-	((j_common_ptr) cinfo, post->whole_image,
-	 post->starting_row, post->strip_height, TRUE);
-  }
-
-  /* Upsample some data (up to a strip height's worth). */
-  old_next_row = post->next_row;
-  (*cinfo->upsample->upsample) (cinfo,
-		input_buf, in_row_group_ctr, in_row_groups_avail,
-		post->buffer, &post->next_row, post->strip_height);
-
-  /* Allow quantizer to scan new data.  No data is emitted, */
-  /* but we advance out_row_ctr so outer loop can tell when we're done. */
-  if (post->next_row > old_next_row) {
-    num_rows = post->next_row - old_next_row;
-    (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
-					 (JSAMPARRAY) NULL, (int) num_rows);
-    *out_row_ctr += num_rows;
-  }
-
-  /* Advance if we filled the strip. */
-  if (post->next_row >= post->strip_height) {
-    post->starting_row += post->strip_height;
-    post->next_row = 0;
-  }
-}
-
-
-/*
- * Process some data in the second pass of 2-pass quantization.
- */
-
-METHODDEF(void)
-post_process_2pass (j_decompress_ptr cinfo,
-		    JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-		    JDIMENSION in_row_groups_avail,
-		    JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-		    JDIMENSION out_rows_avail)
-{
-  my_post_ptr post = (my_post_ptr) cinfo->post;
-  JDIMENSION num_rows, max_rows;
-
-  /* Reposition virtual buffer if at start of strip. */
-  if (post->next_row == 0) {
-    post->buffer = (*cinfo->mem->access_virt_sarray)
-	((j_common_ptr) cinfo, post->whole_image,
-	 post->starting_row, post->strip_height, FALSE);
-  }
-
-  /* Determine number of rows to emit. */
-  num_rows = post->strip_height - post->next_row; /* available in strip */
-  max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
-  if (num_rows > max_rows)
-    num_rows = max_rows;
-  /* We have to check bottom of image here, can't depend on upsampler. */
-  max_rows = cinfo->output_height - post->starting_row;
-  if (num_rows > max_rows)
-    num_rows = max_rows;
-
-  /* Quantize and emit data. */
-  (*cinfo->cquantize->color_quantize) (cinfo,
-		post->buffer + post->next_row, output_buf + *out_row_ctr,
-		(int) num_rows);
-  *out_row_ctr += num_rows;
-
-  /* Advance if we filled the strip. */
-  post->next_row += num_rows;
-  if (post->next_row >= post->strip_height) {
-    post->starting_row += post->strip_height;
-    post->next_row = 0;
-  }
-}
-
-#endif /* QUANT_2PASS_SUPPORTED */
-
-
-/*
- * Initialize postprocessing controller.
- */
-
-GLOBAL(void)
-jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
-{
-  my_post_ptr post;
-
-  post = (my_post_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_post_controller));
-  cinfo->post = (struct jpeg_d_post_controller *) post;
-  post->pub.start_pass = start_pass_dpost;
-  post->whole_image = NULL;	/* flag for no virtual arrays */
-  post->buffer = NULL;		/* flag for no strip buffer */
-
-  /* Create the quantization buffer, if needed */
-  if (cinfo->quantize_colors) {
-    /* The buffer strip height is max_v_samp_factor, which is typically
-     * an efficient number of rows for upsampling to return.
-     * (In the presence of output rescaling, we might want to be smarter?)
-     */
-    post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
-    if (need_full_buffer) {
-      /* Two-pass color quantization: need full-image storage. */
-      /* We round up the number of rows to a multiple of the strip height. */
-#ifdef QUANT_2PASS_SUPPORTED
-      post->whole_image = (*cinfo->mem->request_virt_sarray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-	 cinfo->output_width * cinfo->out_color_components,
-	 (JDIMENSION) jround_up((long) cinfo->output_height,
-				(long) post->strip_height),
-	 post->strip_height);
-#else
-      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
-#endif /* QUANT_2PASS_SUPPORTED */
-    } else {
-      /* One-pass color quantization: just make a strip buffer. */
-      post->buffer = (*cinfo->mem->alloc_sarray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE,
-	 cinfo->output_width * cinfo->out_color_components,
-	 post->strip_height);
-    }
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdsample.c ./Shared/jpeg-6b/jdsample.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdsample.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jdsample.c	Wed Dec 31 19:00:00 1969
@@ -1,478 +0,0 @@
-/*
- * jdsample.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains upsampling routines.
- *
- * Upsampling input data is counted in "row groups".  A row group
- * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
- * sample rows of each component.  Upsampling will normally produce
- * max_v_samp_factor pixel rows from each row group (but this could vary
- * if the upsampler is applying a scale factor of its own).
- *
- * An excellent reference for image resampling is
- *   Digital Image Warping, George Wolberg, 1990.
- *   Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Pointer to routine to upsample a single component */
-typedef JMETHOD(void, upsample1_ptr,
-		(j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		 JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
-
-/* Private subobject */
-
-typedef struct {
-  struct jpeg_upsampler pub;	/* public fields */
-
-  /* Color conversion buffer.  When using separate upsampling and color
-   * conversion steps, this buffer holds one upsampled row group until it
-   * has been color converted and output.
-   * Note: we do not allocate any storage for component(s) which are full-size,
-   * ie do not need rescaling.  The corresponding entry of color_buf[] is
-   * simply set to point to the input data array, thereby avoiding copying.
-   */
-  JSAMPARRAY color_buf[MAX_COMPONENTS];
-
-  /* Per-component upsampling method pointers */
-  upsample1_ptr methods[MAX_COMPONENTS];
-
-  int next_row_out;		/* counts rows emitted from color_buf */
-  JDIMENSION rows_to_go;	/* counts rows remaining in image */
-
-  /* Height of an input row group for each component. */
-  int rowgroup_height[MAX_COMPONENTS];
-
-  /* These arrays save pixel expansion factors so that int_expand need not
-   * recompute them each time.  They are unused for other upsampling methods.
-   */
-  UINT8 h_expand[MAX_COMPONENTS];
-  UINT8 v_expand[MAX_COMPONENTS];
-} my_upsampler;
-
-typedef my_upsampler * my_upsample_ptr;
-
-
-/*
- * Initialize for an upsampling pass.
- */
-
-METHODDEF(void)
-start_pass_upsample (j_decompress_ptr cinfo)
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-
-  /* Mark the conversion buffer empty */
-  upsample->next_row_out = cinfo->max_v_samp_factor;
-  /* Initialize total-height counter for detecting bottom of image */
-  upsample->rows_to_go = cinfo->output_height;
-}
-
-
-/*
- * Control routine to do upsampling (and color conversion).
- *
- * In this version we upsample each component independently.
- * We upsample one row group into the conversion buffer, then apply
- * color conversion a row at a time.
- */
-
-METHODDEF(void)
-sep_upsample (j_decompress_ptr cinfo,
-	      JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
-	      JDIMENSION in_row_groups_avail,
-	      JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-	      JDIMENSION out_rows_avail)
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-  int ci;
-  jpeg_component_info * compptr;
-  JDIMENSION num_rows;
-
-  /* Fill the conversion buffer, if it's empty */
-  if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
-    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-	 ci++, compptr++) {
-      /* Invoke per-component upsample method.  Notice we pass a POINTER
-       * to color_buf[ci], so that fullsize_upsample can change it.
-       */
-      (*upsample->methods[ci]) (cinfo, compptr,
-	input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
-	upsample->color_buf + ci);
-    }
-    upsample->next_row_out = 0;
-  }
-
-  /* Color-convert and emit rows */
-
-  /* How many we have in the buffer: */
-  num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
-  /* Not more than the distance to the end of the image.  Need this test
-   * in case the image height is not a multiple of max_v_samp_factor:
-   */
-  if (num_rows > upsample->rows_to_go) 
-    num_rows = upsample->rows_to_go;
-  /* And not more than what the client can accept: */
-  out_rows_avail -= *out_row_ctr;
-  if (num_rows > out_rows_avail)
-    num_rows = out_rows_avail;
-
-  (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
-				     (JDIMENSION) upsample->next_row_out,
-				     output_buf + *out_row_ctr,
-				     (int) num_rows);
-
-  /* Adjust counts */
-  *out_row_ctr += num_rows;
-  upsample->rows_to_go -= num_rows;
-  upsample->next_row_out += num_rows;
-  /* When the buffer is emptied, declare this input row group consumed */
-  if (upsample->next_row_out >= cinfo->max_v_samp_factor)
-    (*in_row_group_ctr)++;
-}
-
-
-/*
- * These are the routines invoked by sep_upsample to upsample pixel values
- * of a single component.  One row group is processed per call.
- */
-
-
-/*
- * For full-size components, we just make color_buf[ci] point at the
- * input buffer, and thus avoid copying any data.  Note that this is
- * safe only because sep_upsample doesn't declare the input row group
- * "consumed" until we are done color converting and emitting it.
- */
-
-METHODDEF(void)
-fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		   JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
-{
-  *output_data_ptr = input_data;
-}
-
-
-/*
- * This is a no-op version used for "uninteresting" components.
- * These components will not be referenced by color conversion.
- */
-
-METHODDEF(void)
-noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	       JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
-{
-  *output_data_ptr = NULL;	/* safety check */
-}
-
-
-/*
- * This version handles any integral sampling ratios.
- * This is not used for typical JPEG files, so it need not be fast.
- * Nor, for that matter, is it particularly accurate: the algorithm is
- * simple replication of the input pixel onto the corresponding output
- * pixels.  The hi-falutin sampling literature refers to this as a
- * "box filter".  A box filter tends to introduce visible artifacts,
- * so if you are actually going to use 3:1 or 4:1 sampling ratios
- * you would be well advised to improve this code.
- */
-
-METHODDEF(void)
-int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	      JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
-{
-  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
-  JSAMPARRAY output_data = *output_data_ptr;
-  register JSAMPROW inptr, outptr;
-  register JSAMPLE invalue;
-  register int h;
-  JSAMPROW outend;
-  int h_expand, v_expand;
-  int inrow, outrow;
-
-  h_expand = upsample->h_expand[compptr->component_index];
-  v_expand = upsample->v_expand[compptr->component_index];
-
-  inrow = outrow = 0;
-  while (outrow < cinfo->max_v_samp_factor) {
-    /* Generate one output row with proper horizontal expansion */
-    inptr = input_data[inrow];
-    outptr = output_data[outrow];
-    outend = outptr + cinfo->output_width;
-    while (outptr < outend) {
-      invalue = *inptr++;	/* don't need GETJSAMPLE() here */
-      for (h = h_expand; h > 0; h--) {
-	*outptr++ = invalue;
-      }
-    }
-    /* Generate any additional output rows by duplicating the first one */
-    if (v_expand > 1) {
-      jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
-			v_expand-1, cinfo->output_width);
-    }
-    inrow++;
-    outrow += v_expand;
-  }
-}
-
-
-/*
- * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
- * It's still a box filter.
- */
-
-METHODDEF(void)
-h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	       JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
-{
-  JSAMPARRAY output_data = *output_data_ptr;
-  register JSAMPROW inptr, outptr;
-  register JSAMPLE invalue;
-  JSAMPROW outend;
-  int inrow;
-
-  for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
-    inptr = input_data[inrow];
-    outptr = output_data[inrow];
-    outend = outptr + cinfo->output_width;
-    while (outptr < outend) {
-      invalue = *inptr++;	/* don't need GETJSAMPLE() here */
-      *outptr++ = invalue;
-      *outptr++ = invalue;
-    }
-  }
-}
-
-
-/*
- * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
- * It's still a box filter.
- */
-
-METHODDEF(void)
-h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	       JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
-{
-  JSAMPARRAY output_data = *output_data_ptr;
-  register JSAMPROW inptr, outptr;
-  register JSAMPLE invalue;
-  JSAMPROW outend;
-  int inrow, outrow;
-
-  inrow = outrow = 0;
-  while (outrow < cinfo->max_v_samp_factor) {
-    inptr = input_data[inrow];
-    outptr = output_data[outrow];
-    outend = outptr + cinfo->output_width;
-    while (outptr < outend) {
-      invalue = *inptr++;	/* don't need GETJSAMPLE() here */
-      *outptr++ = invalue;
-      *outptr++ = invalue;
-    }
-    jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
-		      1, cinfo->output_width);
-    inrow++;
-    outrow += 2;
-  }
-}
-
-
-/*
- * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
- *
- * The upsampling algorithm is linear interpolation between pixel centers,
- * also known as a "triangle filter".  This is a good compromise between
- * speed and visual quality.  The centers of the output pixels are 1/4 and 3/4
- * of the way between input pixel centers.
- *
- * A note about the "bias" calculations: when rounding fractional values to
- * integer, we do not want to always round 0.5 up to the next integer.
- * If we did that, we'd introduce a noticeable bias towards larger values.
- * Instead, this code is arranged so that 0.5 will be rounded up or down at
- * alternate pixel locations (a simple ordered dither pattern).
- */
-
-METHODDEF(void)
-h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		     JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
-{
-  JSAMPARRAY output_data = *output_data_ptr;
-  register JSAMPROW inptr, outptr;
-  register int invalue;
-  register JDIMENSION colctr;
-  int inrow;
-
-  for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
-    inptr = input_data[inrow];
-    outptr = output_data[inrow];
-    /* Special case for first column */
-    invalue = GETJSAMPLE(*inptr++);
-    *outptr++ = (JSAMPLE) invalue;
-    *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
-
-    for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
-      /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
-      invalue = GETJSAMPLE(*inptr++) * 3;
-      *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
-      *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
-    }
-
-    /* Special case for last column */
-    invalue = GETJSAMPLE(*inptr);
-    *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
-    *outptr++ = (JSAMPLE) invalue;
-  }
-}
-
-
-/*
- * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
- * Again a triangle filter; see comments for h2v1 case, above.
- *
- * It is OK for us to reference the adjacent input rows because we demanded
- * context from the main buffer controller (see initialization code).
- */
-
-METHODDEF(void)
-h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		     JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
-{
-  JSAMPARRAY output_data = *output_data_ptr;
-  register JSAMPROW inptr0, inptr1, outptr;
-#if BITS_IN_JSAMPLE == 8
-  register int thiscolsum, lastcolsum, nextcolsum;
-#else
-  register INT32 thiscolsum, lastcolsum, nextcolsum;
-#endif
-  register JDIMENSION colctr;
-  int inrow, outrow, v;
-
-  inrow = outrow = 0;
-  while (outrow < cinfo->max_v_samp_factor) {
-    for (v = 0; v < 2; v++) {
-      /* inptr0 points to nearest input row, inptr1 points to next nearest */
-      inptr0 = input_data[inrow];
-      if (v == 0)		/* next nearest is row above */
-	inptr1 = input_data[inrow-1];
-      else			/* next nearest is row below */
-	inptr1 = input_data[inrow+1];
-      outptr = output_data[outrow++];
-
-      /* Special case for first column */
-      thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
-      nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
-      *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
-      *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
-      lastcolsum = thiscolsum; thiscolsum = nextcolsum;
-
-      for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
-	/* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
-	/* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
-	nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
-	*outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
-	*outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
-	lastcolsum = thiscolsum; thiscolsum = nextcolsum;
-      }
-
-      /* Special case for last column */
-      *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
-      *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
-    }
-    inrow++;
-  }
-}
-
-
-/*
- * Module initialization routine for upsampling.
- */
-
-GLOBAL(void)
-jinit_upsampler (j_decompress_ptr cinfo)
-{
-  my_upsample_ptr upsample;
-  int ci;
-  jpeg_component_info * compptr;
-  boolean need_buffer, do_fancy;
-  int h_in_group, v_in_group, h_out_group, v_out_group;
-
-  upsample = (my_upsample_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_upsampler));
-  cinfo->upsample = (struct jpeg_upsampler *) upsample;
-  upsample->pub.start_pass = start_pass_upsample;
-  upsample->pub.upsample = sep_upsample;
-  upsample->pub.need_context_rows = FALSE; /* until we find out differently */
-
-  if (cinfo->CCIR601_sampling)	/* this isn't supported */
-    ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
-
-  /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
-   * so don't ask for it.
-   */
-  do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
-
-  /* Verify we can handle the sampling factors, select per-component methods,
-   * and create storage as needed.
-   */
-  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
-       ci++, compptr++) {
-    /* Compute size of an "input group" after IDCT scaling.  This many samples
-     * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
-     */
-    h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
-		 cinfo->min_DCT_scaled_size;
-    v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
-		 cinfo->min_DCT_scaled_size;
-    h_out_group = cinfo->max_h_samp_factor;
-    v_out_group = cinfo->max_v_samp_factor;
-    upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
-    need_buffer = TRUE;
-    if (! compptr->component_needed) {
-      /* Don't bother to upsample an uninteresting component. */
-      upsample->methods[ci] = noop_upsample;
-      need_buffer = FALSE;
-    } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
-      /* Fullsize components can be processed without any work. */
-      upsample->methods[ci] = fullsize_upsample;
-      need_buffer = FALSE;
-    } else if (h_in_group * 2 == h_out_group &&
-	       v_in_group == v_out_group) {
-      /* Special cases for 2h1v upsampling */
-      if (do_fancy && compptr->downsampled_width > 2)
-	upsample->methods[ci] = h2v1_fancy_upsample;
-      else
-	upsample->methods[ci] = h2v1_upsample;
-    } else if (h_in_group * 2 == h_out_group &&
-	       v_in_group * 2 == v_out_group) {
-      /* Special cases for 2h2v upsampling */
-      if (do_fancy && compptr->downsampled_width > 2) {
-	upsample->methods[ci] = h2v2_fancy_upsample;
-	upsample->pub.need_context_rows = TRUE;
-      } else
-	upsample->methods[ci] = h2v2_upsample;
-    } else if ((h_out_group % h_in_group) == 0 &&
-	       (v_out_group % v_in_group) == 0) {
-      /* Generic integral-factors upsampling method */
-      upsample->methods[ci] = int_upsample;
-      upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
-      upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
-    } else
-      ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
-    if (need_buffer) {
-      upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
-	((j_common_ptr) cinfo, JPOOL_IMAGE,
-	 (JDIMENSION) jround_up((long) cinfo->output_width,
-				(long) cinfo->max_h_samp_factor),
-	 (JDIMENSION) cinfo->max_v_samp_factor);
-    }
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jdtrans.c ./Shared/jpeg-6b/jdtrans.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jdtrans.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jdtrans.c	Wed Dec 31 19:00:00 1969
@@ -1,143 +0,0 @@
-/*
- * jdtrans.c
- *
- * Copyright (C) 1995-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains library routines for transcoding decompression,
- * that is, reading raw DCT coefficient arrays from an input JPEG file.
- * The routines in jdapimin.c will also be needed by a transcoder.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/* Forward declarations */
-LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
-
-
-/*
- * Read the coefficient arrays from a JPEG file.
- * jpeg_read_header must be completed before calling this.
- *
- * The entire image is read into a set of virtual coefficient-block arrays,
- * one per component.  The return value is a pointer to the array of
- * virtual-array descriptors.  These can be manipulated directly via the
- * JPEG memory manager, or handed off to jpeg_write_coefficients().
- * To release the memory occupied by the virtual arrays, call
- * jpeg_finish_decompress() when done with the data.
- *
- * An alternative usage is to simply obtain access to the coefficient arrays
- * during a buffered-image-mode decompression operation.  This is allowed
- * after any jpeg_finish_output() call.  The arrays can be accessed until
- * jpeg_finish_decompress() is called.  (Note that any call to the library
- * may reposition the arrays, so don't rely on access_virt_barray() results
- * to stay valid across library calls.)
- *
- * Returns NULL if suspended.  This case need be checked only if
- * a suspending data source is used.
- */
-
-GLOBAL(jvirt_barray_ptr *)
-jpeg_read_coefficients (j_decompress_ptr cinfo)
-{
-  if (cinfo->global_state == DSTATE_READY) {
-    /* First call: initialize active modules */
-    transdecode_master_selection(cinfo);
-    cinfo->global_state = DSTATE_RDCOEFS;
-  }
-  if (cinfo->global_state == DSTATE_RDCOEFS) {
-    /* Absorb whole file into the coef buffer */
-    for (;;) {
-      int retcode;
-      /* Call progress monitor hook if present */
-      if (cinfo->progress != NULL)
-	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
-      /* Absorb some more input */
-      retcode = (*cinfo->inputctl->consume_input) (cinfo);
-      if (retcode == JPEG_SUSPENDED)
-	return NULL;
-      if (retcode == JPEG_REACHED_EOI)
-	break;
-      /* Advance progress counter if appropriate */
-      if (cinfo->progress != NULL &&
-	  (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
-	if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
-	  /* startup underestimated number of scans; ratchet up one scan */
-	  cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
-	}
-      }
-    }
-    /* Set state so that jpeg_finish_decompress does the right thing */
-    cinfo->global_state = DSTATE_STOPPING;
-  }
-  /* At this point we should be in state DSTATE_STOPPING if being used
-   * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
-   * to the coefficients during a full buffered-image-mode decompression.
-   */
-  if ((cinfo->global_state == DSTATE_STOPPING ||
-       cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
-    return cinfo->coef->coef_arrays;
-  }
-  /* Oops, improper usage */
-  ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
-  return NULL;			/* keep compiler happy */
-}
-
-
-/*
- * Master selection of decompression modules for transcoding.
- * This substitutes for jdmaster.c's initialization of the full decompressor.
- */
-
-LOCAL(void)
-transdecode_master_selection (j_decompress_ptr cinfo)
-{
-  /* This is effectively a buffered-image operation. */
-  cinfo->buffered_image = TRUE;
-
-  /* Entropy decoding: either Huffman or arithmetic coding. */
-  if (cinfo->arith_code) {
-    ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
-  } else {
-    if (cinfo->progressive_mode) {
-#ifdef D_PROGRESSIVE_SUPPORTED
-      jinit_phuff_decoder(cinfo);
-#else
-      ERREXIT(cinfo, JERR_NOT_COMPILED);
-#endif
-    } else
-      jinit_huff_decoder(cinfo);
-  }
-
-  /* Always get a full-image coefficient buffer. */
-  jinit_d_coef_controller(cinfo, TRUE);
-
-  /* We can now tell the memory manager to allocate virtual arrays. */
-  (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
-
-  /* Initialize input side of decompressor to consume first scan. */
-  (*cinfo->inputctl->start_input_pass) (cinfo);
-
-  /* Initialize progress monitoring. */
-  if (cinfo->progress != NULL) {
-    int nscans;
-    /* Estimate number of scans to set pass_limit. */
-    if (cinfo->progressive_mode) {
-      /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
-      nscans = 2 + 3 * cinfo->num_components;
-    } else if (cinfo->inputctl->has_multiple_scans) {
-      /* For a nonprogressive multiscan file, estimate 1 scan per component. */
-      nscans = cinfo->num_components;
-    } else {
-      nscans = 1;
-    }
-    cinfo->progress->pass_counter = 0L;
-    cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
-    cinfo->progress->completed_passes = 0;
-    cinfo->progress->total_passes = 1;
-  }
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jerror.c ./Shared/jpeg-6b/jerror.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jerror.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jerror.c	Wed Dec 31 19:00:00 1969
@@ -1,252 +0,0 @@
-/*
- * jerror.c
- *
- * Copyright (C) 1991-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains simple error-reporting and trace-message routines.
- * These are suitable for Unix-like systems and others where writing to
- * stderr is the right thing to do.  Many applications will want to replace
- * some or all of these routines.
- *
- * If you define USE_WINDOWS_MESSAGEBOX in jconfig.h or in the makefile,
- * you get a Windows-specific hack to display error messages in a dialog box.
- * It ain't much, but it beats dropping error messages into the bit bucket,
- * which is what happens to output to stderr under most Windows C compilers.
- *
- * These routines are used by both the compression and decompression code.
- */
-
-/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jversion.h"
-#include "jerror.h"
-
-#ifdef USE_WINDOWS_MESSAGEBOX
-#include <windows.h>
-#endif
-
-#ifndef EXIT_FAILURE		/* define exit() codes if not provided */
-#define EXIT_FAILURE  1
-#endif
-
-
-/*
- * Create the message string table.
- * We do this from the master message list in jerror.h by re-reading
- * jerror.h with a suitable definition for macro JMESSAGE.
- * The message table is made an external symbol just in case any applications
- * want to refer to it directly.
- */
-
-#ifdef NEED_SHORT_EXTERNAL_NAMES
-#define jpeg_std_message_table	jMsgTable
-#endif
-
-#define JMESSAGE(code,string)	string ,
-
-const char * const jpeg_std_message_table[] = {
-#include "jerror.h"
-  NULL
-};
-
-
-/*
- * Error exit handler: must not return to caller.
- *
- * Applications may override this if they want to get control back after
- * an error.  Typically one would longjmp somewhere instead of exiting.
- * The setjmp buffer can be made a private field within an expanded error
- * handler object.  Note that the info needed to generate an error message
- * is stored in the error object, so you can generate the message now or
- * later, at your convenience.
- * You should make sure that the JPEG object is cleaned up (with jpeg_abort
- * or jpeg_destroy) at some point.
- */
-
-METHODDEF(void)
-error_exit (j_common_ptr cinfo)
-{
-  /* Always display the message */
-  (*cinfo->err->output_message) (cinfo);
-
-  /* Let the memory manager delete any temp files before we die */
-  jpeg_destroy(cinfo);
-
-  exit(EXIT_FAILURE);
-}
-
-
-/*
- * Actual output of an error or trace message.
- * Applications may override this method to send JPEG messages somewhere
- * other than stderr.
- *
- * On Windows, printing to stderr is generally completely useless,
- * so we provide optional code to produce an error-dialog popup.
- * Most Windows applications will still prefer to override this routine,
- * but if they don't, it'll do something at least marginally useful.
- *
- * NOTE: to use the library in an environment that doesn't support the
- * C stdio library, you may have to delete the call to fprintf() entirely,
- * not just not use this routine.
- */
-
-METHODDEF(void)
-output_message (j_common_ptr cinfo)
-{
-  char buffer[JMSG_LENGTH_MAX];
-
-  /* Create the message */
-  (*cinfo->err->format_message) (cinfo, buffer);
-
-#ifdef USE_WINDOWS_MESSAGEBOX
-  /* Display it in a message dialog box */
-  MessageBox(GetActiveWindow(), buffer, "JPEG Library Error",
-	     MB_OK | MB_ICONERROR);
-#else
-  /* Send it to stderr, adding a newline */
-  fprintf(stderr, "%s\n", buffer);
-#endif
-}
-
-
-/*
- * Decide whether to emit a trace or warning message.
- * msg_level is one of:
- *   -1: recoverable corrupt-data warning, may want to abort.
- *    0: important advisory messages (always display to user).
- *    1: first level of tracing detail.
- *    2,3,...: successively more detailed tracing messages.
- * An application might override this method if it wanted to abort on warnings
- * or change the policy about which messages to display.
- */
-
-METHODDEF(void)
-emit_message (j_common_ptr cinfo, int msg_level)
-{
-  struct jpeg_error_mgr * err = cinfo->err;
-
-  if (msg_level < 0) {
-    /* It's a warning message.  Since corrupt files may generate many warnings,
-     * the policy implemented here is to show only the first warning,
-     * unless trace_level >= 3.
-     */
-    if (err->num_warnings == 0 || err->trace_level >= 3)
-      (*err->output_message) (cinfo);
-    /* Always count warnings in num_warnings. */
-    err->num_warnings++;
-  } else {
-    /* It's a trace message.  Show it if trace_level >= msg_level. */
-    if (err->trace_level >= msg_level)
-      (*err->output_message) (cinfo);
-  }
-}
-
-
-/*
- * Format a message string for the most recent JPEG error or message.
- * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX
- * characters.  Note that no '\n' character is added to the string.
- * Few applications should need to override this method.
- */
-
-METHODDEF(void)
-format_message (j_common_ptr cinfo, char * buffer)
-{
-  struct jpeg_error_mgr * err = cinfo->err;
-  int msg_code = err->msg_code;
-  const char * msgtext = NULL;
-  const char * msgptr;
-  char ch;
-  boolean isstring;
-
-  /* Look up message string in proper table */
-  if (msg_code > 0 && msg_code <= err->last_jpeg_message) {
-    msgtext = err->jpeg_message_table[msg_code];
-  } else if (err->addon_message_table != NULL &&
-	     msg_code >= err->first_addon_message &&
-	     msg_code <= err->last_addon_message) {
-    msgtext = err->addon_message_table[msg_code - err->first_addon_message];
-  }
-
-  /* Defend against bogus message number */
-  if (msgtext == NULL) {
-    err->msg_parm.i[0] = msg_code;
-    msgtext = err->jpeg_message_table[0];
-  }
-
-  /* Check for string parameter, as indicated by %s in the message text */
-  isstring = FALSE;
-  msgptr = msgtext;
-  while ((ch = *msgptr++) != '\0') {
-    if (ch == '%') {
-      if (*msgptr == 's') isstring = TRUE;
-      break;
-    }
-  }
-
-  /* Format the message into the passed buffer */
-  if (isstring)
-    sprintf(buffer, msgtext, err->msg_parm.s);
-  else
-    sprintf(buffer, msgtext,
-	    err->msg_parm.i[0], err->msg_parm.i[1],
-	    err->msg_parm.i[2], err->msg_parm.i[3],
-	    err->msg_parm.i[4], err->msg_parm.i[5],
-	    err->msg_parm.i[6], err->msg_parm.i[7]);
-}
-
-
-/*
- * Reset error state variables at start of a new image.
- * This is called during compression startup to reset trace/error
- * processing to default state, without losing any application-specific
- * method pointers.  An application might possibly want to override
- * this method if it has additional error processing state.
- */
-
-METHODDEF(void)
-reset_error_mgr (j_common_ptr cinfo)
-{
-  cinfo->err->num_warnings = 0;
-  /* trace_level is not reset since it is an application-supplied parameter */
-  cinfo->err->msg_code = 0;	/* may be useful as a flag for "no error" */
-}
-
-
-/*
- * Fill in the standard error-handling methods in a jpeg_error_mgr object.
- * Typical call is:
- *	struct jpeg_compress_struct cinfo;
- *	struct jpeg_error_mgr err;
- *
- *	cinfo.err = jpeg_std_error(&err);
- * after which the application may override some of the methods.
- */
-
-GLOBAL(struct jpeg_error_mgr *)
-jpeg_std_error (struct jpeg_error_mgr * err)
-{
-  err->error_exit = error_exit;
-  err->emit_message = emit_message;
-  err->output_message = output_message;
-  err->format_message = format_message;
-  err->reset_error_mgr = reset_error_mgr;
-
-  err->trace_level = 0;		/* default = no tracing */
-  err->num_warnings = 0;	/* no warnings emitted yet */
-  err->msg_code = 0;		/* may be useful as a flag for "no error" */
-
-  /* Initialize message table pointers */
-  err->jpeg_message_table = jpeg_std_message_table;
-  err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1;
-
-  err->addon_message_table = NULL;
-  err->first_addon_message = 0;	/* for safety */
-  err->last_addon_message = 0;
-
-  return err;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jerror.h ./Shared/jpeg-6b/jerror.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jerror.h	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jerror.h	Wed Dec 31 19:00:00 1969
@@ -1,291 +0,0 @@
-/*
- * jerror.h
- *
- * Copyright (C) 1994-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file defines the error and message codes for the JPEG library.
- * Edit this file to add new codes, or to translate the message strings to
- * some other language.
- * A set of error-reporting macros are defined too.  Some applications using
- * the JPEG library may wish to include this file to get the error codes
- * and/or the macros.
- */
-
-/*
- * To define the enum list of message codes, include this file without
- * defining macro JMESSAGE.  To create a message string table, include it
- * again with a suitable JMESSAGE definition (see jerror.c for an example).
- */
-#ifndef JMESSAGE
-#ifndef JERROR_H
-/* First time through, define the enum list */
-#define JMAKE_ENUM_LIST
-#else
-/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
-#define JMESSAGE(code,string)
-#endif /* JERROR_H */
-#endif /* JMESSAGE */
-
-#ifdef JMAKE_ENUM_LIST
-
-typedef enum {
-
-#define JMESSAGE(code,string)	code ,
-
-#endif /* JMAKE_ENUM_LIST */
-
-JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
-
-/* For maintenance convenience, list is alphabetical by message code name */
-JMESSAGE(JERR_ARITH_NOTIMPL,
-	 "Sorry, there are legal restrictions on arithmetic coding")
-JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
-JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
-JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
-JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
-JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
-JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
-JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
-JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
-JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
-JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
-JMESSAGE(JERR_BAD_LIB_VERSION,
-	 "Wrong JPEG library version: library is %d, caller expects %d")
-JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
-JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
-JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
-JMESSAGE(JERR_BAD_PROGRESSION,
-	 "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
-JMESSAGE(JERR_BAD_PROG_SCRIPT,
-	 "Invalid progressive parameters at scan script entry %d")
-JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
-JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
-JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
-JMESSAGE(JERR_BAD_STRUCT_SIZE,
-	 "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
-JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
-JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
-JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
-JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
-JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
-JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
-JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
-JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
-JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
-JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
-JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
-JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
-JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
-JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
-JMESSAGE(JERR_FILE_READ, "Input file read error")
-JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
-JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
-JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
-JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
-JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
-JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
-JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
-JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
-	 "Cannot transcode due to multiple use of quantization table %d")
-JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
-JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
-JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
-JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
-JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
-JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
-JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
-JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
-JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
-JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
-JMESSAGE(JERR_QUANT_COMPONENTS,
-	 "Cannot quantize more than %d color components")
-JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
-JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
-JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
-JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
-JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
-JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
-JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
-JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
-JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
-JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
-JMESSAGE(JERR_TFILE_WRITE,
-	 "Write failed on temporary file --- out of disk space?")
-JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
-JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
-JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
-JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
-JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
-JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
-JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
-JMESSAGE(JMSG_VERSION, JVERSION)
-JMESSAGE(JTRC_16BIT_TABLES,
-	 "Caution: quantization tables are too coarse for baseline JPEG")
-JMESSAGE(JTRC_ADOBE,
-	 "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
-JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
-JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
-JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
-JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
-JMESSAGE(JTRC_DQT, "Define Quantization Table %d  precision %d")
-JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
-JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
-JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
-JMESSAGE(JTRC_EOI, "End Of Image")
-JMESSAGE(JTRC_HUFFBITS, "        %3d %3d %3d %3d %3d %3d %3d %3d")
-JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d  %d")
-JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
-	 "Warning: thumbnail image size does not match data length %u")
-JMESSAGE(JTRC_JFIF_EXTENSION,
-	 "JFIF extension marker: type 0x%02x, length %u")
-JMESSAGE(JTRC_JFIF_THUMBNAIL, "    with %d x %d thumbnail image")
-JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
-JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
-JMESSAGE(JTRC_QUANTVALS, "        %4u %4u %4u %4u %4u %4u %4u %4u")
-JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
-JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
-JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
-JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
-JMESSAGE(JTRC_RST, "RST%d")
-JMESSAGE(JTRC_SMOOTH_NOTIMPL,
-	 "Smoothing not supported with nonstandard sampling ratios")
-JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
-JMESSAGE(JTRC_SOF_COMPONENT, "    Component %d: %dhx%dv q=%d")
-JMESSAGE(JTRC_SOI, "Start of Image")
-JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
-JMESSAGE(JTRC_SOS_COMPONENT, "    Component %d: dc=%d ac=%d")
-JMESSAGE(JTRC_SOS_PARAMS, "  Ss=%d, Se=%d, Ah=%d, Al=%d")
-JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
-JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
-JMESSAGE(JTRC_THUMB_JPEG,
-	 "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
-JMESSAGE(JTRC_THUMB_PALETTE,
-	 "JFIF extension marker: palette thumbnail image, length %u")
-JMESSAGE(JTRC_THUMB_RGB,
-	 "JFIF extension marker: RGB thumbnail image, length %u")
-JMESSAGE(JTRC_UNKNOWN_IDS,
-	 "Unrecognized component IDs %d %d %d, assuming YCbCr")
-JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
-JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
-JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
-JMESSAGE(JWRN_BOGUS_PROGRESSION,
-	 "Inconsistent progression sequence for component %d coefficient %d")
-JMESSAGE(JWRN_EXTRANEOUS_DATA,
-	 "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
-JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
-JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
-JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
-JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
-JMESSAGE(JWRN_MUST_RESYNC,
-	 "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
-JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
-JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
-
-#ifdef JMAKE_ENUM_LIST
-
-  JMSG_LASTMSGCODE
-} J_MESSAGE_CODE;
-
-#undef JMAKE_ENUM_LIST
-#endif /* JMAKE_ENUM_LIST */
-
-/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
-#undef JMESSAGE
-
-
-#ifndef JERROR_H
-#define JERROR_H
-
-/* Macros to simplify using the error and trace message stuff */
-/* The first parameter is either type of cinfo pointer */
-
-/* Fatal errors (print message and exit) */
-#define ERREXIT(cinfo,code)  \
-  ((cinfo)->err->msg_code = (code), \
-   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
-#define ERREXIT1(cinfo,code,p1)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
-#define ERREXIT2(cinfo,code,p1,p2)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (cinfo)->err->msg_parm.i[1] = (p2), \
-   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
-#define ERREXIT3(cinfo,code,p1,p2,p3)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (cinfo)->err->msg_parm.i[1] = (p2), \
-   (cinfo)->err->msg_parm.i[2] = (p3), \
-   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
-#define ERREXIT4(cinfo,code,p1,p2,p3,p4)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (cinfo)->err->msg_parm.i[1] = (p2), \
-   (cinfo)->err->msg_parm.i[2] = (p3), \
-   (cinfo)->err->msg_parm.i[3] = (p4), \
-   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
-#define ERREXITS(cinfo,code,str)  \
-  ((cinfo)->err->msg_code = (code), \
-   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
-   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
-
-#define MAKESTMT(stuff)		do { stuff } while (0)
-
-/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
-#define WARNMS(cinfo,code)  \
-  ((cinfo)->err->msg_code = (code), \
-   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
-#define WARNMS1(cinfo,code,p1)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
-#define WARNMS2(cinfo,code,p1,p2)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (cinfo)->err->msg_parm.i[1] = (p2), \
-   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
-
-/* Informational/debugging messages */
-#define TRACEMS(cinfo,lvl,code)  \
-  ((cinfo)->err->msg_code = (code), \
-   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
-#define TRACEMS1(cinfo,lvl,code,p1)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
-#define TRACEMS2(cinfo,lvl,code,p1,p2)  \
-  ((cinfo)->err->msg_code = (code), \
-   (cinfo)->err->msg_parm.i[0] = (p1), \
-   (cinfo)->err->msg_parm.i[1] = (p2), \
-   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
-#define TRACEMS3(cinfo,lvl,code,p1,p2,p3)  \
-  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
-	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
-	   (cinfo)->err->msg_code = (code); \
-	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
-#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4)  \
-  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
-	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
-	   (cinfo)->err->msg_code = (code); \
-	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
-#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5)  \
-  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
-	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
-	   _mp[4] = (p5); \
-	   (cinfo)->err->msg_code = (code); \
-	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
-#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8)  \
-  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
-	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
-	   _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
-	   (cinfo)->err->msg_code = (code); \
-	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
-#define TRACEMSS(cinfo,lvl,code,str)  \
-  ((cinfo)->err->msg_code = (code), \
-   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
-   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
-
-#endif /* JERROR_H */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jfdctflt.c ./Shared/jpeg-6b/jfdctflt.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jfdctflt.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jfdctflt.c	Wed Dec 31 19:00:00 1969
@@ -1,168 +0,0 @@
-/*
- * jfdctflt.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains a floating-point implementation of the
- * forward DCT (Discrete Cosine Transform).
- *
- * This implementation should be more accurate than either of the integer
- * DCT implementations.  However, it may not give the same results on all
- * machines because of differences in roundoff behavior.  Speed will depend
- * on the hardware's floating point capacity.
- *
- * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
- * on each column.  Direct algorithms are also available, but they are
- * much more complex and seem not to be any faster when reduced to code.
- *
- * This implementation is based on Arai, Agui, and Nakajima's algorithm for
- * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
- * Japanese, but the algorithm is described in the Pennebaker & Mitchell
- * JPEG textbook (see REFERENCES section in file README).  The following code
- * is based directly on figure 4-8 in P&M.
- * While an 8-point DCT cannot be done in less than 11 multiplies, it is
- * possible to arrange the computation so that many of the multiplies are
- * simple scalings of the final outputs.  These multiplies can then be
- * folded into the multiplications or divisions by the JPEG quantization
- * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
- * to be done in the DCT itself.
- * The primary disadvantage of this method is that with a fixed-point
- * implementation, accuracy is lost due to imprecise representation of the
- * scaled quantization values.  However, that problem does not arise if
- * we use floating point arithmetic.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-#ifdef DCT_FLOAT_SUPPORTED
-
-
-/*
- * This module is specialized to the case DCTSIZE = 8.
- */
-
-#if DCTSIZE != 8
-  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
-#endif
-
-
-/*
- * Perform the forward DCT on one block of samples.
- */
-
-GLOBAL(void)
-jpeg_fdct_float (FAST_FLOAT * data)
-{
-  FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
-  FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
-  FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
-  FAST_FLOAT *dataptr;
-  int ctr;
-
-  /* Pass 1: process rows. */
-
-  dataptr = data;
-  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
-    tmp0 = dataptr[0] + dataptr[7];
-    tmp7 = dataptr[0] - dataptr[7];
-    tmp1 = dataptr[1] + dataptr[6];
-    tmp6 = dataptr[1] - dataptr[6];
-    tmp2 = dataptr[2] + dataptr[5];
-    tmp5 = dataptr[2] - dataptr[5];
-    tmp3 = dataptr[3] + dataptr[4];
-    tmp4 = dataptr[3] - dataptr[4];
-    
-    /* Even part */
-    
-    tmp10 = tmp0 + tmp3;	/* phase 2 */
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    dataptr[0] = tmp10 + tmp11; /* phase 3 */
-    dataptr[4] = tmp10 - tmp11;
-    
-    z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
-    dataptr[2] = tmp13 + z1;	/* phase 5 */
-    dataptr[6] = tmp13 - z1;
-    
-    /* Odd part */
-
-    tmp10 = tmp4 + tmp5;	/* phase 2 */
-    tmp11 = tmp5 + tmp6;
-    tmp12 = tmp6 + tmp7;
-
-    /* The rotator is modified from fig 4-8 to avoid extra negations. */
-    z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
-    z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
-    z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
-    z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
-
-    z11 = tmp7 + z3;		/* phase 5 */
-    z13 = tmp7 - z3;
-
-    dataptr[5] = z13 + z2;	/* phase 6 */
-    dataptr[3] = z13 - z2;
-    dataptr[1] = z11 + z4;
-    dataptr[7] = z11 - z4;
-
-    dataptr += DCTSIZE;		/* advance pointer to next row */
-  }
-
-  /* Pass 2: process columns. */
-
-  dataptr = data;
-  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
-    tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
-    tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
-    tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
-    tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
-    tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
-    tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
-    tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
-    tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
-    
-    /* Even part */
-    
-    tmp10 = tmp0 + tmp3;	/* phase 2 */
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
-    dataptr[DCTSIZE*4] = tmp10 - tmp11;
-    
-    z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
-    dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
-    dataptr[DCTSIZE*6] = tmp13 - z1;
-    
-    /* Odd part */
-
-    tmp10 = tmp4 + tmp5;	/* phase 2 */
-    tmp11 = tmp5 + tmp6;
-    tmp12 = tmp6 + tmp7;
-
-    /* The rotator is modified from fig 4-8 to avoid extra negations. */
-    z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
-    z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
-    z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
-    z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
-
-    z11 = tmp7 + z3;		/* phase 5 */
-    z13 = tmp7 - z3;
-
-    dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
-    dataptr[DCTSIZE*3] = z13 - z2;
-    dataptr[DCTSIZE*1] = z11 + z4;
-    dataptr[DCTSIZE*7] = z11 - z4;
-
-    dataptr++;			/* advance pointer to next column */
-  }
-}
-
-#endif /* DCT_FLOAT_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jfdctfst.c ./Shared/jpeg-6b/jfdctfst.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jfdctfst.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jfdctfst.c	Wed Dec 31 19:00:00 1969
@@ -1,224 +0,0 @@
-/*
- * jfdctfst.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains a fast, not so accurate integer implementation of the
- * forward DCT (Discrete Cosine Transform).
- *
- * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
- * on each column.  Direct algorithms are also available, but they are
- * much more complex and seem not to be any faster when reduced to code.
- *
- * This implementation is based on Arai, Agui, and Nakajima's algorithm for
- * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
- * Japanese, but the algorithm is described in the Pennebaker & Mitchell
- * JPEG textbook (see REFERENCES section in file README).  The following code
- * is based directly on figure 4-8 in P&M.
- * While an 8-point DCT cannot be done in less than 11 multiplies, it is
- * possible to arrange the computation so that many of the multiplies are
- * simple scalings of the final outputs.  These multiplies can then be
- * folded into the multiplications or divisions by the JPEG quantization
- * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
- * to be done in the DCT itself.
- * The primary disadvantage of this method is that with fixed-point math,
- * accuracy is lost due to imprecise representation of the scaled
- * quantization values.  The smaller the quantization table entry, the less
- * precise the scaled value, so this implementation does worse with high-
- * quality-setting files than with low-quality ones.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-#ifdef DCT_IFAST_SUPPORTED
-
-
-/*
- * This module is specialized to the case DCTSIZE = 8.
- */
-
-#if DCTSIZE != 8
-  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
-#endif
-
-
-/* Scaling decisions are generally the same as in the LL&M algorithm;
- * see jfdctint.c for more details.  However, we choose to descale
- * (right shift) multiplication products as soon as they are formed,
- * rather than carrying additional fractional bits into subsequent additions.
- * This compromises accuracy slightly, but it lets us save a few shifts.
- * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
- * everywhere except in the multiplications proper; this saves a good deal
- * of work on 16-bit-int machines.
- *
- * Again to save a few shifts, the intermediate results between pass 1 and
- * pass 2 are not upscaled, but are represented only to integral precision.
- *
- * A final compromise is to represent the multiplicative constants to only
- * 8 fractional bits, rather than 13.  This saves some shifting work on some
- * machines, and may also reduce the cost of multiplication (since there
- * are fewer one-bits in the constants).
- */
-
-#define CONST_BITS  8
-
-
-/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
- * causing a lot of useless floating-point operations at run time.
- * To get around this we use the following pre-calculated constants.
- * If you change CONST_BITS you may want to add appropriate values.
- * (With a reasonable C compiler, you can just rely on the FIX() macro...)
- */
-
-#if CONST_BITS == 8
-#define FIX_0_382683433  ((INT32)   98)		/* FIX(0.382683433) */
-#define FIX_0_541196100  ((INT32)  139)		/* FIX(0.541196100) */
-#define FIX_0_707106781  ((INT32)  181)		/* FIX(0.707106781) */
-#define FIX_1_306562965  ((INT32)  334)		/* FIX(1.306562965) */
-#else
-#define FIX_0_382683433  FIX(0.382683433)
-#define FIX_0_541196100  FIX(0.541196100)
-#define FIX_0_707106781  FIX(0.707106781)
-#define FIX_1_306562965  FIX(1.306562965)
-#endif
-
-
-/* We can gain a little more speed, with a further compromise in accuracy,
- * by omitting the addition in a descaling shift.  This yields an incorrectly
- * rounded result half the time...
- */
-
-#ifndef USE_ACCURATE_ROUNDING
-#undef DESCALE
-#define DESCALE(x,n)  RIGHT_SHIFT(x, n)
-#endif
-
-
-/* Multiply a DCTELEM variable by an INT32 constant, and immediately
- * descale to yield a DCTELEM result.
- */
-
-#define MULTIPLY(var,const)  ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
-
-
-/*
- * Perform the forward DCT on one block of samples.
- */
-
-GLOBAL(void)
-jpeg_fdct_ifast (DCTELEM * data)
-{
-  DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
-  DCTELEM tmp10, tmp11, tmp12, tmp13;
-  DCTELEM z1, z2, z3, z4, z5, z11, z13;
-  DCTELEM *dataptr;
-  int ctr;
-  SHIFT_TEMPS
-
-  /* Pass 1: process rows. */
-
-  dataptr = data;
-  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
-    tmp0 = dataptr[0] + dataptr[7];
-    tmp7 = dataptr[0] - dataptr[7];
-    tmp1 = dataptr[1] + dataptr[6];
-    tmp6 = dataptr[1] - dataptr[6];
-    tmp2 = dataptr[2] + dataptr[5];
-    tmp5 = dataptr[2] - dataptr[5];
-    tmp3 = dataptr[3] + dataptr[4];
-    tmp4 = dataptr[3] - dataptr[4];
-    
-    /* Even part */
-    
-    tmp10 = tmp0 + tmp3;	/* phase 2 */
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    dataptr[0] = tmp10 + tmp11; /* phase 3 */
-    dataptr[4] = tmp10 - tmp11;
-    
-    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
-    dataptr[2] = tmp13 + z1;	/* phase 5 */
-    dataptr[6] = tmp13 - z1;
-    
-    /* Odd part */
-
-    tmp10 = tmp4 + tmp5;	/* phase 2 */
-    tmp11 = tmp5 + tmp6;
-    tmp12 = tmp6 + tmp7;
-
-    /* The rotator is modified from fig 4-8 to avoid extra negations. */
-    z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
-    z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
-    z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
-    z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
-
-    z11 = tmp7 + z3;		/* phase 5 */
-    z13 = tmp7 - z3;
-
-    dataptr[5] = z13 + z2;	/* phase 6 */
-    dataptr[3] = z13 - z2;
-    dataptr[1] = z11 + z4;
-    dataptr[7] = z11 - z4;
-
-    dataptr += DCTSIZE;		/* advance pointer to next row */
-  }
-
-  /* Pass 2: process columns. */
-
-  dataptr = data;
-  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
-    tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
-    tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
-    tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
-    tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
-    tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
-    tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
-    tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
-    tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
-    
-    /* Even part */
-    
-    tmp10 = tmp0 + tmp3;	/* phase 2 */
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
-    dataptr[DCTSIZE*4] = tmp10 - tmp11;
-    
-    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
-    dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
-    dataptr[DCTSIZE*6] = tmp13 - z1;
-    
-    /* Odd part */
-
-    tmp10 = tmp4 + tmp5;	/* phase 2 */
-    tmp11 = tmp5 + tmp6;
-    tmp12 = tmp6 + tmp7;
-
-    /* The rotator is modified from fig 4-8 to avoid extra negations. */
-    z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
-    z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
-    z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
-    z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
-
-    z11 = tmp7 + z3;		/* phase 5 */
-    z13 = tmp7 - z3;
-
-    dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
-    dataptr[DCTSIZE*3] = z13 - z2;
-    dataptr[DCTSIZE*1] = z11 + z4;
-    dataptr[DCTSIZE*7] = z11 - z4;
-
-    dataptr++;			/* advance pointer to next column */
-  }
-}
-
-#endif /* DCT_IFAST_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jfdctint.c ./Shared/jpeg-6b/jfdctint.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jfdctint.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jfdctint.c	Wed Dec 31 19:00:00 1969
@@ -1,283 +0,0 @@
-/*
- * jfdctint.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains a slow-but-accurate integer implementation of the
- * forward DCT (Discrete Cosine Transform).
- *
- * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
- * on each column.  Direct algorithms are also available, but they are
- * much more complex and seem not to be any faster when reduced to code.
- *
- * This implementation is based on an algorithm described in
- *   C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
- *   Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
- *   Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
- * The primary algorithm described there uses 11 multiplies and 29 adds.
- * We use their alternate method with 12 multiplies and 32 adds.
- * The advantage of this method is that no data path contains more than one
- * multiplication; this allows a very simple and accurate implementation in
- * scaled fixed-point arithmetic, with a minimal number of shifts.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-#ifdef DCT_ISLOW_SUPPORTED
-
-
-/*
- * This module is specialized to the case DCTSIZE = 8.
- */
-
-#if DCTSIZE != 8
-  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
-#endif
-
-
-/*
- * The poop on this scaling stuff is as follows:
- *
- * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
- * larger than the true DCT outputs.  The final outputs are therefore
- * a factor of N larger than desired; since N=8 this can be cured by
- * a simple right shift at the end of the algorithm.  The advantage of
- * this arrangement is that we save two multiplications per 1-D DCT,
- * because the y0 and y4 outputs need not be divided by sqrt(N).
- * In the IJG code, this factor of 8 is removed by the quantization step
- * (in jcdctmgr.c), NOT in this module.
- *
- * We have to do addition and subtraction of the integer inputs, which
- * is no problem, and multiplication by fractional constants, which is
- * a problem to do in integer arithmetic.  We multiply all the constants
- * by CONST_SCALE and convert them to integer constants (thus retaining
- * CONST_BITS bits of precision in the constants).  After doing a
- * multiplication we have to divide the product by CONST_SCALE, with proper
- * rounding, to produce the correct output.  This division can be done
- * cheaply as a right shift of CONST_BITS bits.  We postpone shifting
- * as long as possible so that partial sums can be added together with
- * full fractional precision.
- *
- * The outputs of the first pass are scaled up by PASS1_BITS bits so that
- * they are represented to better-than-integral precision.  These outputs
- * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
- * with the recommended scaling.  (For 12-bit sample data, the intermediate
- * array is INT32 anyway.)
- *
- * To avoid overflow of the 32-bit intermediate results in pass 2, we must
- * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26.  Error analysis
- * shows that the values given below are the most effective.
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define CONST_BITS  13
-#define PASS1_BITS  2
-#else
-#define CONST_BITS  13
-#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
-#endif
-
-/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
- * causing a lot of useless floating-point operations at run time.
- * To get around this we use the following pre-calculated constants.
- * If you change CONST_BITS you may want to add appropriate values.
- * (With a reasonable C compiler, you can just rely on the FIX() macro...)
- */
-
-#if CONST_BITS == 13
-#define FIX_0_298631336  ((INT32)  2446)	/* FIX(0.298631336) */
-#define FIX_0_390180644  ((INT32)  3196)	/* FIX(0.390180644) */
-#define FIX_0_541196100  ((INT32)  4433)	/* FIX(0.541196100) */
-#define FIX_0_765366865  ((INT32)  6270)	/* FIX(0.765366865) */
-#define FIX_0_899976223  ((INT32)  7373)	/* FIX(0.899976223) */
-#define FIX_1_175875602  ((INT32)  9633)	/* FIX(1.175875602) */
-#define FIX_1_501321110  ((INT32)  12299)	/* FIX(1.501321110) */
-#define FIX_1_847759065  ((INT32)  15137)	/* FIX(1.847759065) */
-#define FIX_1_961570560  ((INT32)  16069)	/* FIX(1.961570560) */
-#define FIX_2_053119869  ((INT32)  16819)	/* FIX(2.053119869) */
-#define FIX_2_562915447  ((INT32)  20995)	/* FIX(2.562915447) */
-#define FIX_3_072711026  ((INT32)  25172)	/* FIX(3.072711026) */
-#else
-#define FIX_0_298631336  FIX(0.298631336)
-#define FIX_0_390180644  FIX(0.390180644)
-#define FIX_0_541196100  FIX(0.541196100)
-#define FIX_0_765366865  FIX(0.765366865)
-#define FIX_0_899976223  FIX(0.899976223)
-#define FIX_1_175875602  FIX(1.175875602)
-#define FIX_1_501321110  FIX(1.501321110)
-#define FIX_1_847759065  FIX(1.847759065)
-#define FIX_1_961570560  FIX(1.961570560)
-#define FIX_2_053119869  FIX(2.053119869)
-#define FIX_2_562915447  FIX(2.562915447)
-#define FIX_3_072711026  FIX(3.072711026)
-#endif
-
-
-/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
- * For 8-bit samples with the recommended scaling, all the variable
- * and constant values involved are no more than 16 bits wide, so a
- * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
- * For 12-bit samples, a full 32-bit multiplication will be needed.
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define MULTIPLY(var,const)  MULTIPLY16C16(var,const)
-#else
-#define MULTIPLY(var,const)  ((var) * (const))
-#endif
-
-
-/*
- * Perform the forward DCT on one block of samples.
- */
-
-GLOBAL(void)
-jpeg_fdct_islow (DCTELEM * data)
-{
-  INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
-  INT32 tmp10, tmp11, tmp12, tmp13;
-  INT32 z1, z2, z3, z4, z5;
-  DCTELEM *dataptr;
-  int ctr;
-  SHIFT_TEMPS
-
-  /* Pass 1: process rows. */
-  /* Note results are scaled up by sqrt(8) compared to a true DCT; */
-  /* furthermore, we scale the results by 2**PASS1_BITS. */
-
-  dataptr = data;
-  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
-    tmp0 = dataptr[0] + dataptr[7];
-    tmp7 = dataptr[0] - dataptr[7];
-    tmp1 = dataptr[1] + dataptr[6];
-    tmp6 = dataptr[1] - dataptr[6];
-    tmp2 = dataptr[2] + dataptr[5];
-    tmp5 = dataptr[2] - dataptr[5];
-    tmp3 = dataptr[3] + dataptr[4];
-    tmp4 = dataptr[3] - dataptr[4];
-    
-    /* Even part per LL&M figure 1 --- note that published figure is faulty;
-     * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
-     */
-    
-    tmp10 = tmp0 + tmp3;
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
-    dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
-    
-    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
-    dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
-				   CONST_BITS-PASS1_BITS);
-    dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
-				   CONST_BITS-PASS1_BITS);
-    
-    /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
-     * cK represents cos(K*pi/16).
-     * i0..i3 in the paper are tmp4..tmp7 here.
-     */
-    
-    z1 = tmp4 + tmp7;
-    z2 = tmp5 + tmp6;
-    z3 = tmp4 + tmp6;
-    z4 = tmp5 + tmp7;
-    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
-    
-    tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
-    tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
-    tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
-    tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
-    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
-    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
-    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
-    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
-    
-    z3 += z5;
-    z4 += z5;
-    
-    dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
-    dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
-    dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
-    dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
-    
-    dataptr += DCTSIZE;		/* advance pointer to next row */
-  }
-
-  /* Pass 2: process columns.
-   * We remove the PASS1_BITS scaling, but leave the results scaled up
-   * by an overall factor of 8.
-   */
-
-  dataptr = data;
-  for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
-    tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
-    tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
-    tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
-    tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
-    tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
-    tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
-    tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
-    tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
-    
-    /* Even part per LL&M figure 1 --- note that published figure is faulty;
-     * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
-     */
-    
-    tmp10 = tmp0 + tmp3;
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
-    dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
-    
-    z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
-    dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
-					   CONST_BITS+PASS1_BITS);
-    dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
-					   CONST_BITS+PASS1_BITS);
-    
-    /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
-     * cK represents cos(K*pi/16).
-     * i0..i3 in the paper are tmp4..tmp7 here.
-     */
-    
-    z1 = tmp4 + tmp7;
-    z2 = tmp5 + tmp6;
-    z3 = tmp4 + tmp6;
-    z4 = tmp5 + tmp7;
-    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
-    
-    tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
-    tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
-    tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
-    tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
-    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
-    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
-    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
-    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
-    
-    z3 += z5;
-    z4 += z5;
-    
-    dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
-					   CONST_BITS+PASS1_BITS);
-    dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
-					   CONST_BITS+PASS1_BITS);
-    dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
-					   CONST_BITS+PASS1_BITS);
-    dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
-					   CONST_BITS+PASS1_BITS);
-    
-    dataptr++;			/* advance pointer to next column */
-  }
-}
-
-#endif /* DCT_ISLOW_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jidctflt.c ./Shared/jpeg-6b/jidctflt.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jidctflt.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jidctflt.c	Wed Dec 31 19:00:00 1969
@@ -1,242 +0,0 @@
-/*
- * jidctflt.c
- *
- * Copyright (C) 1994-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains a floating-point implementation of the
- * inverse DCT (Discrete Cosine Transform).  In the IJG code, this routine
- * must also perform dequantization of the input coefficients.
- *
- * This implementation should be more accurate than either of the integer
- * IDCT implementations.  However, it may not give the same results on all
- * machines because of differences in roundoff behavior.  Speed will depend
- * on the hardware's floating point capacity.
- *
- * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
- * on each row (or vice versa, but it's more convenient to emit a row at
- * a time).  Direct algorithms are also available, but they are much more
- * complex and seem not to be any faster when reduced to code.
- *
- * This implementation is based on Arai, Agui, and Nakajima's algorithm for
- * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
- * Japanese, but the algorithm is described in the Pennebaker & Mitchell
- * JPEG textbook (see REFERENCES section in file README).  The following code
- * is based directly on figure 4-8 in P&M.
- * While an 8-point DCT cannot be done in less than 11 multiplies, it is
- * possible to arrange the computation so that many of the multiplies are
- * simple scalings of the final outputs.  These multiplies can then be
- * folded into the multiplications or divisions by the JPEG quantization
- * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
- * to be done in the DCT itself.
- * The primary disadvantage of this method is that with a fixed-point
- * implementation, accuracy is lost due to imprecise representation of the
- * scaled quantization values.  However, that problem does not arise if
- * we use floating point arithmetic.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-#ifdef DCT_FLOAT_SUPPORTED
-
-
-/*
- * This module is specialized to the case DCTSIZE = 8.
- */
-
-#if DCTSIZE != 8
-  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
-#endif
-
-
-/* Dequantize a coefficient by multiplying it by the multiplier-table
- * entry; produce a float result.
- */
-
-#define DEQUANTIZE(coef,quantval)  (((FAST_FLOAT) (coef)) * (quantval))
-
-
-/*
- * Perform dequantization and inverse DCT on one block of coefficients.
- */
-
-GLOBAL(void)
-jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		 JCOEFPTR coef_block,
-		 JSAMPARRAY output_buf, JDIMENSION output_col)
-{
-  FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
-  FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
-  FAST_FLOAT z5, z10, z11, z12, z13;
-  JCOEFPTR inptr;
-  FLOAT_MULT_TYPE * quantptr;
-  FAST_FLOAT * wsptr;
-  JSAMPROW outptr;
-  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
-  int ctr;
-  FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
-  SHIFT_TEMPS
-
-  /* Pass 1: process columns from input, store into work array. */
-
-  inptr = coef_block;
-  quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
-  wsptr = workspace;
-  for (ctr = DCTSIZE; ctr > 0; ctr--) {
-    /* Due to quantization, we will usually find that many of the input
-     * coefficients are zero, especially the AC terms.  We can exploit this
-     * by short-circuiting the IDCT calculation for any column in which all
-     * the AC terms are zero.  In that case each output is equal to the
-     * DC coefficient (with scale factor as needed).
-     * With typical images and quantization tables, half or more of the
-     * column DCT calculations can be simplified this way.
-     */
-    
-    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
-	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
-	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
-	inptr[DCTSIZE*7] == 0) {
-      /* AC terms all zero */
-      FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
-      
-      wsptr[DCTSIZE*0] = dcval;
-      wsptr[DCTSIZE*1] = dcval;
-      wsptr[DCTSIZE*2] = dcval;
-      wsptr[DCTSIZE*3] = dcval;
-      wsptr[DCTSIZE*4] = dcval;
-      wsptr[DCTSIZE*5] = dcval;
-      wsptr[DCTSIZE*6] = dcval;
-      wsptr[DCTSIZE*7] = dcval;
-      
-      inptr++;			/* advance pointers to next column */
-      quantptr++;
-      wsptr++;
-      continue;
-    }
-    
-    /* Even part */
-
-    tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
-    tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
-    tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
-    tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
-
-    tmp10 = tmp0 + tmp2;	/* phase 3 */
-    tmp11 = tmp0 - tmp2;
-
-    tmp13 = tmp1 + tmp3;	/* phases 5-3 */
-    tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
-
-    tmp0 = tmp10 + tmp13;	/* phase 2 */
-    tmp3 = tmp10 - tmp13;
-    tmp1 = tmp11 + tmp12;
-    tmp2 = tmp11 - tmp12;
-    
-    /* Odd part */
-
-    tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
-    tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
-    tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
-    tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
-
-    z13 = tmp6 + tmp5;		/* phase 6 */
-    z10 = tmp6 - tmp5;
-    z11 = tmp4 + tmp7;
-    z12 = tmp4 - tmp7;
-
-    tmp7 = z11 + z13;		/* phase 5 */
-    tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
-
-    z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
-    tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
-    tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
-
-    tmp6 = tmp12 - tmp7;	/* phase 2 */
-    tmp5 = tmp11 - tmp6;
-    tmp4 = tmp10 + tmp5;
-
-    wsptr[DCTSIZE*0] = tmp0 + tmp7;
-    wsptr[DCTSIZE*7] = tmp0 - tmp7;
-    wsptr[DCTSIZE*1] = tmp1 + tmp6;
-    wsptr[DCTSIZE*6] = tmp1 - tmp6;
-    wsptr[DCTSIZE*2] = tmp2 + tmp5;
-    wsptr[DCTSIZE*5] = tmp2 - tmp5;
-    wsptr[DCTSIZE*4] = tmp3 + tmp4;
-    wsptr[DCTSIZE*3] = tmp3 - tmp4;
-
-    inptr++;			/* advance pointers to next column */
-    quantptr++;
-    wsptr++;
-  }
-  
-  /* Pass 2: process rows from work array, store into output array. */
-  /* Note that we must descale the results by a factor of 8 == 2**3. */
-
-  wsptr = workspace;
-  for (ctr = 0; ctr < DCTSIZE; ctr++) {
-    outptr = output_buf[ctr] + output_col;
-    /* Rows of zeroes can be exploited in the same way as we did with columns.
-     * However, the column calculation has created many nonzero AC terms, so
-     * the simplification applies less often (typically 5% to 10% of the time).
-     * And testing floats for zero is relatively expensive, so we don't bother.
-     */
-    
-    /* Even part */
-
-    tmp10 = wsptr[0] + wsptr[4];
-    tmp11 = wsptr[0] - wsptr[4];
-
-    tmp13 = wsptr[2] + wsptr[6];
-    tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
-
-    tmp0 = tmp10 + tmp13;
-    tmp3 = tmp10 - tmp13;
-    tmp1 = tmp11 + tmp12;
-    tmp2 = tmp11 - tmp12;
-
-    /* Odd part */
-
-    z13 = wsptr[5] + wsptr[3];
-    z10 = wsptr[5] - wsptr[3];
-    z11 = wsptr[1] + wsptr[7];
-    z12 = wsptr[1] - wsptr[7];
-
-    tmp7 = z11 + z13;
-    tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
-
-    z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
-    tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
-    tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
-
-    tmp6 = tmp12 - tmp7;
-    tmp5 = tmp11 - tmp6;
-    tmp4 = tmp10 + tmp5;
-
-    /* Final output stage: scale down by a factor of 8 and range-limit */
-
-    outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
-			    & RANGE_MASK];
-    outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
-			    & RANGE_MASK];
-    outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
-			    & RANGE_MASK];
-    outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
-			    & RANGE_MASK];
-    outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
-			    & RANGE_MASK];
-    outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
-			    & RANGE_MASK];
-    outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
-			    & RANGE_MASK];
-    outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
-			    & RANGE_MASK];
-    
-    wsptr += DCTSIZE;		/* advance pointer to next row */
-  }
-}
-
-#endif /* DCT_FLOAT_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jidctfst.c ./Shared/jpeg-6b/jidctfst.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jidctfst.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jidctfst.c	Wed Dec 31 19:00:00 1969
@@ -1,368 +0,0 @@
-/*
- * jidctfst.c
- *
- * Copyright (C) 1994-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains a fast, not so accurate integer implementation of the
- * inverse DCT (Discrete Cosine Transform).  In the IJG code, this routine
- * must also perform dequantization of the input coefficients.
- *
- * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
- * on each row (or vice versa, but it's more convenient to emit a row at
- * a time).  Direct algorithms are also available, but they are much more
- * complex and seem not to be any faster when reduced to code.
- *
- * This implementation is based on Arai, Agui, and Nakajima's algorithm for
- * scaled DCT.  Their original paper (Trans. IEICE E-71(11):1095) is in
- * Japanese, but the algorithm is described in the Pennebaker & Mitchell
- * JPEG textbook (see REFERENCES section in file README).  The following code
- * is based directly on figure 4-8 in P&M.
- * While an 8-point DCT cannot be done in less than 11 multiplies, it is
- * possible to arrange the computation so that many of the multiplies are
- * simple scalings of the final outputs.  These multiplies can then be
- * folded into the multiplications or divisions by the JPEG quantization
- * table entries.  The AA&N method leaves only 5 multiplies and 29 adds
- * to be done in the DCT itself.
- * The primary disadvantage of this method is that with fixed-point math,
- * accuracy is lost due to imprecise representation of the scaled
- * quantization values.  The smaller the quantization table entry, the less
- * precise the scaled value, so this implementation does worse with high-
- * quality-setting files than with low-quality ones.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-#ifdef DCT_IFAST_SUPPORTED
-
-
-/*
- * This module is specialized to the case DCTSIZE = 8.
- */
-
-#if DCTSIZE != 8
-  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
-#endif
-
-
-/* Scaling decisions are generally the same as in the LL&M algorithm;
- * see jidctint.c for more details.  However, we choose to descale
- * (right shift) multiplication products as soon as they are formed,
- * rather than carrying additional fractional bits into subsequent additions.
- * This compromises accuracy slightly, but it lets us save a few shifts.
- * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
- * everywhere except in the multiplications proper; this saves a good deal
- * of work on 16-bit-int machines.
- *
- * The dequantized coefficients are not integers because the AA&N scaling
- * factors have been incorporated.  We represent them scaled up by PASS1_BITS,
- * so that the first and second IDCT rounds have the same input scaling.
- * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
- * avoid a descaling shift; this compromises accuracy rather drastically
- * for small quantization table entries, but it saves a lot of shifts.
- * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
- * so we use a much larger scaling factor to preserve accuracy.
- *
- * A final compromise is to represent the multiplicative constants to only
- * 8 fractional bits, rather than 13.  This saves some shifting work on some
- * machines, and may also reduce the cost of multiplication (since there
- * are fewer one-bits in the constants).
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define CONST_BITS  8
-#define PASS1_BITS  2
-#else
-#define CONST_BITS  8
-#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
-#endif
-
-/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
- * causing a lot of useless floating-point operations at run time.
- * To get around this we use the following pre-calculated constants.
- * If you change CONST_BITS you may want to add appropriate values.
- * (With a reasonable C compiler, you can just rely on the FIX() macro...)
- */
-
-#if CONST_BITS == 8
-#define FIX_1_082392200  ((INT32)  277)		/* FIX(1.082392200) */
-#define FIX_1_414213562  ((INT32)  362)		/* FIX(1.414213562) */
-#define FIX_1_847759065  ((INT32)  473)		/* FIX(1.847759065) */
-#define FIX_2_613125930  ((INT32)  669)		/* FIX(2.613125930) */
-#else
-#define FIX_1_082392200  FIX(1.082392200)
-#define FIX_1_414213562  FIX(1.414213562)
-#define FIX_1_847759065  FIX(1.847759065)
-#define FIX_2_613125930  FIX(2.613125930)
-#endif
-
-
-/* We can gain a little more speed, with a further compromise in accuracy,
- * by omitting the addition in a descaling shift.  This yields an incorrectly
- * rounded result half the time...
- */
-
-#ifndef USE_ACCURATE_ROUNDING
-#undef DESCALE
-#define DESCALE(x,n)  RIGHT_SHIFT(x, n)
-#endif
-
-
-/* Multiply a DCTELEM variable by an INT32 constant, and immediately
- * descale to yield a DCTELEM result.
- */
-
-#define MULTIPLY(var,const)  ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
-
-
-/* Dequantize a coefficient by multiplying it by the multiplier-table
- * entry; produce a DCTELEM result.  For 8-bit data a 16x16->16
- * multiplication will do.  For 12-bit data, the multiplier table is
- * declared INT32, so a 32-bit multiply will be used.
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define DEQUANTIZE(coef,quantval)  (((IFAST_MULT_TYPE) (coef)) * (quantval))
-#else
-#define DEQUANTIZE(coef,quantval)  \
-	DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
-#endif
-
-
-/* Like DESCALE, but applies to a DCTELEM and produces an int.
- * We assume that int right shift is unsigned if INT32 right shift is.
- */
-
-#ifdef RIGHT_SHIFT_IS_UNSIGNED
-#define ISHIFT_TEMPS	DCTELEM ishift_temp;
-#if BITS_IN_JSAMPLE == 8
-#define DCTELEMBITS  16		/* DCTELEM may be 16 or 32 bits */
-#else
-#define DCTELEMBITS  32		/* DCTELEM must be 32 bits */
-#endif
-#define IRIGHT_SHIFT(x,shft)  \
-    ((ishift_temp = (x)) < 0 ? \
-     (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
-     (ishift_temp >> (shft)))
-#else
-#define ISHIFT_TEMPS
-#define IRIGHT_SHIFT(x,shft)	((x) >> (shft))
-#endif
-
-#ifdef USE_ACCURATE_ROUNDING
-#define IDESCALE(x,n)  ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
-#else
-#define IDESCALE(x,n)  ((int) IRIGHT_SHIFT(x, n))
-#endif
-
-
-/*
- * Perform dequantization and inverse DCT on one block of coefficients.
- */
-
-GLOBAL(void)
-jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		 JCOEFPTR coef_block,
-		 JSAMPARRAY output_buf, JDIMENSION output_col)
-{
-  DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
-  DCTELEM tmp10, tmp11, tmp12, tmp13;
-  DCTELEM z5, z10, z11, z12, z13;
-  JCOEFPTR inptr;
-  IFAST_MULT_TYPE * quantptr;
-  int * wsptr;
-  JSAMPROW outptr;
-  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
-  int ctr;
-  int workspace[DCTSIZE2];	/* buffers data between passes */
-  SHIFT_TEMPS			/* for DESCALE */
-  ISHIFT_TEMPS			/* for IDESCALE */
-
-  /* Pass 1: process columns from input, store into work array. */
-
-  inptr = coef_block;
-  quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
-  wsptr = workspace;
-  for (ctr = DCTSIZE; ctr > 0; ctr--) {
-    /* Due to quantization, we will usually find that many of the input
-     * coefficients are zero, especially the AC terms.  We can exploit this
-     * by short-circuiting the IDCT calculation for any column in which all
-     * the AC terms are zero.  In that case each output is equal to the
-     * DC coefficient (with scale factor as needed).
-     * With typical images and quantization tables, half or more of the
-     * column DCT calculations can be simplified this way.
-     */
-    
-    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
-	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
-	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
-	inptr[DCTSIZE*7] == 0) {
-      /* AC terms all zero */
-      int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
-
-      wsptr[DCTSIZE*0] = dcval;
-      wsptr[DCTSIZE*1] = dcval;
-      wsptr[DCTSIZE*2] = dcval;
-      wsptr[DCTSIZE*3] = dcval;
-      wsptr[DCTSIZE*4] = dcval;
-      wsptr[DCTSIZE*5] = dcval;
-      wsptr[DCTSIZE*6] = dcval;
-      wsptr[DCTSIZE*7] = dcval;
-      
-      inptr++;			/* advance pointers to next column */
-      quantptr++;
-      wsptr++;
-      continue;
-    }
-    
-    /* Even part */
-
-    tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
-    tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
-    tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
-    tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
-
-    tmp10 = tmp0 + tmp2;	/* phase 3 */
-    tmp11 = tmp0 - tmp2;
-
-    tmp13 = tmp1 + tmp3;	/* phases 5-3 */
-    tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
-
-    tmp0 = tmp10 + tmp13;	/* phase 2 */
-    tmp3 = tmp10 - tmp13;
-    tmp1 = tmp11 + tmp12;
-    tmp2 = tmp11 - tmp12;
-    
-    /* Odd part */
-
-    tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
-    tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
-    tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
-    tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
-
-    z13 = tmp6 + tmp5;		/* phase 6 */
-    z10 = tmp6 - tmp5;
-    z11 = tmp4 + tmp7;
-    z12 = tmp4 - tmp7;
-
-    tmp7 = z11 + z13;		/* phase 5 */
-    tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
-
-    z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
-    tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
-    tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
-
-    tmp6 = tmp12 - tmp7;	/* phase 2 */
-    tmp5 = tmp11 - tmp6;
-    tmp4 = tmp10 + tmp5;
-
-    wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
-    wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
-    wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
-    wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
-    wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
-    wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
-    wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
-    wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
-
-    inptr++;			/* advance pointers to next column */
-    quantptr++;
-    wsptr++;
-  }
-  
-  /* Pass 2: process rows from work array, store into output array. */
-  /* Note that we must descale the results by a factor of 8 == 2**3, */
-  /* and also undo the PASS1_BITS scaling. */
-
-  wsptr = workspace;
-  for (ctr = 0; ctr < DCTSIZE; ctr++) {
-    outptr = output_buf[ctr] + output_col;
-    /* Rows of zeroes can be exploited in the same way as we did with columns.
-     * However, the column calculation has created many nonzero AC terms, so
-     * the simplification applies less often (typically 5% to 10% of the time).
-     * On machines with very fast multiplication, it's possible that the
-     * test takes more time than it's worth.  In that case this section
-     * may be commented out.
-     */
-    
-#ifndef NO_ZERO_ROW_TEST
-    if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
-	wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
-      /* AC terms all zero */
-      JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
-				  & RANGE_MASK];
-      
-      outptr[0] = dcval;
-      outptr[1] = dcval;
-      outptr[2] = dcval;
-      outptr[3] = dcval;
-      outptr[4] = dcval;
-      outptr[5] = dcval;
-      outptr[6] = dcval;
-      outptr[7] = dcval;
-
-      wsptr += DCTSIZE;		/* advance pointer to next row */
-      continue;
-    }
-#endif
-    
-    /* Even part */
-
-    tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
-    tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
-
-    tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
-    tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
-	    - tmp13;
-
-    tmp0 = tmp10 + tmp13;
-    tmp3 = tmp10 - tmp13;
-    tmp1 = tmp11 + tmp12;
-    tmp2 = tmp11 - tmp12;
-
-    /* Odd part */
-
-    z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
-    z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
-    z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
-    z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
-
-    tmp7 = z11 + z13;		/* phase 5 */
-    tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
-
-    z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
-    tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
-    tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
-
-    tmp6 = tmp12 - tmp7;	/* phase 2 */
-    tmp5 = tmp11 - tmp6;
-    tmp4 = tmp10 + tmp5;
-
-    /* Final output stage: scale down by a factor of 8 and range-limit */
-
-    outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
-			    & RANGE_MASK];
-
-    wsptr += DCTSIZE;		/* advance pointer to next row */
-  }
-}
-
-#endif /* DCT_IFAST_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jidctint.c ./Shared/jpeg-6b/jidctint.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jidctint.c	Mon Dec  1 12:30:37 2003
+++ ./Shared/jpeg-6b/jidctint.c	Wed Dec 31 19:00:00 1969
@@ -1,389 +0,0 @@
-/*
- * jidctint.c
- *
- * Copyright (C) 1991-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains a slow-but-accurate integer implementation of the
- * inverse DCT (Discrete Cosine Transform).  In the IJG code, this routine
- * must also perform dequantization of the input coefficients.
- *
- * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT
- * on each row (or vice versa, but it's more convenient to emit a row at
- * a time).  Direct algorithms are also available, but they are much more
- * complex and seem not to be any faster when reduced to code.
- *
- * This implementation is based on an algorithm described in
- *   C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
- *   Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
- *   Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
- * The primary algorithm described there uses 11 multiplies and 29 adds.
- * We use their alternate method with 12 multiplies and 32 adds.
- * The advantage of this method is that no data path contains more than one
- * multiplication; this allows a very simple and accurate implementation in
- * scaled fixed-point arithmetic, with a minimal number of shifts.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-#ifdef DCT_ISLOW_SUPPORTED
-
-
-/*
- * This module is specialized to the case DCTSIZE = 8.
- */
-
-#if DCTSIZE != 8
-  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
-#endif
-
-
-/*
- * The poop on this scaling stuff is as follows:
- *
- * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
- * larger than the true IDCT outputs.  The final outputs are therefore
- * a factor of N larger than desired; since N=8 this can be cured by
- * a simple right shift at the end of the algorithm.  The advantage of
- * this arrangement is that we save two multiplications per 1-D IDCT,
- * because the y0 and y4 inputs need not be divided by sqrt(N).
- *
- * We have to do addition and subtraction of the integer inputs, which
- * is no problem, and multiplication by fractional constants, which is
- * a problem to do in integer arithmetic.  We multiply all the constants
- * by CONST_SCALE and convert them to integer constants (thus retaining
- * CONST_BITS bits of precision in the constants).  After doing a
- * multiplication we have to divide the product by CONST_SCALE, with proper
- * rounding, to produce the correct output.  This division can be done
- * cheaply as a right shift of CONST_BITS bits.  We postpone shifting
- * as long as possible so that partial sums can be added together with
- * full fractional precision.
- *
- * The outputs of the first pass are scaled up by PASS1_BITS bits so that
- * they are represented to better-than-integral precision.  These outputs
- * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
- * with the recommended scaling.  (To scale up 12-bit sample data further, an
- * intermediate INT32 array would be needed.)
- *
- * To avoid overflow of the 32-bit intermediate results in pass 2, we must
- * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26.  Error analysis
- * shows that the values given below are the most effective.
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define CONST_BITS  13
-#define PASS1_BITS  2
-#else
-#define CONST_BITS  13
-#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
-#endif
-
-/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
- * causing a lot of useless floating-point operations at run time.
- * To get around this we use the following pre-calculated constants.
- * If you change CONST_BITS you may want to add appropriate values.
- * (With a reasonable C compiler, you can just rely on the FIX() macro...)
- */
-
-#if CONST_BITS == 13
-#define FIX_0_298631336  ((INT32)  2446)	/* FIX(0.298631336) */
-#define FIX_0_390180644  ((INT32)  3196)	/* FIX(0.390180644) */
-#define FIX_0_541196100  ((INT32)  4433)	/* FIX(0.541196100) */
-#define FIX_0_765366865  ((INT32)  6270)	/* FIX(0.765366865) */
-#define FIX_0_899976223  ((INT32)  7373)	/* FIX(0.899976223) */
-#define FIX_1_175875602  ((INT32)  9633)	/* FIX(1.175875602) */
-#define FIX_1_501321110  ((INT32)  12299)	/* FIX(1.501321110) */
-#define FIX_1_847759065  ((INT32)  15137)	/* FIX(1.847759065) */
-#define FIX_1_961570560  ((INT32)  16069)	/* FIX(1.961570560) */
-#define FIX_2_053119869  ((INT32)  16819)	/* FIX(2.053119869) */
-#define FIX_2_562915447  ((INT32)  20995)	/* FIX(2.562915447) */
-#define FIX_3_072711026  ((INT32)  25172)	/* FIX(3.072711026) */
-#else
-#define FIX_0_298631336  FIX(0.298631336)
-#define FIX_0_390180644  FIX(0.390180644)
-#define FIX_0_541196100  FIX(0.541196100)
-#define FIX_0_765366865  FIX(0.765366865)
-#define FIX_0_899976223  FIX(0.899976223)
-#define FIX_1_175875602  FIX(1.175875602)
-#define FIX_1_501321110  FIX(1.501321110)
-#define FIX_1_847759065  FIX(1.847759065)
-#define FIX_1_961570560  FIX(1.961570560)
-#define FIX_2_053119869  FIX(2.053119869)
-#define FIX_2_562915447  FIX(2.562915447)
-#define FIX_3_072711026  FIX(3.072711026)
-#endif
-
-
-/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
- * For 8-bit samples with the recommended scaling, all the variable
- * and constant values involved are no more than 16 bits wide, so a
- * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
- * For 12-bit samples, a full 32-bit multiplication will be needed.
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define MULTIPLY(var,const)  MULTIPLY16C16(var,const)
-#else
-#define MULTIPLY(var,const)  ((var) * (const))
-#endif
-
-
-/* Dequantize a coefficient by multiplying it by the multiplier-table
- * entry; produce an int result.  In this module, both inputs and result
- * are 16 bits or less, so either int or short multiply will work.
- */
-
-#define DEQUANTIZE(coef,quantval)  (((ISLOW_MULT_TYPE) (coef)) * (quantval))
-
-
-/*
- * Perform dequantization and inverse DCT on one block of coefficients.
- */
-
-GLOBAL(void)
-jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		 JCOEFPTR coef_block,
-		 JSAMPARRAY output_buf, JDIMENSION output_col)
-{
-  INT32 tmp0, tmp1, tmp2, tmp3;
-  INT32 tmp10, tmp11, tmp12, tmp13;
-  INT32 z1, z2, z3, z4, z5;
-  JCOEFPTR inptr;
-  ISLOW_MULT_TYPE * quantptr;
-  int * wsptr;
-  JSAMPROW outptr;
-  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
-  int ctr;
-  int workspace[DCTSIZE2];	/* buffers data between passes */
-  SHIFT_TEMPS
-
-  /* Pass 1: process columns from input, store into work array. */
-  /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
-  /* furthermore, we scale the results by 2**PASS1_BITS. */
-
-  inptr = coef_block;
-  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
-  wsptr = workspace;
-  for (ctr = DCTSIZE; ctr > 0; ctr--) {
-    /* Due to quantization, we will usually find that many of the input
-     * coefficients are zero, especially the AC terms.  We can exploit this
-     * by short-circuiting the IDCT calculation for any column in which all
-     * the AC terms are zero.  In that case each output is equal to the
-     * DC coefficient (with scale factor as needed).
-     * With typical images and quantization tables, half or more of the
-     * column DCT calculations can be simplified this way.
-     */
-    
-    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
-	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
-	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
-	inptr[DCTSIZE*7] == 0) {
-      /* AC terms all zero */
-      int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
-      
-      wsptr[DCTSIZE*0] = dcval;
-      wsptr[DCTSIZE*1] = dcval;
-      wsptr[DCTSIZE*2] = dcval;
-      wsptr[DCTSIZE*3] = dcval;
-      wsptr[DCTSIZE*4] = dcval;
-      wsptr[DCTSIZE*5] = dcval;
-      wsptr[DCTSIZE*6] = dcval;
-      wsptr[DCTSIZE*7] = dcval;
-      
-      inptr++;			/* advance pointers to next column */
-      quantptr++;
-      wsptr++;
-      continue;
-    }
-    
-    /* Even part: reverse the even part of the forward DCT. */
-    /* The rotator is sqrt(2)*c(-6). */
-    
-    z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
-    z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
-    
-    z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
-    tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
-    tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
-    
-    z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
-    z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
-
-    tmp0 = (z2 + z3) << CONST_BITS;
-    tmp1 = (z2 - z3) << CONST_BITS;
-    
-    tmp10 = tmp0 + tmp3;
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    /* Odd part per figure 8; the matrix is unitary and hence its
-     * transpose is its inverse.  i0..i3 are y7,y5,y3,y1 respectively.
-     */
-    
-    tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
-    tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
-    tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
-    tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
-    
-    z1 = tmp0 + tmp3;
-    z2 = tmp1 + tmp2;
-    z3 = tmp0 + tmp2;
-    z4 = tmp1 + tmp3;
-    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
-    
-    tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
-    tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
-    tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
-    tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
-    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
-    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
-    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
-    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
-    
-    z3 += z5;
-    z4 += z5;
-    
-    tmp0 += z1 + z3;
-    tmp1 += z2 + z4;
-    tmp2 += z2 + z3;
-    tmp3 += z1 + z4;
-    
-    /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
-    
-    wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
-    wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
-    wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
-    wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
-    wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
-    wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
-    wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
-    wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
-    
-    inptr++;			/* advance pointers to next column */
-    quantptr++;
-    wsptr++;
-  }
-  
-  /* Pass 2: process rows from work array, store into output array. */
-  /* Note that we must descale the results by a factor of 8 == 2**3, */
-  /* and also undo the PASS1_BITS scaling. */
-
-  wsptr = workspace;
-  for (ctr = 0; ctr < DCTSIZE; ctr++) {
-    outptr = output_buf[ctr] + output_col;
-    /* Rows of zeroes can be exploited in the same way as we did with columns.
-     * However, the column calculation has created many nonzero AC terms, so
-     * the simplification applies less often (typically 5% to 10% of the time).
-     * On machines with very fast multiplication, it's possible that the
-     * test takes more time than it's worth.  In that case this section
-     * may be commented out.
-     */
-    
-#ifndef NO_ZERO_ROW_TEST
-    if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
-	wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
-      /* AC terms all zero */
-      JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
-				  & RANGE_MASK];
-      
-      outptr[0] = dcval;
-      outptr[1] = dcval;
-      outptr[2] = dcval;
-      outptr[3] = dcval;
-      outptr[4] = dcval;
-      outptr[5] = dcval;
-      outptr[6] = dcval;
-      outptr[7] = dcval;
-
-      wsptr += DCTSIZE;		/* advance pointer to next row */
-      continue;
-    }
-#endif
-    
-    /* Even part: reverse the even part of the forward DCT. */
-    /* The rotator is sqrt(2)*c(-6). */
-    
-    z2 = (INT32) wsptr[2];
-    z3 = (INT32) wsptr[6];
-    
-    z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
-    tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
-    tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
-    
-    tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
-    tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
-    
-    tmp10 = tmp0 + tmp3;
-    tmp13 = tmp0 - tmp3;
-    tmp11 = tmp1 + tmp2;
-    tmp12 = tmp1 - tmp2;
-    
-    /* Odd part per figure 8; the matrix is unitary and hence its
-     * transpose is its inverse.  i0..i3 are y7,y5,y3,y1 respectively.
-     */
-    
-    tmp0 = (INT32) wsptr[7];
-    tmp1 = (INT32) wsptr[5];
-    tmp2 = (INT32) wsptr[3];
-    tmp3 = (INT32) wsptr[1];
-    
-    z1 = tmp0 + tmp3;
-    z2 = tmp1 + tmp2;
-    z3 = tmp0 + tmp2;
-    z4 = tmp1 + tmp3;
-    z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
-    
-    tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
-    tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
-    tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
-    tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
-    z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
-    z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
-    z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
-    z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
-    
-    z3 += z5;
-    z4 += z5;
-    
-    tmp0 += z1 + z3;
-    tmp1 += z2 + z4;
-    tmp2 += z2 + z3;
-    tmp3 += z1 + z4;
-    
-    /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
-    
-    outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
-					  CONST_BITS+PASS1_BITS+3)
-			    & RANGE_MASK];
-    
-    wsptr += DCTSIZE;		/* advance pointer to next row */
-  }
-}
-
-#endif /* DCT_ISLOW_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jidctred.c ./Shared/jpeg-6b/jidctred.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jidctred.c	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jidctred.c	Wed Dec 31 19:00:00 1969
@@ -1,398 +0,0 @@
-/*
- * jidctred.c
- *
- * Copyright (C) 1994-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains inverse-DCT routines that produce reduced-size output:
- * either 4x4, 2x2, or 1x1 pixels from an 8x8 DCT block.
- *
- * The implementation is based on the Loeffler, Ligtenberg and Moschytz (LL&M)
- * algorithm used in jidctint.c.  We simply replace each 8-to-8 1-D IDCT step
- * with an 8-to-4 step that produces the four averages of two adjacent outputs
- * (or an 8-to-2 step producing two averages of four outputs, for 2x2 output).
- * These steps were derived by computing the corresponding values at the end
- * of the normal LL&M code, then simplifying as much as possible.
- *
- * 1x1 is trivial: just take the DC coefficient divided by 8.
- *
- * See jidctint.c for additional comments.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jdct.h"		/* Private declarations for DCT subsystem */
-
-#ifdef IDCT_SCALING_SUPPORTED
-
-
-/*
- * This module is specialized to the case DCTSIZE = 8.
- */
-
-#if DCTSIZE != 8
-  Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
-#endif
-
-
-/* Scaling is the same as in jidctint.c. */
-
-#if BITS_IN_JSAMPLE == 8
-#define CONST_BITS  13
-#define PASS1_BITS  2
-#else
-#define CONST_BITS  13
-#define PASS1_BITS  1		/* lose a little precision to avoid overflow */
-#endif
-
-/* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
- * causing a lot of useless floating-point operations at run time.
- * To get around this we use the following pre-calculated constants.
- * If you change CONST_BITS you may want to add appropriate values.
- * (With a reasonable C compiler, you can just rely on the FIX() macro...)
- */
-
-#if CONST_BITS == 13
-#define FIX_0_211164243  ((INT32)  1730)	/* FIX(0.211164243) */
-#define FIX_0_509795579  ((INT32)  4176)	/* FIX(0.509795579) */
-#define FIX_0_601344887  ((INT32)  4926)	/* FIX(0.601344887) */
-#define FIX_0_720959822  ((INT32)  5906)	/* FIX(0.720959822) */
-#define FIX_0_765366865  ((INT32)  6270)	/* FIX(0.765366865) */
-#define FIX_0_850430095  ((INT32)  6967)	/* FIX(0.850430095) */
-#define FIX_0_899976223  ((INT32)  7373)	/* FIX(0.899976223) */
-#define FIX_1_061594337  ((INT32)  8697)	/* FIX(1.061594337) */
-#define FIX_1_272758580  ((INT32)  10426)	/* FIX(1.272758580) */
-#define FIX_1_451774981  ((INT32)  11893)	/* FIX(1.451774981) */
-#define FIX_1_847759065  ((INT32)  15137)	/* FIX(1.847759065) */
-#define FIX_2_172734803  ((INT32)  17799)	/* FIX(2.172734803) */
-#define FIX_2_562915447  ((INT32)  20995)	/* FIX(2.562915447) */
-#define FIX_3_624509785  ((INT32)  29692)	/* FIX(3.624509785) */
-#else
-#define FIX_0_211164243  FIX(0.211164243)
-#define FIX_0_509795579  FIX(0.509795579)
-#define FIX_0_601344887  FIX(0.601344887)
-#define FIX_0_720959822  FIX(0.720959822)
-#define FIX_0_765366865  FIX(0.765366865)
-#define FIX_0_850430095  FIX(0.850430095)
-#define FIX_0_899976223  FIX(0.899976223)
-#define FIX_1_061594337  FIX(1.061594337)
-#define FIX_1_272758580  FIX(1.272758580)
-#define FIX_1_451774981  FIX(1.451774981)
-#define FIX_1_847759065  FIX(1.847759065)
-#define FIX_2_172734803  FIX(2.172734803)
-#define FIX_2_562915447  FIX(2.562915447)
-#define FIX_3_624509785  FIX(3.624509785)
-#endif
-
-
-/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
- * For 8-bit samples with the recommended scaling, all the variable
- * and constant values involved are no more than 16 bits wide, so a
- * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
- * For 12-bit samples, a full 32-bit multiplication will be needed.
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define MULTIPLY(var,const)  MULTIPLY16C16(var,const)
-#else
-#define MULTIPLY(var,const)  ((var) * (const))
-#endif
-
-
-/* Dequantize a coefficient by multiplying it by the multiplier-table
- * entry; produce an int result.  In this module, both inputs and result
- * are 16 bits or less, so either int or short multiply will work.
- */
-
-#define DEQUANTIZE(coef,quantval)  (((ISLOW_MULT_TYPE) (coef)) * (quantval))
-
-
-/*
- * Perform dequantization and inverse DCT on one block of coefficients,
- * producing a reduced-size 4x4 output block.
- */
-
-GLOBAL(void)
-jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	       JCOEFPTR coef_block,
-	       JSAMPARRAY output_buf, JDIMENSION output_col)
-{
-  INT32 tmp0, tmp2, tmp10, tmp12;
-  INT32 z1, z2, z3, z4;
-  JCOEFPTR inptr;
-  ISLOW_MULT_TYPE * quantptr;
-  int * wsptr;
-  JSAMPROW outptr;
-  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
-  int ctr;
-  int workspace[DCTSIZE*4];	/* buffers data between passes */
-  SHIFT_TEMPS
-
-  /* Pass 1: process columns from input, store into work array. */
-
-  inptr = coef_block;
-  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
-  wsptr = workspace;
-  for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
-    /* Don't bother to process column 4, because second pass won't use it */
-    if (ctr == DCTSIZE-4)
-      continue;
-    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
-	inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
-	inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
-      /* AC terms all zero; we need not examine term 4 for 4x4 output */
-      int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
-      
-      wsptr[DCTSIZE*0] = dcval;
-      wsptr[DCTSIZE*1] = dcval;
-      wsptr[DCTSIZE*2] = dcval;
-      wsptr[DCTSIZE*3] = dcval;
-      
-      continue;
-    }
-    
-    /* Even part */
-    
-    tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
-    tmp0 <<= (CONST_BITS+1);
-    
-    z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
-    z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
-
-    tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
-    
-    tmp10 = tmp0 + tmp2;
-    tmp12 = tmp0 - tmp2;
-    
-    /* Odd part */
-    
-    z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
-    z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
-    z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
-    z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
-    
-    tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
-	 + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
-	 + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
-	 + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
-    
-    tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
-	 + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
-	 + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
-	 + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
-
-    /* Final output stage */
-    
-    wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
-    wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
-    wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
-    wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
-  }
-  
-  /* Pass 2: process 4 rows from work array, store into output array. */
-
-  wsptr = workspace;
-  for (ctr = 0; ctr < 4; ctr++) {
-    outptr = output_buf[ctr] + output_col;
-    /* It's not clear whether a zero row test is worthwhile here ... */
-
-#ifndef NO_ZERO_ROW_TEST
-    if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
-	wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
-      /* AC terms all zero */
-      JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
-				  & RANGE_MASK];
-      
-      outptr[0] = dcval;
-      outptr[1] = dcval;
-      outptr[2] = dcval;
-      outptr[3] = dcval;
-      
-      wsptr += DCTSIZE;		/* advance pointer to next row */
-      continue;
-    }
-#endif
-    
-    /* Even part */
-    
-    tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
-    
-    tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
-	 + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
-    
-    tmp10 = tmp0 + tmp2;
-    tmp12 = tmp0 - tmp2;
-    
-    /* Odd part */
-    
-    z1 = (INT32) wsptr[7];
-    z2 = (INT32) wsptr[5];
-    z3 = (INT32) wsptr[3];
-    z4 = (INT32) wsptr[1];
-    
-    tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
-	 + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
-	 + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
-	 + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
-    
-    tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
-	 + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
-	 + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
-	 + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
-
-    /* Final output stage */
-    
-    outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
-					  CONST_BITS+PASS1_BITS+3+1)
-			    & RANGE_MASK];
-    outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
-					  CONST_BITS+PASS1_BITS+3+1)
-			    & RANGE_MASK];
-    outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
-					  CONST_BITS+PASS1_BITS+3+1)
-			    & RANGE_MASK];
-    outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
-					  CONST_BITS+PASS1_BITS+3+1)
-			    & RANGE_MASK];
-    
-    wsptr += DCTSIZE;		/* advance pointer to next row */
-  }
-}
-
-
-/*
- * Perform dequantization and inverse DCT on one block of coefficients,
- * producing a reduced-size 2x2 output block.
- */
-
-GLOBAL(void)
-jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	       JCOEFPTR coef_block,
-	       JSAMPARRAY output_buf, JDIMENSION output_col)
-{
-  INT32 tmp0, tmp10, z1;
-  JCOEFPTR inptr;
-  ISLOW_MULT_TYPE * quantptr;
-  int * wsptr;
-  JSAMPROW outptr;
-  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
-  int ctr;
-  int workspace[DCTSIZE*2];	/* buffers data between passes */
-  SHIFT_TEMPS
-
-  /* Pass 1: process columns from input, store into work array. */
-
-  inptr = coef_block;
-  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
-  wsptr = workspace;
-  for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
-    /* Don't bother to process columns 2,4,6 */
-    if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
-      continue;
-    if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
-	inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
-      /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
-      int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
-      
-      wsptr[DCTSIZE*0] = dcval;
-      wsptr[DCTSIZE*1] = dcval;
-      
-      continue;
-    }
-    
-    /* Even part */
-    
-    z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
-    tmp10 = z1 << (CONST_BITS+2);
-    
-    /* Odd part */
-
-    z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
-    tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
-    z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
-    tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
-    z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
-    tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
-    z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
-    tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
-
-    /* Final output stage */
-    
-    wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
-    wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
-  }
-  
-  /* Pass 2: process 2 rows from work array, store into output array. */
-
-  wsptr = workspace;
-  for (ctr = 0; ctr < 2; ctr++) {
-    outptr = output_buf[ctr] + output_col;
-    /* It's not clear whether a zero row test is worthwhile here ... */
-
-#ifndef NO_ZERO_ROW_TEST
-    if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
-      /* AC terms all zero */
-      JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
-				  & RANGE_MASK];
-      
-      outptr[0] = dcval;
-      outptr[1] = dcval;
-      
-      wsptr += DCTSIZE;		/* advance pointer to next row */
-      continue;
-    }
-#endif
-    
-    /* Even part */
-    
-    tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
-    
-    /* Odd part */
-
-    tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
-	 + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
-	 + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
-	 + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
-
-    /* Final output stage */
-    
-    outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
-					  CONST_BITS+PASS1_BITS+3+2)
-			    & RANGE_MASK];
-    outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
-					  CONST_BITS+PASS1_BITS+3+2)
-			    & RANGE_MASK];
-    
-    wsptr += DCTSIZE;		/* advance pointer to next row */
-  }
-}
-
-
-/*
- * Perform dequantization and inverse DCT on one block of coefficients,
- * producing a reduced-size 1x1 output block.
- */
-
-GLOBAL(void)
-jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
-	       JCOEFPTR coef_block,
-	       JSAMPARRAY output_buf, JDIMENSION output_col)
-{
-  int dcval;
-  ISLOW_MULT_TYPE * quantptr;
-  JSAMPLE *range_limit = IDCT_range_limit(cinfo);
-  SHIFT_TEMPS
-
-  /* We hardly need an inverse DCT routine for this: just take the
-   * average pixel value, which is one-eighth of the DC coefficient.
-   */
-  quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
-  dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
-  dcval = (int) DESCALE((INT32) dcval, 3);
-
-  output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
-}
-
-#endif /* IDCT_SCALING_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jinclude.h ./Shared/jpeg-6b/jinclude.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jinclude.h	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jinclude.h	Wed Dec 31 19:00:00 1969
@@ -1,91 +0,0 @@
-/*
- * jinclude.h
- *
- * Copyright (C) 1991-1994, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file exists to provide a single place to fix any problems with
- * including the wrong system include files.  (Common problems are taken
- * care of by the standard jconfig symbols, but on really weird systems
- * you may have to edit this file.)
- *
- * NOTE: this file is NOT intended to be included by applications using the
- * JPEG library.  Most applications need only include jpeglib.h.
- */
-
-
-/* Include auto-config file to find out which system include files we need. */
-
-#include "jconfig.h"		/* auto configuration options */
-#define JCONFIG_INCLUDED	/* so that jpeglib.h doesn't do it again */
-
-/*
- * We need the NULL macro and size_t typedef.
- * On an ANSI-conforming system it is sufficient to include <stddef.h>.
- * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
- * pull in <sys/types.h> as well.
- * Note that the core JPEG library does not require <stdio.h>;
- * only the default error handler and data source/destination modules do.
- * But we must pull it in because of the references to FILE in jpeglib.h.
- * You can remove those references if you want to compile without <stdio.h>.
- */
-
-#ifdef HAVE_STDDEF_H
-#include <stddef.h>
-#endif
-
-#ifdef HAVE_STDLIB_H
-#include <stdlib.h>
-#endif
-
-#ifdef NEED_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-
-#include <stdio.h>
-
-/*
- * We need memory copying and zeroing functions, plus strncpy().
- * ANSI and System V implementations declare these in <string.h>.
- * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
- * Some systems may declare memset and memcpy in <memory.h>.
- *
- * NOTE: we assume the size parameters to these functions are of type size_t.
- * Change the casts in these macros if not!
- */
-
-#ifdef NEED_BSD_STRINGS
-
-#include <strings.h>
-#define MEMZERO(target,size)	bzero((void *)(target), (size_t)(size))
-#define MEMCOPY(dest,src,size)	bcopy((const void *)(src), (void *)(dest), (size_t)(size))
-
-#else /* not BSD, assume ANSI/SysV string lib */
-
-#include <string.h>
-#define MEMZERO(target,size)	memset((void *)(target), 0, (size_t)(size))
-#define MEMCOPY(dest,src,size)	memcpy((void *)(dest), (const void *)(src), (size_t)(size))
-
-#endif
-
-/*
- * In ANSI C, and indeed any rational implementation, size_t is also the
- * type returned by sizeof().  However, it seems there are some irrational
- * implementations out there, in which sizeof() returns an int even though
- * size_t is defined as long or unsigned long.  To ensure consistent results
- * we always use this SIZEOF() macro in place of using sizeof() directly.
- */
-
-#define SIZEOF(object)	((size_t) sizeof(object))
-
-/*
- * The modules that use fread() and fwrite() always invoke them through
- * these macros.  On some systems you may need to twiddle the argument casts.
- * CAUTION: argument order is different from underlying functions!
- */
-
-#define JFREAD(file,buf,sizeofbuf)  \
-  ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
-#define JFWRITE(file,buf,sizeofbuf)  \
-  ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemansi.c ./Shared/jpeg-6b/jmemansi.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemansi.c	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemansi.c	Wed Dec 31 19:00:00 1969
@@ -1,167 +0,0 @@
-/*
- * jmemansi.c
- *
- * Copyright (C) 1992-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file provides a simple generic implementation of the system-
- * dependent portion of the JPEG memory manager.  This implementation
- * assumes that you have the ANSI-standard library routine tmpfile().
- * Also, the problem of determining the amount of memory available
- * is shoved onto the user.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jmemsys.h"		/* import the system-dependent declarations */
-
-#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare malloc(),free() */
-extern void * malloc JPP((size_t size));
-extern void free JPP((void *ptr));
-#endif
-
-#ifndef SEEK_SET		/* pre-ANSI systems may not define this; */
-#define SEEK_SET  0		/* if not, assume 0 is correct */
-#endif
-
-
-/*
- * Memory allocation and freeing are controlled by the regular library
- * routines malloc() and free().
- */
-
-GLOBAL(void *)
-jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void *) malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
-{
-  free(object);
-}
-
-
-/*
- * "Large" objects are treated the same as "small" ones.
- * NB: although we include FAR keywords in the routine declarations,
- * this file won't actually work in 80x86 small/medium model; at least,
- * you probably won't be able to process useful-size images in only 64KB.
- */
-
-GLOBAL(void FAR *)
-jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void FAR *) malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
-{
-  free(object);
-}
-
-
-/*
- * This routine computes the total memory space available for allocation.
- * It's impossible to do this in a portable way; our current solution is
- * to make the user tell us (with a default value set at compile time).
- * If you can actually get the available space, it's a good idea to subtract
- * a slop factor of 5% or so.
- */
-
-#ifndef DEFAULT_MAX_MEM		/* so can override from makefile */
-#define DEFAULT_MAX_MEM		1000000L /* default: one megabyte */
-#endif
-
-GLOBAL(long)
-jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
-		    long max_bytes_needed, long already_allocated)
-{
-  return cinfo->mem->max_memory_to_use - already_allocated;
-}
-
-
-/*
- * Backing store (temporary file) management.
- * Backing store objects are only used when the value returned by
- * jpeg_mem_available is less than the total space needed.  You can dispense
- * with these routines if you have plenty of virtual memory; see jmemnobs.c.
- */
-
-
-METHODDEF(void)
-read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-		    void FAR * buffer_address,
-		    long file_offset, long byte_count)
-{
-  if (fseek(info->temp_file, file_offset, SEEK_SET))
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-  if (JFREAD(info->temp_file, buffer_address, byte_count)
-      != (size_t) byte_count)
-    ERREXIT(cinfo, JERR_TFILE_READ);
-}
-
-
-METHODDEF(void)
-write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-		     void FAR * buffer_address,
-		     long file_offset, long byte_count)
-{
-  if (fseek(info->temp_file, file_offset, SEEK_SET))
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-  if (JFWRITE(info->temp_file, buffer_address, byte_count)
-      != (size_t) byte_count)
-    ERREXIT(cinfo, JERR_TFILE_WRITE);
-}
-
-
-METHODDEF(void)
-close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
-{
-  fclose(info->temp_file);
-  /* Since this implementation uses tmpfile() to create the file,
-   * no explicit file deletion is needed.
-   */
-}
-
-
-/*
- * Initial opening of a backing-store object.
- *
- * This version uses tmpfile(), which constructs a suitable file name
- * behind the scenes.  We don't have to use info->temp_name[] at all;
- * indeed, we can't even find out the actual name of the temp file.
- */
-
-GLOBAL(void)
-jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-			 long total_bytes_needed)
-{
-  if ((info->temp_file = tmpfile()) == NULL)
-    ERREXITS(cinfo, JERR_TFILE_CREATE, "");
-  info->read_backing_store = read_backing_store;
-  info->write_backing_store = write_backing_store;
-  info->close_backing_store = close_backing_store;
-}
-
-
-/*
- * These routines take care of any system-dependent initialization and
- * cleanup required.
- */
-
-GLOBAL(long)
-jpeg_mem_init (j_common_ptr cinfo)
-{
-  return DEFAULT_MAX_MEM;	/* default for max_memory_to_use */
-}
-
-GLOBAL(void)
-jpeg_mem_term (j_common_ptr cinfo)
-{
-  /* no work */
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemdos.c ./Shared/jpeg-6b/jmemdos.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemdos.c	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemdos.c	Wed Dec 31 19:00:00 1969
@@ -1,638 +0,0 @@
-/*
- * jmemdos.c
- *
- * Copyright (C) 1992-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file provides an MS-DOS-compatible implementation of the system-
- * dependent portion of the JPEG memory manager.  Temporary data can be
- * stored in extended or expanded memory as well as in regular DOS files.
- *
- * If you use this file, you must be sure that NEED_FAR_POINTERS is defined
- * if you compile in a small-data memory model; it should NOT be defined if
- * you use a large-data memory model.  This file is not recommended if you
- * are using a flat-memory-space 386 environment such as DJGCC or Watcom C.
- * Also, this code will NOT work if struct fields are aligned on greater than
- * 2-byte boundaries.
- *
- * Based on code contributed by Ge' Weijers.
- */
-
-/*
- * If you have both extended and expanded memory, you may want to change the
- * order in which they are tried in jopen_backing_store.  On a 286 machine
- * expanded memory is usually faster, since extended memory access involves
- * an expensive protected-mode-and-back switch.  On 386 and better, extended
- * memory is usually faster.  As distributed, the code tries extended memory
- * first (what? not everyone has a 386? :-).
- *
- * You can disable use of extended/expanded memory entirely by altering these
- * definitions or overriding them from the Makefile (eg, -DEMS_SUPPORTED=0).
- */
-
-#ifndef XMS_SUPPORTED
-#define XMS_SUPPORTED  1
-#endif
-#ifndef EMS_SUPPORTED
-#define EMS_SUPPORTED  1
-#endif
-
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jmemsys.h"		/* import the system-dependent declarations */
-
-#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare these */
-extern void * malloc JPP((size_t size));
-extern void free JPP((void *ptr));
-extern char * getenv JPP((const char * name));
-#endif
-
-#ifdef NEED_FAR_POINTERS
-
-#ifdef __TURBOC__
-/* These definitions work for Borland C (Turbo C) */
-#include <alloc.h>		/* need farmalloc(), farfree() */
-#define far_malloc(x)	farmalloc(x)
-#define far_free(x)	farfree(x)
-#else
-/* These definitions work for Microsoft C and compatible compilers */
-#include <malloc.h>		/* need _fmalloc(), _ffree() */
-#define far_malloc(x)	_fmalloc(x)
-#define far_free(x)	_ffree(x)
-#endif
-
-#else /* not NEED_FAR_POINTERS */
-
-#define far_malloc(x)	malloc(x)
-#define far_free(x)	free(x)
-
-#endif /* NEED_FAR_POINTERS */
-
-#ifdef DONT_USE_B_MODE		/* define mode parameters for fopen() */
-#define READ_BINARY	"r"
-#else
-#define READ_BINARY	"rb"
-#endif
-
-#ifndef USE_MSDOS_MEMMGR	/* make sure user got configuration right */
-  You forgot to define USE_MSDOS_MEMMGR in jconfig.h. /* deliberate syntax error */
-#endif
-
-#if MAX_ALLOC_CHUNK >= 65535L	/* make sure jconfig.h got this right */
-  MAX_ALLOC_CHUNK should be less than 64K. /* deliberate syntax error */
-#endif
-
-
-/*
- * Declarations for assembly-language support routines (see jmemdosa.asm).
- *
- * The functions are declared "far" as are all their pointer arguments;
- * this ensures the assembly source code will work regardless of the
- * compiler memory model.  We assume "short" is 16 bits, "long" is 32.
- */
-
-typedef void far * XMSDRIVER;	/* actually a pointer to code */
-typedef struct {		/* registers for calling XMS driver */
-	unsigned short ax, dx, bx;
-	void far * ds_si;
-      } XMScontext;
-typedef struct {		/* registers for calling EMS driver */
-	unsigned short ax, dx, bx;
-	void far * ds_si;
-      } EMScontext;
-
-extern short far jdos_open JPP((short far * handle, char far * filename));
-extern short far jdos_close JPP((short handle));
-extern short far jdos_seek JPP((short handle, long offset));
-extern short far jdos_read JPP((short handle, void far * buffer,
-				unsigned short count));
-extern short far jdos_write JPP((short handle, void far * buffer,
-				 unsigned short count));
-extern void far jxms_getdriver JPP((XMSDRIVER far *));
-extern void far jxms_calldriver JPP((XMSDRIVER, XMScontext far *));
-extern short far jems_available JPP((void));
-extern void far jems_calldriver JPP((EMScontext far *));
-
-
-/*
- * Selection of a file name for a temporary file.
- * This is highly system-dependent, and you may want to customize it.
- */
-
-static int next_file_num;	/* to distinguish among several temp files */
-
-LOCAL(void)
-select_file_name (char * fname)
-{
-  const char * env;
-  char * ptr;
-  FILE * tfile;
-
-  /* Keep generating file names till we find one that's not in use */
-  for (;;) {
-    /* Get temp directory name from environment TMP or TEMP variable;
-     * if none, use "."
-     */
-    if ((env = (const char *) getenv("TMP")) == NULL)
-      if ((env = (const char *) getenv("TEMP")) == NULL)
-	env = ".";
-    if (*env == '\0')		/* null string means "." */
-      env = ".";
-    ptr = fname;		/* copy name to fname */
-    while (*env != '\0')
-      *ptr++ = *env++;
-    if (ptr[-1] != '\\' && ptr[-1] != '/')
-      *ptr++ = '\\';		/* append backslash if not in env variable */
-    /* Append a suitable file name */
-    next_file_num++;		/* advance counter */
-    sprintf(ptr, "JPG%03d.TMP", next_file_num);
-    /* Probe to see if file name is already in use */
-    if ((tfile = fopen(fname, READ_BINARY)) == NULL)
-      break;
-    fclose(tfile);		/* oops, it's there; close tfile & try again */
-  }
-}
-
-
-/*
- * Near-memory allocation and freeing are controlled by the regular library
- * routines malloc() and free().
- */
-
-GLOBAL(void *)
-jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void *) malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
-{
-  free(object);
-}
-
-
-/*
- * "Large" objects are allocated in far memory, if possible
- */
-
-GLOBAL(void FAR *)
-jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void FAR *) far_malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
-{
-  far_free(object);
-}
-
-
-/*
- * This routine computes the total memory space available for allocation.
- * It's impossible to do this in a portable way; our current solution is
- * to make the user tell us (with a default value set at compile time).
- * If you can actually get the available space, it's a good idea to subtract
- * a slop factor of 5% or so.
- */
-
-#ifndef DEFAULT_MAX_MEM		/* so can override from makefile */
-#define DEFAULT_MAX_MEM		300000L /* for total usage about 450K */
-#endif
-
-GLOBAL(long)
-jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
-		    long max_bytes_needed, long already_allocated)
-{
-  return cinfo->mem->max_memory_to_use - already_allocated;
-}
-
-
-/*
- * Backing store (temporary file) management.
- * Backing store objects are only used when the value returned by
- * jpeg_mem_available is less than the total space needed.  You can dispense
- * with these routines if you have plenty of virtual memory; see jmemnobs.c.
- */
-
-/*
- * For MS-DOS we support three types of backing storage:
- *   1. Conventional DOS files.  We access these by direct DOS calls rather
- *      than via the stdio package.  This provides a bit better performance,
- *      but the real reason is that the buffers to be read or written are FAR.
- *      The stdio library for small-data memory models can't cope with that.
- *   2. Extended memory, accessed per the XMS V2.0 specification.
- *   3. Expanded memory, accessed per the LIM/EMS 4.0 specification.
- * You'll need copies of those specs to make sense of the related code.
- * The specs are available by Internet FTP from the SIMTEL archives 
- * (oak.oakland.edu and its various mirror sites).  See files
- * pub/msdos/microsoft/xms20.arc and pub/msdos/info/limems41.zip.
- */
-
-
-/*
- * Access methods for a DOS file.
- */
-
-
-METHODDEF(void)
-read_file_store (j_common_ptr cinfo, backing_store_ptr info,
-		 void FAR * buffer_address,
-		 long file_offset, long byte_count)
-{
-  if (jdos_seek(info->handle.file_handle, file_offset))
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-  /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */
-  if (byte_count > 65535L)	/* safety check */
-    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
-  if (jdos_read(info->handle.file_handle, buffer_address,
-		(unsigned short) byte_count))
-    ERREXIT(cinfo, JERR_TFILE_READ);
-}
-
-
-METHODDEF(void)
-write_file_store (j_common_ptr cinfo, backing_store_ptr info,
-		  void FAR * buffer_address,
-		  long file_offset, long byte_count)
-{
-  if (jdos_seek(info->handle.file_handle, file_offset))
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-  /* Since MAX_ALLOC_CHUNK is less than 64K, byte_count will be too. */
-  if (byte_count > 65535L)	/* safety check */
-    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
-  if (jdos_write(info->handle.file_handle, buffer_address,
-		 (unsigned short) byte_count))
-    ERREXIT(cinfo, JERR_TFILE_WRITE);
-}
-
-
-METHODDEF(void)
-close_file_store (j_common_ptr cinfo, backing_store_ptr info)
-{
-  jdos_close(info->handle.file_handle);	/* close the file */
-  remove(info->temp_name);	/* delete the file */
-/* If your system doesn't have remove(), try unlink() instead.
- * remove() is the ANSI-standard name for this function, but
- * unlink() was more common in pre-ANSI systems.
- */
-  TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name);
-}
-
-
-LOCAL(boolean)
-open_file_store (j_common_ptr cinfo, backing_store_ptr info,
-		 long total_bytes_needed)
-{
-  short handle;
-
-  select_file_name(info->temp_name);
-  if (jdos_open((short far *) & handle, (char far *) info->temp_name)) {
-    /* might as well exit since jpeg_open_backing_store will fail anyway */
-    ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
-    return FALSE;
-  }
-  info->handle.file_handle = handle;
-  info->read_backing_store = read_file_store;
-  info->write_backing_store = write_file_store;
-  info->close_backing_store = close_file_store;
-  TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
-  return TRUE;			/* succeeded */
-}
-
-
-/*
- * Access methods for extended memory.
- */
-
-#if XMS_SUPPORTED
-
-static XMSDRIVER xms_driver;	/* saved address of XMS driver */
-
-typedef union {			/* either long offset or real-mode pointer */
-	long offset;
-	void far * ptr;
-      } XMSPTR;
-
-typedef struct {		/* XMS move specification structure */
-	long length;
-	XMSH src_handle;
-	XMSPTR src;
-	XMSH dst_handle;
-	XMSPTR dst;
-      } XMSspec;
-
-#define ODD(X)	(((X) & 1L) != 0)
-
-
-METHODDEF(void)
-read_xms_store (j_common_ptr cinfo, backing_store_ptr info,
-		void FAR * buffer_address,
-		long file_offset, long byte_count)
-{
-  XMScontext ctx;
-  XMSspec spec;
-  char endbuffer[2];
-
-  /* The XMS driver can't cope with an odd length, so handle the last byte
-   * specially if byte_count is odd.  We don't expect this to be common.
-   */
-
-  spec.length = byte_count & (~ 1L);
-  spec.src_handle = info->handle.xms_handle;
-  spec.src.offset = file_offset;
-  spec.dst_handle = 0;
-  spec.dst.ptr = buffer_address;
-  
-  ctx.ds_si = (void far *) & spec;
-  ctx.ax = 0x0b00;		/* EMB move */
-  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
-  if (ctx.ax != 1)
-    ERREXIT(cinfo, JERR_XMS_READ);
-
-  if (ODD(byte_count)) {
-    read_xms_store(cinfo, info, (void FAR *) endbuffer,
-		   file_offset + byte_count - 1L, 2L);
-    ((char FAR *) buffer_address)[byte_count - 1L] = endbuffer[0];
-  }
-}
-
-
-METHODDEF(void)
-write_xms_store (j_common_ptr cinfo, backing_store_ptr info,
-		 void FAR * buffer_address,
-		 long file_offset, long byte_count)
-{
-  XMScontext ctx;
-  XMSspec spec;
-  char endbuffer[2];
-
-  /* The XMS driver can't cope with an odd length, so handle the last byte
-   * specially if byte_count is odd.  We don't expect this to be common.
-   */
-
-  spec.length = byte_count & (~ 1L);
-  spec.src_handle = 0;
-  spec.src.ptr = buffer_address;
-  spec.dst_handle = info->handle.xms_handle;
-  spec.dst.offset = file_offset;
-
-  ctx.ds_si = (void far *) & spec;
-  ctx.ax = 0x0b00;		/* EMB move */
-  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
-  if (ctx.ax != 1)
-    ERREXIT(cinfo, JERR_XMS_WRITE);
-
-  if (ODD(byte_count)) {
-    read_xms_store(cinfo, info, (void FAR *) endbuffer,
-		   file_offset + byte_count - 1L, 2L);
-    endbuffer[0] = ((char FAR *) buffer_address)[byte_count - 1L];
-    write_xms_store(cinfo, info, (void FAR *) endbuffer,
-		    file_offset + byte_count - 1L, 2L);
-  }
-}
-
-
-METHODDEF(void)
-close_xms_store (j_common_ptr cinfo, backing_store_ptr info)
-{
-  XMScontext ctx;
-
-  ctx.dx = info->handle.xms_handle;
-  ctx.ax = 0x0a00;
-  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
-  TRACEMS1(cinfo, 1, JTRC_XMS_CLOSE, info->handle.xms_handle);
-  /* we ignore any error return from the driver */
-}
-
-
-LOCAL(boolean)
-open_xms_store (j_common_ptr cinfo, backing_store_ptr info,
-		long total_bytes_needed)
-{
-  XMScontext ctx;
-
-  /* Get address of XMS driver */
-  jxms_getdriver((XMSDRIVER far *) & xms_driver);
-  if (xms_driver == NULL)
-    return FALSE;		/* no driver to be had */
-
-  /* Get version number, must be >= 2.00 */
-  ctx.ax = 0x0000;
-  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
-  if (ctx.ax < (unsigned short) 0x0200)
-    return FALSE;
-
-  /* Try to get space (expressed in kilobytes) */
-  ctx.dx = (unsigned short) ((total_bytes_needed + 1023L) >> 10);
-  ctx.ax = 0x0900;
-  jxms_calldriver(xms_driver, (XMScontext far *) & ctx);
-  if (ctx.ax != 1)
-    return FALSE;
-
-  /* Succeeded, save the handle and away we go */
-  info->handle.xms_handle = ctx.dx;
-  info->read_backing_store = read_xms_store;
-  info->write_backing_store = write_xms_store;
-  info->close_backing_store = close_xms_store;
-  TRACEMS1(cinfo, 1, JTRC_XMS_OPEN, ctx.dx);
-  return TRUE;			/* succeeded */
-}
-
-#endif /* XMS_SUPPORTED */
-
-
-/*
- * Access methods for expanded memory.
- */
-
-#if EMS_SUPPORTED
-
-/* The EMS move specification structure requires word and long fields aligned
- * at odd byte boundaries.  Some compilers will align struct fields at even
- * byte boundaries.  While it's usually possible to force byte alignment,
- * that causes an overall performance penalty and may pose problems in merging
- * JPEG into a larger application.  Instead we accept some rather dirty code
- * here.  Note this code would fail if the hardware did not allow odd-byte
- * word & long accesses, but all 80x86 CPUs do.
- */
-
-typedef void far * EMSPTR;
-
-typedef union {			/* EMS move specification structure */
-	long length;		/* It's easy to access first 4 bytes */
-	char bytes[18];		/* Misaligned fields in here! */
-      } EMSspec;
-
-/* Macros for accessing misaligned fields */
-#define FIELD_AT(spec,offset,type)  (*((type *) &(spec.bytes[offset])))
-#define SRC_TYPE(spec)		FIELD_AT(spec,4,char)
-#define SRC_HANDLE(spec)	FIELD_AT(spec,5,EMSH)
-#define SRC_OFFSET(spec)	FIELD_AT(spec,7,unsigned short)
-#define SRC_PAGE(spec)		FIELD_AT(spec,9,unsigned short)
-#define SRC_PTR(spec)		FIELD_AT(spec,7,EMSPTR)
-#define DST_TYPE(spec)		FIELD_AT(spec,11,char)
-#define DST_HANDLE(spec)	FIELD_AT(spec,12,EMSH)
-#define DST_OFFSET(spec)	FIELD_AT(spec,14,unsigned short)
-#define DST_PAGE(spec)		FIELD_AT(spec,16,unsigned short)
-#define DST_PTR(spec)		FIELD_AT(spec,14,EMSPTR)
-
-#define EMSPAGESIZE	16384L	/* gospel, see the EMS specs */
-
-#define HIBYTE(W)  (((W) >> 8) & 0xFF)
-#define LOBYTE(W)  ((W) & 0xFF)
-
-
-METHODDEF(void)
-read_ems_store (j_common_ptr cinfo, backing_store_ptr info,
-		void FAR * buffer_address,
-		long file_offset, long byte_count)
-{
-  EMScontext ctx;
-  EMSspec spec;
-
-  spec.length = byte_count;
-  SRC_TYPE(spec) = 1;
-  SRC_HANDLE(spec) = info->handle.ems_handle;
-  SRC_PAGE(spec)   = (unsigned short) (file_offset / EMSPAGESIZE);
-  SRC_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE);
-  DST_TYPE(spec) = 0;
-  DST_HANDLE(spec) = 0;
-  DST_PTR(spec)    = buffer_address;
-  
-  ctx.ds_si = (void far *) & spec;
-  ctx.ax = 0x5700;		/* move memory region */
-  jems_calldriver((EMScontext far *) & ctx);
-  if (HIBYTE(ctx.ax) != 0)
-    ERREXIT(cinfo, JERR_EMS_READ);
-}
-
-
-METHODDEF(void)
-write_ems_store (j_common_ptr cinfo, backing_store_ptr info,
-		 void FAR * buffer_address,
-		 long file_offset, long byte_count)
-{
-  EMScontext ctx;
-  EMSspec spec;
-
-  spec.length = byte_count;
-  SRC_TYPE(spec) = 0;
-  SRC_HANDLE(spec) = 0;
-  SRC_PTR(spec)    = buffer_address;
-  DST_TYPE(spec) = 1;
-  DST_HANDLE(spec) = info->handle.ems_handle;
-  DST_PAGE(spec)   = (unsigned short) (file_offset / EMSPAGESIZE);
-  DST_OFFSET(spec) = (unsigned short) (file_offset % EMSPAGESIZE);
-  
-  ctx.ds_si = (void far *) & spec;
-  ctx.ax = 0x5700;		/* move memory region */
-  jems_calldriver((EMScontext far *) & ctx);
-  if (HIBYTE(ctx.ax) != 0)
-    ERREXIT(cinfo, JERR_EMS_WRITE);
-}
-
-
-METHODDEF(void)
-close_ems_store (j_common_ptr cinfo, backing_store_ptr info)
-{
-  EMScontext ctx;
-
-  ctx.ax = 0x4500;
-  ctx.dx = info->handle.ems_handle;
-  jems_calldriver((EMScontext far *) & ctx);
-  TRACEMS1(cinfo, 1, JTRC_EMS_CLOSE, info->handle.ems_handle);
-  /* we ignore any error return from the driver */
-}
-
-
-LOCAL(boolean)
-open_ems_store (j_common_ptr cinfo, backing_store_ptr info,
-		long total_bytes_needed)
-{
-  EMScontext ctx;
-
-  /* Is EMS driver there? */
-  if (! jems_available())
-    return FALSE;
-
-  /* Get status, make sure EMS is OK */
-  ctx.ax = 0x4000;
-  jems_calldriver((EMScontext far *) & ctx);
-  if (HIBYTE(ctx.ax) != 0)
-    return FALSE;
-
-  /* Get version, must be >= 4.0 */
-  ctx.ax = 0x4600;
-  jems_calldriver((EMScontext far *) & ctx);
-  if (HIBYTE(ctx.ax) != 0 || LOBYTE(ctx.ax) < 0x40)
-    return FALSE;
-
-  /* Try to allocate requested space */
-  ctx.ax = 0x4300;
-  ctx.bx = (unsigned short) ((total_bytes_needed + EMSPAGESIZE-1L) / EMSPAGESIZE);
-  jems_calldriver((EMScontext far *) & ctx);
-  if (HIBYTE(ctx.ax) != 0)
-    return FALSE;
-
-  /* Succeeded, save the handle and away we go */
-  info->handle.ems_handle = ctx.dx;
-  info->read_backing_store = read_ems_store;
-  info->write_backing_store = write_ems_store;
-  info->close_backing_store = close_ems_store;
-  TRACEMS1(cinfo, 1, JTRC_EMS_OPEN, ctx.dx);
-  return TRUE;			/* succeeded */
-}
-
-#endif /* EMS_SUPPORTED */
-
-
-/*
- * Initial opening of a backing-store object.
- */
-
-GLOBAL(void)
-jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-			 long total_bytes_needed)
-{
-  /* Try extended memory, then expanded memory, then regular file. */
-#if XMS_SUPPORTED
-  if (open_xms_store(cinfo, info, total_bytes_needed))
-    return;
-#endif
-#if EMS_SUPPORTED
-  if (open_ems_store(cinfo, info, total_bytes_needed))
-    return;
-#endif
-  if (open_file_store(cinfo, info, total_bytes_needed))
-    return;
-  ERREXITS(cinfo, JERR_TFILE_CREATE, "");
-}
-
-
-/*
- * These routines take care of any system-dependent initialization and
- * cleanup required.
- */
-
-GLOBAL(long)
-jpeg_mem_init (j_common_ptr cinfo)
-{
-  next_file_num = 0;		/* initialize temp file name generator */
-  return DEFAULT_MAX_MEM;	/* default for max_memory_to_use */
-}
-
-GLOBAL(void)
-jpeg_mem_term (j_common_ptr cinfo)
-{
-  /* Microsoft C, at least in v6.00A, will not successfully reclaim freed
-   * blocks of size > 32Kbytes unless we give it a kick in the rear, like so:
-   */
-#ifdef NEED_FHEAPMIN
-  _fheapmin();
-#endif
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemdosa.asm ./Shared/jpeg-6b/jmemdosa.asm
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemdosa.asm	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemdosa.asm	Wed Dec 31 19:00:00 1969
@@ -1,379 +0,0 @@
-;
-; jmemdosa.asm
-;
-; Copyright (C) 1992, Thomas G. Lane.
-; This file is part of the Independent JPEG Group's software.
-; For conditions of distribution and use, see the accompanying README file.
-;
-; This file contains low-level interface routines to support the MS-DOS
-; backing store manager (jmemdos.c).  Routines are provided to access disk
-; files through direct DOS calls, and to access XMS and EMS drivers.
-;
-; This file should assemble with Microsoft's MASM or any compatible
-; assembler (including Borland's Turbo Assembler).  If you haven't got
-; a compatible assembler, better fall back to jmemansi.c or jmemname.c.
-;
-; To minimize dependence on the C compiler's register usage conventions,
-; we save and restore all 8086 registers, even though most compilers only
-; require SI,DI,DS to be preserved.  Also, we use only 16-bit-wide return
-; values, which everybody returns in AX.
-;
-; Based on code contributed by Ge' Weijers.
-;
-
-JMEMDOSA_TXT	segment byte public 'CODE'
-
-		assume	cs:JMEMDOSA_TXT
-
-		public	_jdos_open
-		public	_jdos_close
-		public	_jdos_seek
-		public	_jdos_read
-		public	_jdos_write
-		public	_jxms_getdriver
-		public	_jxms_calldriver
-		public	_jems_available
-		public	_jems_calldriver
-
-;
-; short far jdos_open (short far * handle, char far * filename)
-;
-; Create and open a temporary file
-;
-_jdos_open	proc	far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		mov	cx,0			; normal file attributes
-		lds	dx,dword ptr [bp+10]	; get filename pointer
-		mov	ah,3ch			; create file
-		int	21h
-		jc	open_err		; if failed, return error code
-		lds	bx,dword ptr [bp+6]	; get handle pointer
-		mov	word ptr [bx],ax	; save the handle
-		xor	ax,ax			; return zero for OK
-open_err:	pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop 	bp
-		ret
-_jdos_open	endp
-
-
-;
-; short far jdos_close (short handle)
-;
-; Close the file handle
-;
-_jdos_close	proc	far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		mov	bx,word ptr [bp+6]	; file handle
-		mov	ah,3eh			; close file
-		int	21h
-		jc	close_err		; if failed, return error code
-		xor	ax,ax			; return zero for OK
-close_err:	pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop 	bp
-		ret
-_jdos_close	endp
-
-
-;
-; short far jdos_seek (short handle, long offset)
-;
-; Set file position
-;
-_jdos_seek	proc	far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		mov	bx,word ptr [bp+6]	; file handle
-		mov	dx,word ptr [bp+8]	; LS offset
-		mov	cx,word ptr [bp+10]	; MS offset
-		mov	ax,4200h		; absolute seek
-		int	21h
-		jc	seek_err		; if failed, return error code
-		xor	ax,ax			; return zero for OK
-seek_err:	pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop 	bp
-		ret
-_jdos_seek	endp
-
-
-;
-; short far jdos_read (short handle, void far * buffer, unsigned short count)
-;
-; Read from file
-;
-_jdos_read	proc	far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		mov	bx,word ptr [bp+6]	; file handle
-		lds	dx,dword ptr [bp+8]	; buffer address
-		mov	cx,word ptr [bp+12]	; number of bytes
-		mov	ah,3fh			; read file
-		int	21h
-		jc	read_err		; if failed, return error code
-		cmp	ax,word ptr [bp+12]	; make sure all bytes were read
-		je	read_ok
-		mov	ax,1			; else return 1 for not OK
-		jmp	short read_err
-read_ok:	xor	ax,ax			; return zero for OK
-read_err:	pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop 	bp
-		ret
-_jdos_read	endp
-
-
-;
-; short far jdos_write (short handle, void far * buffer, unsigned short count)
-;
-; Write to file
-;
-_jdos_write	proc	far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		mov	bx,word ptr [bp+6]	; file handle
-		lds	dx,dword ptr [bp+8]	; buffer address
-		mov	cx,word ptr [bp+12]	; number of bytes
-		mov	ah,40h			; write file
-		int	21h
-		jc	write_err		; if failed, return error code
-		cmp	ax,word ptr [bp+12]	; make sure all bytes written
-		je	write_ok
-		mov	ax,1			; else return 1 for not OK
-		jmp	short write_err
-write_ok:	xor	ax,ax			; return zero for OK
-write_err:	pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop 	bp
-		ret
-_jdos_write	endp
-
-
-;
-; void far jxms_getdriver (XMSDRIVER far *)
-;
-; Get the address of the XMS driver, or NULL if not available
-;
-_jxms_getdriver	proc	far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		mov 	ax,4300h		; call multiplex interrupt with
-		int	2fh			; a magic cookie, hex 4300
-		cmp 	al,80h			; AL should contain hex 80
-		je	xmsavail
-		xor 	dx,dx			; no XMS driver available
-		xor 	ax,ax			; return a nil pointer
-		jmp	short xmsavail_done
-xmsavail:	mov 	ax,4310h		; fetch driver address with
-		int	2fh			; another magic cookie
-		mov 	dx,es			; copy address to dx:ax
-		mov 	ax,bx
-xmsavail_done:	les 	bx,dword ptr [bp+6]	; get pointer to return value
-		mov	word ptr es:[bx],ax
-		mov	word ptr es:[bx+2],dx
-		pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop	bp
-		ret
-_jxms_getdriver	endp
-
-
-;
-; void far jxms_calldriver (XMSDRIVER, XMScontext far *)
-;
-; The XMScontext structure contains values for the AX,DX,BX,SI,DS registers.
-; These are loaded, the XMS call is performed, and the new values of the
-; AX,DX,BX registers are written back to the context structure.
-;
-_jxms_calldriver 	proc	far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		les 	bx,dword ptr [bp+10]	; get XMScontext pointer
-		mov 	ax,word ptr es:[bx]	; load registers
-		mov 	dx,word ptr es:[bx+2]
-		mov 	si,word ptr es:[bx+6]
-		mov 	ds,word ptr es:[bx+8]
-		mov 	bx,word ptr es:[bx+4]
-		call	dword ptr [bp+6]	; call the driver
-		mov	cx,bx			; save returned BX for a sec
-		les 	bx,dword ptr [bp+10]	; get XMScontext pointer
-		mov 	word ptr es:[bx],ax	; put back ax,dx,bx
-		mov 	word ptr es:[bx+2],dx
-		mov 	word ptr es:[bx+4],cx
-		pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop 	bp
-		ret
-_jxms_calldriver 	endp
-
-
-;
-; short far jems_available (void)
-;
-; Have we got an EMS driver? (this comes straight from the EMS 4.0 specs)
-;
-_jems_available	proc	far
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		mov	ax,3567h		; get interrupt vector 67h
-		int	21h
-		push	cs
-		pop	ds
-		mov	di,000ah		; check offs 10 in returned seg
-		lea	si,ASCII_device_name	; against literal string
-		mov	cx,8
-		cld
-		repe cmpsb
-		jne	no_ems
-		mov	ax,1			; match, it's there
-		jmp	short avail_done
-no_ems:		xor	ax,ax			; it's not there
-avail_done:	pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		ret
-
-ASCII_device_name	db	"EMMXXXX0"
-
-_jems_available	endp
-
-
-;
-; void far jems_calldriver (EMScontext far *)
-;
-; The EMScontext structure contains values for the AX,DX,BX,SI,DS registers.
-; These are loaded, the EMS trap is performed, and the new values of the
-; AX,DX,BX registers are written back to the context structure.
-;
-_jems_calldriver	proc far
-		push	bp			; linkage
-		mov 	bp,sp
-		push	si			; save all registers for safety
-		push	di
-		push	bx
-		push	cx
-		push	dx
-		push	es
-		push	ds
-		les 	bx,dword ptr [bp+6]	; get EMScontext pointer
-		mov 	ax,word ptr es:[bx]	; load registers
-		mov 	dx,word ptr es:[bx+2]
-		mov 	si,word ptr es:[bx+6]
-		mov 	ds,word ptr es:[bx+8]
-		mov 	bx,word ptr es:[bx+4]
-		int	67h			; call the EMS driver
-		mov	cx,bx			; save returned BX for a sec
-		les 	bx,dword ptr [bp+6]	; get EMScontext pointer
-		mov 	word ptr es:[bx],ax	; put back ax,dx,bx
-		mov 	word ptr es:[bx+2],dx
-		mov 	word ptr es:[bx+4],cx
-		pop	ds			; restore registers and exit
-		pop	es
-		pop	dx
-		pop	cx
-		pop	bx
-		pop	di
-		pop	si
-		pop 	bp
-		ret
-_jems_calldriver	endp
-
-JMEMDOSA_TXT	ends
-
-		end
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemmac.c ./Shared/jpeg-6b/jmemmac.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemmac.c	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemmac.c	Wed Dec 31 19:00:00 1969
@@ -1,289 +0,0 @@
-/*
- * jmemmac.c
- *
- * Copyright (C) 1992-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * jmemmac.c provides an Apple Macintosh implementation of the system-
- * dependent portion of the JPEG memory manager.
- *
- * If you use jmemmac.c, then you must define USE_MAC_MEMMGR in the
- * JPEG_INTERNALS part of jconfig.h.
- *
- * jmemmac.c uses the Macintosh toolbox routines NewPtr and DisposePtr
- * instead of malloc and free.  It accurately determines the amount of
- * memory available by using CompactMem.  Notice that if left to its
- * own devices, this code can chew up all available space in the
- * application's zone, with the exception of the rather small "slop"
- * factor computed in jpeg_mem_available().  The application can ensure
- * that more space is left over by reducing max_memory_to_use.
- *
- * Large images are swapped to disk using temporary files and System 7.0+'s
- * temporary folder functionality.
- *
- * Note that jmemmac.c depends on two features of MacOS that were first
- * introduced in System 7: FindFolder and the FSSpec-based calls.
- * If your application uses jmemmac.c and is run under System 6 or earlier,
- * and the jpeg library decides it needs a temporary file, it will abort,
- * printing error messages about requiring System 7.  (If no temporary files
- * are created, it will run fine.)
- *
- * If you want to use jmemmac.c in an application that might be used with
- * System 6 or earlier, then you should remove dependencies on FindFolder
- * and the FSSpec calls.  You will need to replace FindFolder with some
- * other mechanism for finding a place to put temporary files, and you
- * should replace the FSSpec calls with their HFS equivalents:
- *
- *     FSpDelete     ->  HDelete
- *     FSpGetFInfo   ->  HGetFInfo
- *     FSpCreate     ->  HCreate
- *     FSpOpenDF     ->  HOpen      *** Note: not HOpenDF ***
- *     FSMakeFSSpec  ->  (fill in spec by hand.)
- *
- * (Use HOpen instead of HOpenDF.  HOpen is just a glue-interface to PBHOpen,
- * which is on all HFS macs.  HOpenDF is a System 7 addition which avoids the
- * ages-old problem of names starting with a period.)
- *
- * Contributed by Sam Bushell (jsam@iagu.on.net) and
- * Dan Gildor (gyld@in-touch.com).
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jmemsys.h"    /* import the system-dependent declarations */
-
-#ifndef USE_MAC_MEMMGR	/* make sure user got configuration right */
-  You forgot to define USE_MAC_MEMMGR in jconfig.h. /* deliberate syntax error */
-#endif
-
-#include <Memory.h>     /* we use the MacOS memory manager */
-#include <Files.h>      /* we use the MacOS File stuff */
-#include <Folders.h>    /* we use the MacOS HFS stuff */
-#include <Script.h>     /* for smSystemScript */
-#include <Gestalt.h>    /* we use Gestalt to test for specific functionality */
-
-#ifndef TEMP_FILE_NAME		/* can override from jconfig.h or Makefile */
-#define TEMP_FILE_NAME  "JPG%03d.TMP"
-#endif
-
-static int next_file_num;	/* to distinguish among several temp files */
-
-
-/*
- * Memory allocation and freeing are controlled by the MacOS library
- * routines NewPtr() and DisposePtr(), which allocate fixed-address
- * storage.  Unfortunately, the IJG library isn't smart enough to cope
- * with relocatable storage.
- */
-
-GLOBAL(void *)
-jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void *) NewPtr(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
-{
-  DisposePtr((Ptr) object);
-}
-
-
-/*
- * "Large" objects are treated the same as "small" ones.
- * NB: we include FAR keywords in the routine declarations simply for
- * consistency with the rest of the IJG code; FAR should expand to empty
- * on rational architectures like the Mac.
- */
-
-GLOBAL(void FAR *)
-jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void FAR *) NewPtr(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
-{
-  DisposePtr((Ptr) object);
-}
-
-
-/*
- * This routine computes the total memory space available for allocation.
- */
-
-GLOBAL(long)
-jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
-		    long max_bytes_needed, long already_allocated)
-{
-  long limit = cinfo->mem->max_memory_to_use - already_allocated;
-  long slop, mem;
-
-  /* Don't ask for more than what application has told us we may use */
-  if (max_bytes_needed > limit && limit > 0)
-    max_bytes_needed = limit;
-  /* Find whether there's a big enough free block in the heap.
-   * CompactMem tries to create a contiguous block of the requested size,
-   * and then returns the size of the largest free block (which could be
-   * much more or much less than we asked for).
-   * We add some slop to ensure we don't use up all available memory.
-   */
-  slop = max_bytes_needed / 16 + 32768L;
-  mem = CompactMem(max_bytes_needed + slop) - slop;
-  if (mem < 0)
-    mem = 0;			/* sigh, couldn't even get the slop */
-  /* Don't take more than the application says we can have */
-  if (mem > limit && limit > 0)
-    mem = limit;
-  return mem;
-}
-
-
-/*
- * Backing store (temporary file) management.
- * Backing store objects are only used when the value returned by
- * jpeg_mem_available is less than the total space needed.  You can dispense
- * with these routines if you have plenty of virtual memory; see jmemnobs.c.
- */
-
-
-METHODDEF(void)
-read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-		    void FAR * buffer_address,
-		    long file_offset, long byte_count)
-{
-  long bytes = byte_count;
-  long retVal;
-
-  if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr )
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-
-  retVal = FSRead ( info->temp_file, &bytes,
-		    (unsigned char *) buffer_address );
-  if ( retVal != noErr || bytes != byte_count )
-    ERREXIT(cinfo, JERR_TFILE_READ);
-}
-
-
-METHODDEF(void)
-write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-		     void FAR * buffer_address,
-		     long file_offset, long byte_count)
-{
-  long bytes = byte_count;
-  long retVal;
-
-  if ( SetFPos ( info->temp_file, fsFromStart, file_offset ) != noErr )
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-
-  retVal = FSWrite ( info->temp_file, &bytes,
-		     (unsigned char *) buffer_address );
-  if ( retVal != noErr || bytes != byte_count )
-    ERREXIT(cinfo, JERR_TFILE_WRITE);
-}
-
-
-METHODDEF(void)
-close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
-{
-  FSClose ( info->temp_file );
-  FSpDelete ( &(info->tempSpec) );
-}
-
-
-/*
- * Initial opening of a backing-store object.
- *
- * This version uses FindFolder to find the Temporary Items folder,
- * and puts the temporary file in there.
- */
-
-GLOBAL(void)
-jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-			 long total_bytes_needed)
-{
-  short         tmpRef, vRefNum;
-  long          dirID;
-  FInfo         finderInfo;
-  FSSpec        theSpec;
-  Str255        fName;
-  OSErr         osErr;
-  long          gestaltResponse = 0;
-
-  /* Check that FSSpec calls are available. */
-  osErr = Gestalt( gestaltFSAttr, &gestaltResponse );
-  if ( ( osErr != noErr )
-       || !( gestaltResponse & (1<<gestaltHasFSSpecCalls) ) )
-    ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required");
-  /* TO DO: add a proper error message to jerror.h. */
-
-  /* Check that FindFolder is available. */
-  osErr = Gestalt( gestaltFindFolderAttr, &gestaltResponse );
-  if ( ( osErr != noErr )
-       || !( gestaltResponse & (1<<gestaltFindFolderPresent) ) )
-    ERREXITS(cinfo, JERR_TFILE_CREATE, "- System 7.0 or later required.");
-  /* TO DO: add a proper error message to jerror.h. */
-
-  osErr = FindFolder ( kOnSystemDisk, kTemporaryFolderType, kCreateFolder,
-                       &vRefNum, &dirID );
-  if ( osErr != noErr )
-    ERREXITS(cinfo, JERR_TFILE_CREATE, "- temporary items folder unavailable");
-  /* TO DO: Try putting the temp files somewhere else. */
-
-  /* Keep generating file names till we find one that's not in use */
-  for (;;) {
-    next_file_num++;		/* advance counter */
-
-    sprintf(info->temp_name, TEMP_FILE_NAME, next_file_num);
-    strcpy ( (Ptr)fName+1, info->temp_name );
-    *fName = strlen (info->temp_name);
-    osErr = FSMakeFSSpec ( vRefNum, dirID, fName, &theSpec );
-
-    if ( (osErr = FSpGetFInfo ( &theSpec, &finderInfo ) ) != noErr )
-      break;
-  }
-
-  osErr = FSpCreate ( &theSpec, '????', '????', smSystemScript );
-  if ( osErr != noErr )
-    ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
-
-  osErr = FSpOpenDF ( &theSpec, fsRdWrPerm, &(info->temp_file) );
-  if ( osErr != noErr )
-    ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
-
-  info->tempSpec = theSpec;
-
-  info->read_backing_store = read_backing_store;
-  info->write_backing_store = write_backing_store;
-  info->close_backing_store = close_backing_store;
-  TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
-}
-
-
-/*
- * These routines take care of any system-dependent initialization and
- * cleanup required.
- */
-
-GLOBAL(long)
-jpeg_mem_init (j_common_ptr cinfo)
-{
-  next_file_num = 0;
-
-  /* max_memory_to_use will be initialized to FreeMem()'s result;
-   * the calling application might later reduce it, for example
-   * to leave room to invoke multiple JPEG objects.
-   * Note that FreeMem returns the total number of free bytes;
-   * it may not be possible to allocate a single block of this size.
-   */
-  return FreeMem();
-}
-
-GLOBAL(void)
-jpeg_mem_term (j_common_ptr cinfo)
-{
-  /* no work */
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemmgr.c ./Shared/jpeg-6b/jmemmgr.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemmgr.c	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemmgr.c	Wed Dec 31 19:00:00 1969
@@ -1,1118 +0,0 @@
-/*
- * jmemmgr.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains the JPEG system-independent memory management
- * routines.  This code is usable across a wide variety of machines; most
- * of the system dependencies have been isolated in a separate file.
- * The major functions provided here are:
- *   * pool-based allocation and freeing of memory;
- *   * policy decisions about how to divide available memory among the
- *     virtual arrays;
- *   * control logic for swapping virtual arrays between main memory and
- *     backing storage.
- * The separate system-dependent file provides the actual backing-storage
- * access code, and it contains the policy decision about how much total
- * main memory to use.
- * This file is system-dependent in the sense that some of its functions
- * are unnecessary in some systems.  For example, if there is enough virtual
- * memory so that backing storage will never be used, much of the virtual
- * array control logic could be removed.  (Of course, if you have that much
- * memory then you shouldn't care about a little bit of unused code...)
- */
-
-#define JPEG_INTERNALS
-#define AM_MEMORY_MANAGER	/* we define jvirt_Xarray_control structs */
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jmemsys.h"		/* import the system-dependent declarations */
-
-#ifndef NO_GETENV
-#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare getenv() */
-extern char * getenv JPP((const char * name));
-#endif
-#endif
-
-
-/*
- * Some important notes:
- *   The allocation routines provided here must never return NULL.
- *   They should exit to error_exit if unsuccessful.
- *
- *   It's not a good idea to try to merge the sarray and barray routines,
- *   even though they are textually almost the same, because samples are
- *   usually stored as bytes while coefficients are shorts or ints.  Thus,
- *   in machines where byte pointers have a different representation from
- *   word pointers, the resulting machine code could not be the same.
- */
-
-
-/*
- * Many machines require storage alignment: longs must start on 4-byte
- * boundaries, doubles on 8-byte boundaries, etc.  On such machines, malloc()
- * always returns pointers that are multiples of the worst-case alignment
- * requirement, and we had better do so too.
- * There isn't any really portable way to determine the worst-case alignment
- * requirement.  This module assumes that the alignment requirement is
- * multiples of sizeof(ALIGN_TYPE).
- * By default, we define ALIGN_TYPE as double.  This is necessary on some
- * workstations (where doubles really do need 8-byte alignment) and will work
- * fine on nearly everything.  If your machine has lesser alignment needs,
- * you can save a few bytes by making ALIGN_TYPE smaller.
- * The only place I know of where this will NOT work is certain Macintosh
- * 680x0 compilers that define double as a 10-byte IEEE extended float.
- * Doing 10-byte alignment is counterproductive because longwords won't be
- * aligned well.  Put "#define ALIGN_TYPE long" in jconfig.h if you have
- * such a compiler.
- */
-
-#ifndef ALIGN_TYPE		/* so can override from jconfig.h */
-#define ALIGN_TYPE  double
-#endif
-
-
-/*
- * We allocate objects from "pools", where each pool is gotten with a single
- * request to jpeg_get_small() or jpeg_get_large().  There is no per-object
- * overhead within a pool, except for alignment padding.  Each pool has a
- * header with a link to the next pool of the same class.
- * Small and large pool headers are identical except that the latter's
- * link pointer must be FAR on 80x86 machines.
- * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
- * field.  This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
- * of the alignment requirement of ALIGN_TYPE.
- */
-
-typedef union small_pool_struct * small_pool_ptr;
-
-typedef union small_pool_struct {
-  struct {
-    small_pool_ptr next;	/* next in list of pools */
-    size_t bytes_used;		/* how many bytes already used within pool */
-    size_t bytes_left;		/* bytes still available in this pool */
-  } hdr;
-  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
-} small_pool_hdr;
-
-typedef union large_pool_struct FAR * large_pool_ptr;
-
-typedef union large_pool_struct {
-  struct {
-    large_pool_ptr next;	/* next in list of pools */
-    size_t bytes_used;		/* how many bytes already used within pool */
-    size_t bytes_left;		/* bytes still available in this pool */
-  } hdr;
-  ALIGN_TYPE dummy;		/* included in union to ensure alignment */
-} large_pool_hdr;
-
-
-/*
- * Here is the full definition of a memory manager object.
- */
-
-typedef struct {
-  struct jpeg_memory_mgr pub;	/* public fields */
-
-  /* Each pool identifier (lifetime class) names a linked list of pools. */
-  small_pool_ptr small_list[JPOOL_NUMPOOLS];
-  large_pool_ptr large_list[JPOOL_NUMPOOLS];
-
-  /* Since we only have one lifetime class of virtual arrays, only one
-   * linked list is necessary (for each datatype).  Note that the virtual
-   * array control blocks being linked together are actually stored somewhere
-   * in the small-pool list.
-   */
-  jvirt_sarray_ptr virt_sarray_list;
-  jvirt_barray_ptr virt_barray_list;
-
-  /* This counts total space obtained from jpeg_get_small/large */
-  long total_space_allocated;
-
-  /* alloc_sarray and alloc_barray set this value for use by virtual
-   * array routines.
-   */
-  JDIMENSION last_rowsperchunk;	/* from most recent alloc_sarray/barray */
-} my_memory_mgr;
-
-typedef my_memory_mgr * my_mem_ptr;
-
-
-/*
- * The control blocks for virtual arrays.
- * Note that these blocks are allocated in the "small" pool area.
- * System-dependent info for the associated backing store (if any) is hidden
- * inside the backing_store_info struct.
- */
-
-struct jvirt_sarray_control {
-  JSAMPARRAY mem_buffer;	/* => the in-memory buffer */
-  JDIMENSION rows_in_array;	/* total virtual array height */
-  JDIMENSION samplesperrow;	/* width of array (and of memory buffer) */
-  JDIMENSION maxaccess;		/* max rows accessed by access_virt_sarray */
-  JDIMENSION rows_in_mem;	/* height of memory buffer */
-  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
-  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
-  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
-  boolean pre_zero;		/* pre-zero mode requested? */
-  boolean dirty;		/* do current buffer contents need written? */
-  boolean b_s_open;		/* is backing-store data valid? */
-  jvirt_sarray_ptr next;	/* link to next virtual sarray control block */
-  backing_store_info b_s_info;	/* System-dependent control info */
-};
-
-struct jvirt_barray_control {
-  JBLOCKARRAY mem_buffer;	/* => the in-memory buffer */
-  JDIMENSION rows_in_array;	/* total virtual array height */
-  JDIMENSION blocksperrow;	/* width of array (and of memory buffer) */
-  JDIMENSION maxaccess;		/* max rows accessed by access_virt_barray */
-  JDIMENSION rows_in_mem;	/* height of memory buffer */
-  JDIMENSION rowsperchunk;	/* allocation chunk size in mem_buffer */
-  JDIMENSION cur_start_row;	/* first logical row # in the buffer */
-  JDIMENSION first_undef_row;	/* row # of first uninitialized row */
-  boolean pre_zero;		/* pre-zero mode requested? */
-  boolean dirty;		/* do current buffer contents need written? */
-  boolean b_s_open;		/* is backing-store data valid? */
-  jvirt_barray_ptr next;	/* link to next virtual barray control block */
-  backing_store_info b_s_info;	/* System-dependent control info */
-};
-
-
-#ifdef MEM_STATS		/* optional extra stuff for statistics */
-
-LOCAL(void)
-print_mem_stats (j_common_ptr cinfo, int pool_id)
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  small_pool_ptr shdr_ptr;
-  large_pool_ptr lhdr_ptr;
-
-  /* Since this is only a debugging stub, we can cheat a little by using
-   * fprintf directly rather than going through the trace message code.
-   * This is helpful because message parm array can't handle longs.
-   */
-  fprintf(stderr, "Freeing pool %d, total space = %ld\n",
-	  pool_id, mem->total_space_allocated);
-
-  for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
-       lhdr_ptr = lhdr_ptr->hdr.next) {
-    fprintf(stderr, "  Large chunk used %ld\n",
-	    (long) lhdr_ptr->hdr.bytes_used);
-  }
-
-  for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
-       shdr_ptr = shdr_ptr->hdr.next) {
-    fprintf(stderr, "  Small chunk used %ld free %ld\n",
-	    (long) shdr_ptr->hdr.bytes_used,
-	    (long) shdr_ptr->hdr.bytes_left);
-  }
-}
-
-#endif /* MEM_STATS */
-
-
-LOCAL(void)
-out_of_memory (j_common_ptr cinfo, int which)
-/* Report an out-of-memory error and stop execution */
-/* If we compiled MEM_STATS support, report alloc requests before dying */
-{
-#ifdef MEM_STATS
-  cinfo->err->trace_level = 2;	/* force self_destruct to report stats */
-#endif
-  ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
-}
-
-
-/*
- * Allocation of "small" objects.
- *
- * For these, we use pooled storage.  When a new pool must be created,
- * we try to get enough space for the current request plus a "slop" factor,
- * where the slop will be the amount of leftover space in the new pool.
- * The speed vs. space tradeoff is largely determined by the slop values.
- * A different slop value is provided for each pool class (lifetime),
- * and we also distinguish the first pool of a class from later ones.
- * NOTE: the values given work fairly well on both 16- and 32-bit-int
- * machines, but may be too small if longs are 64 bits or more.
- */
-
-static const size_t first_pool_slop[JPOOL_NUMPOOLS] = 
-{
-	1600,			/* first PERMANENT pool */
-	16000			/* first IMAGE pool */
-};
-
-static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = 
-{
-	0,			/* additional PERMANENT pools */
-	5000			/* additional IMAGE pools */
-};
-
-#define MIN_SLOP  50		/* greater than 0 to avoid futile looping */
-
-
-METHODDEF(void *)
-alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
-/* Allocate a "small" object */
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  small_pool_ptr hdr_ptr, prev_hdr_ptr;
-  char * data_ptr;
-  size_t odd_bytes, min_request, slop;
-
-  /* Check for unsatisfiable request (do now to ensure no overflow below) */
-  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
-    out_of_memory(cinfo, 1);	/* request exceeds malloc's ability */
-
-  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
-  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
-  if (odd_bytes > 0)
-    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
-
-  /* See if space is available in any existing pool */
-  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
-    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
-  prev_hdr_ptr = NULL;
-  hdr_ptr = mem->small_list[pool_id];
-  while (hdr_ptr != NULL) {
-    if (hdr_ptr->hdr.bytes_left >= sizeofobject)
-      break;			/* found pool with enough space */
-    prev_hdr_ptr = hdr_ptr;
-    hdr_ptr = hdr_ptr->hdr.next;
-  }
-
-  /* Time to make a new pool? */
-  if (hdr_ptr == NULL) {
-    /* min_request is what we need now, slop is what will be leftover */
-    min_request = sizeofobject + SIZEOF(small_pool_hdr);
-    if (prev_hdr_ptr == NULL)	/* first pool in class? */
-      slop = first_pool_slop[pool_id];
-    else
-      slop = extra_pool_slop[pool_id];
-    /* Don't ask for more than MAX_ALLOC_CHUNK */
-    if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
-      slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
-    /* Try to get space, if fail reduce slop and try again */
-    for (;;) {
-      hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
-      if (hdr_ptr != NULL)
-	break;
-      slop /= 2;
-      if (slop < MIN_SLOP)	/* give up when it gets real small */
-	out_of_memory(cinfo, 2); /* jpeg_get_small failed */
-    }
-    mem->total_space_allocated += min_request + slop;
-    /* Success, initialize the new pool header and add to end of list */
-    hdr_ptr->hdr.next = NULL;
-    hdr_ptr->hdr.bytes_used = 0;
-    hdr_ptr->hdr.bytes_left = sizeofobject + slop;
-    if (prev_hdr_ptr == NULL)	/* first pool in class? */
-      mem->small_list[pool_id] = hdr_ptr;
-    else
-      prev_hdr_ptr->hdr.next = hdr_ptr;
-  }
-
-  /* OK, allocate the object from the current pool */
-  data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
-  data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
-  hdr_ptr->hdr.bytes_used += sizeofobject;
-  hdr_ptr->hdr.bytes_left -= sizeofobject;
-
-  return (void *) data_ptr;
-}
-
-
-/*
- * Allocation of "large" objects.
- *
- * The external semantics of these are the same as "small" objects,
- * except that FAR pointers are used on 80x86.  However the pool
- * management heuristics are quite different.  We assume that each
- * request is large enough that it may as well be passed directly to
- * jpeg_get_large; the pool management just links everything together
- * so that we can free it all on demand.
- * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
- * structures.  The routines that create these structures (see below)
- * deliberately bunch rows together to ensure a large request size.
- */
-
-METHODDEF(void FAR *)
-alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
-/* Allocate a "large" object */
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  large_pool_ptr hdr_ptr;
-  size_t odd_bytes;
-
-  /* Check for unsatisfiable request (do now to ensure no overflow below) */
-  if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
-    out_of_memory(cinfo, 3);	/* request exceeds malloc's ability */
-
-  /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
-  odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
-  if (odd_bytes > 0)
-    sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
-
-  /* Always make a new pool */
-  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
-    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
-
-  hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
-					    SIZEOF(large_pool_hdr));
-  if (hdr_ptr == NULL)
-    out_of_memory(cinfo, 4);	/* jpeg_get_large failed */
-  mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
-
-  /* Success, initialize the new pool header and add to list */
-  hdr_ptr->hdr.next = mem->large_list[pool_id];
-  /* We maintain space counts in each pool header for statistical purposes,
-   * even though they are not needed for allocation.
-   */
-  hdr_ptr->hdr.bytes_used = sizeofobject;
-  hdr_ptr->hdr.bytes_left = 0;
-  mem->large_list[pool_id] = hdr_ptr;
-
-  return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
-}
-
-
-/*
- * Creation of 2-D sample arrays.
- * The pointers are in near heap, the samples themselves in FAR heap.
- *
- * To minimize allocation overhead and to allow I/O of large contiguous
- * blocks, we allocate the sample rows in groups of as many rows as possible
- * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
- * NB: the virtual array control routines, later in this file, know about
- * this chunking of rows.  The rowsperchunk value is left in the mem manager
- * object so that it can be saved away if this sarray is the workspace for
- * a virtual array.
- */
-
-METHODDEF(JSAMPARRAY)
-alloc_sarray (j_common_ptr cinfo, int pool_id,
-	      JDIMENSION samplesperrow, JDIMENSION numrows)
-/* Allocate a 2-D sample array */
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  JSAMPARRAY result;
-  JSAMPROW workspace;
-  JDIMENSION rowsperchunk, currow, i;
-  long ltemp;
-
-  /* Calculate max # of rows allowed in one allocation chunk */
-  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
-	  ((long) samplesperrow * SIZEOF(JSAMPLE));
-  if (ltemp <= 0)
-    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
-  if (ltemp < (long) numrows)
-    rowsperchunk = (JDIMENSION) ltemp;
-  else
-    rowsperchunk = numrows;
-  mem->last_rowsperchunk = rowsperchunk;
-
-  /* Get space for row pointers (small object) */
-  result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
-				    (size_t) (numrows * SIZEOF(JSAMPROW)));
-
-  /* Get the rows themselves (large objects) */
-  currow = 0;
-  while (currow < numrows) {
-    rowsperchunk = MIN(rowsperchunk, numrows - currow);
-    workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
-	(size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
-		  * SIZEOF(JSAMPLE)));
-    for (i = rowsperchunk; i > 0; i--) {
-      result[currow++] = workspace;
-      workspace += samplesperrow;
-    }
-  }
-
-  return result;
-}
-
-
-/*
- * Creation of 2-D coefficient-block arrays.
- * This is essentially the same as the code for sample arrays, above.
- */
-
-METHODDEF(JBLOCKARRAY)
-alloc_barray (j_common_ptr cinfo, int pool_id,
-	      JDIMENSION blocksperrow, JDIMENSION numrows)
-/* Allocate a 2-D coefficient-block array */
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  JBLOCKARRAY result;
-  JBLOCKROW workspace;
-  JDIMENSION rowsperchunk, currow, i;
-  long ltemp;
-
-  /* Calculate max # of rows allowed in one allocation chunk */
-  ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
-	  ((long) blocksperrow * SIZEOF(JBLOCK));
-  if (ltemp <= 0)
-    ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
-  if (ltemp < (long) numrows)
-    rowsperchunk = (JDIMENSION) ltemp;
-  else
-    rowsperchunk = numrows;
-  mem->last_rowsperchunk = rowsperchunk;
-
-  /* Get space for row pointers (small object) */
-  result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
-				     (size_t) (numrows * SIZEOF(JBLOCKROW)));
-
-  /* Get the rows themselves (large objects) */
-  currow = 0;
-  while (currow < numrows) {
-    rowsperchunk = MIN(rowsperchunk, numrows - currow);
-    workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
-	(size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
-		  * SIZEOF(JBLOCK)));
-    for (i = rowsperchunk; i > 0; i--) {
-      result[currow++] = workspace;
-      workspace += blocksperrow;
-    }
-  }
-
-  return result;
-}
-
-
-/*
- * About virtual array management:
- *
- * The above "normal" array routines are only used to allocate strip buffers
- * (as wide as the image, but just a few rows high).  Full-image-sized buffers
- * are handled as "virtual" arrays.  The array is still accessed a strip at a
- * time, but the memory manager must save the whole array for repeated
- * accesses.  The intended implementation is that there is a strip buffer in
- * memory (as high as is possible given the desired memory limit), plus a
- * backing file that holds the rest of the array.
- *
- * The request_virt_array routines are told the total size of the image and
- * the maximum number of rows that will be accessed at once.  The in-memory
- * buffer must be at least as large as the maxaccess value.
- *
- * The request routines create control blocks but not the in-memory buffers.
- * That is postponed until realize_virt_arrays is called.  At that time the
- * total amount of space needed is known (approximately, anyway), so free
- * memory can be divided up fairly.
- *
- * The access_virt_array routines are responsible for making a specific strip
- * area accessible (after reading or writing the backing file, if necessary).
- * Note that the access routines are told whether the caller intends to modify
- * the accessed strip; during a read-only pass this saves having to rewrite
- * data to disk.  The access routines are also responsible for pre-zeroing
- * any newly accessed rows, if pre-zeroing was requested.
- *
- * In current usage, the access requests are usually for nonoverlapping
- * strips; that is, successive access start_row numbers differ by exactly
- * num_rows = maxaccess.  This means we can get good performance with simple
- * buffer dump/reload logic, by making the in-memory buffer be a multiple
- * of the access height; then there will never be accesses across bufferload
- * boundaries.  The code will still work with overlapping access requests,
- * but it doesn't handle bufferload overlaps very efficiently.
- */
-
-
-METHODDEF(jvirt_sarray_ptr)
-request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
-		     JDIMENSION samplesperrow, JDIMENSION numrows,
-		     JDIMENSION maxaccess)
-/* Request a virtual 2-D sample array */
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  jvirt_sarray_ptr result;
-
-  /* Only IMAGE-lifetime virtual arrays are currently supported */
-  if (pool_id != JPOOL_IMAGE)
-    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
-
-  /* get control block */
-  result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
-					  SIZEOF(struct jvirt_sarray_control));
-
-  result->mem_buffer = NULL;	/* marks array not yet realized */
-  result->rows_in_array = numrows;
-  result->samplesperrow = samplesperrow;
-  result->maxaccess = maxaccess;
-  result->pre_zero = pre_zero;
-  result->b_s_open = FALSE;	/* no associated backing-store object */
-  result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
-  mem->virt_sarray_list = result;
-
-  return result;
-}
-
-
-METHODDEF(jvirt_barray_ptr)
-request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
-		     JDIMENSION blocksperrow, JDIMENSION numrows,
-		     JDIMENSION maxaccess)
-/* Request a virtual 2-D coefficient-block array */
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  jvirt_barray_ptr result;
-
-  /* Only IMAGE-lifetime virtual arrays are currently supported */
-  if (pool_id != JPOOL_IMAGE)
-    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
-
-  /* get control block */
-  result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
-					  SIZEOF(struct jvirt_barray_control));
-
-  result->mem_buffer = NULL;	/* marks array not yet realized */
-  result->rows_in_array = numrows;
-  result->blocksperrow = blocksperrow;
-  result->maxaccess = maxaccess;
-  result->pre_zero = pre_zero;
-  result->b_s_open = FALSE;	/* no associated backing-store object */
-  result->next = mem->virt_barray_list; /* add to list of virtual arrays */
-  mem->virt_barray_list = result;
-
-  return result;
-}
-
-
-METHODDEF(void)
-realize_virt_arrays (j_common_ptr cinfo)
-/* Allocate the in-memory buffers for any unrealized virtual arrays */
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  long space_per_minheight, maximum_space, avail_mem;
-  long minheights, max_minheights;
-  jvirt_sarray_ptr sptr;
-  jvirt_barray_ptr bptr;
-
-  /* Compute the minimum space needed (maxaccess rows in each buffer)
-   * and the maximum space needed (full image height in each buffer).
-   * These may be of use to the system-dependent jpeg_mem_available routine.
-   */
-  space_per_minheight = 0;
-  maximum_space = 0;
-  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
-    if (sptr->mem_buffer == NULL) { /* if not realized yet */
-      space_per_minheight += (long) sptr->maxaccess *
-			     (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
-      maximum_space += (long) sptr->rows_in_array *
-		       (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
-    }
-  }
-  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
-    if (bptr->mem_buffer == NULL) { /* if not realized yet */
-      space_per_minheight += (long) bptr->maxaccess *
-			     (long) bptr->blocksperrow * SIZEOF(JBLOCK);
-      maximum_space += (long) bptr->rows_in_array *
-		       (long) bptr->blocksperrow * SIZEOF(JBLOCK);
-    }
-  }
-
-  if (space_per_minheight <= 0)
-    return;			/* no unrealized arrays, no work */
-
-  /* Determine amount of memory to actually use; this is system-dependent. */
-  avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
-				 mem->total_space_allocated);
-
-  /* If the maximum space needed is available, make all the buffers full
-   * height; otherwise parcel it out with the same number of minheights
-   * in each buffer.
-   */
-  if (avail_mem >= maximum_space)
-    max_minheights = 1000000000L;
-  else {
-    max_minheights = avail_mem / space_per_minheight;
-    /* If there doesn't seem to be enough space, try to get the minimum
-     * anyway.  This allows a "stub" implementation of jpeg_mem_available().
-     */
-    if (max_minheights <= 0)
-      max_minheights = 1;
-  }
-
-  /* Allocate the in-memory buffers and initialize backing store as needed. */
-
-  for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
-    if (sptr->mem_buffer == NULL) { /* if not realized yet */
-      minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
-      if (minheights <= max_minheights) {
-	/* This buffer fits in memory */
-	sptr->rows_in_mem = sptr->rows_in_array;
-      } else {
-	/* It doesn't fit in memory, create backing store. */
-	sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
-	jpeg_open_backing_store(cinfo, & sptr->b_s_info,
-				(long) sptr->rows_in_array *
-				(long) sptr->samplesperrow *
-				(long) SIZEOF(JSAMPLE));
-	sptr->b_s_open = TRUE;
-      }
-      sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
-				      sptr->samplesperrow, sptr->rows_in_mem);
-      sptr->rowsperchunk = mem->last_rowsperchunk;
-      sptr->cur_start_row = 0;
-      sptr->first_undef_row = 0;
-      sptr->dirty = FALSE;
-    }
-  }
-
-  for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
-    if (bptr->mem_buffer == NULL) { /* if not realized yet */
-      minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
-      if (minheights <= max_minheights) {
-	/* This buffer fits in memory */
-	bptr->rows_in_mem = bptr->rows_in_array;
-      } else {
-	/* It doesn't fit in memory, create backing store. */
-	bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
-	jpeg_open_backing_store(cinfo, & bptr->b_s_info,
-				(long) bptr->rows_in_array *
-				(long) bptr->blocksperrow *
-				(long) SIZEOF(JBLOCK));
-	bptr->b_s_open = TRUE;
-      }
-      bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
-				      bptr->blocksperrow, bptr->rows_in_mem);
-      bptr->rowsperchunk = mem->last_rowsperchunk;
-      bptr->cur_start_row = 0;
-      bptr->first_undef_row = 0;
-      bptr->dirty = FALSE;
-    }
-  }
-}
-
-
-LOCAL(void)
-do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
-/* Do backing store read or write of a virtual sample array */
-{
-  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
-
-  bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
-  file_offset = ptr->cur_start_row * bytesperrow;
-  /* Loop to read or write each allocation chunk in mem_buffer */
-  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
-    /* One chunk, but check for short chunk at end of buffer */
-    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
-    /* Transfer no more than is currently defined */
-    thisrow = (long) ptr->cur_start_row + i;
-    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
-    /* Transfer no more than fits in file */
-    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
-    if (rows <= 0)		/* this chunk might be past end of file! */
-      break;
-    byte_count = rows * bytesperrow;
-    if (writing)
-      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
-					    (void FAR *) ptr->mem_buffer[i],
-					    file_offset, byte_count);
-    else
-      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
-					   (void FAR *) ptr->mem_buffer[i],
-					   file_offset, byte_count);
-    file_offset += byte_count;
-  }
-}
-
-
-LOCAL(void)
-do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
-/* Do backing store read or write of a virtual coefficient-block array */
-{
-  long bytesperrow, file_offset, byte_count, rows, thisrow, i;
-
-  bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
-  file_offset = ptr->cur_start_row * bytesperrow;
-  /* Loop to read or write each allocation chunk in mem_buffer */
-  for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
-    /* One chunk, but check for short chunk at end of buffer */
-    rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
-    /* Transfer no more than is currently defined */
-    thisrow = (long) ptr->cur_start_row + i;
-    rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
-    /* Transfer no more than fits in file */
-    rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
-    if (rows <= 0)		/* this chunk might be past end of file! */
-      break;
-    byte_count = rows * bytesperrow;
-    if (writing)
-      (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
-					    (void FAR *) ptr->mem_buffer[i],
-					    file_offset, byte_count);
-    else
-      (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
-					   (void FAR *) ptr->mem_buffer[i],
-					   file_offset, byte_count);
-    file_offset += byte_count;
-  }
-}
-
-
-METHODDEF(JSAMPARRAY)
-access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
-		    JDIMENSION start_row, JDIMENSION num_rows,
-		    boolean writable)
-/* Access the part of a virtual sample array starting at start_row */
-/* and extending for num_rows rows.  writable is true if  */
-/* caller intends to modify the accessed area. */
-{
-  JDIMENSION end_row = start_row + num_rows;
-  JDIMENSION undef_row;
-
-  /* debugging check */
-  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
-      ptr->mem_buffer == NULL)
-    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
-
-  /* Make the desired part of the virtual array accessible */
-  if (start_row < ptr->cur_start_row ||
-      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
-    if (! ptr->b_s_open)
-      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
-    /* Flush old buffer contents if necessary */
-    if (ptr->dirty) {
-      do_sarray_io(cinfo, ptr, TRUE);
-      ptr->dirty = FALSE;
-    }
-    /* Decide what part of virtual array to access.
-     * Algorithm: if target address > current window, assume forward scan,
-     * load starting at target address.  If target address < current window,
-     * assume backward scan, load so that target area is top of window.
-     * Note that when switching from forward write to forward read, will have
-     * start_row = 0, so the limiting case applies and we load from 0 anyway.
-     */
-    if (start_row > ptr->cur_start_row) {
-      ptr->cur_start_row = start_row;
-    } else {
-      /* use long arithmetic here to avoid overflow & unsigned problems */
-      long ltemp;
-
-      ltemp = (long) end_row - (long) ptr->rows_in_mem;
-      if (ltemp < 0)
-	ltemp = 0;		/* don't fall off front end of file */
-      ptr->cur_start_row = (JDIMENSION) ltemp;
-    }
-    /* Read in the selected part of the array.
-     * During the initial write pass, we will do no actual read
-     * because the selected part is all undefined.
-     */
-    do_sarray_io(cinfo, ptr, FALSE);
-  }
-  /* Ensure the accessed part of the array is defined; prezero if needed.
-   * To improve locality of access, we only prezero the part of the array
-   * that the caller is about to access, not the entire in-memory array.
-   */
-  if (ptr->first_undef_row < end_row) {
-    if (ptr->first_undef_row < start_row) {
-      if (writable)		/* writer skipped over a section of array */
-	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
-      undef_row = start_row;	/* but reader is allowed to read ahead */
-    } else {
-      undef_row = ptr->first_undef_row;
-    }
-    if (writable)
-      ptr->first_undef_row = end_row;
-    if (ptr->pre_zero) {
-      size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
-      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
-      end_row -= ptr->cur_start_row;
-      while (undef_row < end_row) {
-	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
-	undef_row++;
-      }
-    } else {
-      if (! writable)		/* reader looking at undefined data */
-	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
-    }
-  }
-  /* Flag the buffer dirty if caller will write in it */
-  if (writable)
-    ptr->dirty = TRUE;
-  /* Return address of proper part of the buffer */
-  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
-}
-
-
-METHODDEF(JBLOCKARRAY)
-access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
-		    JDIMENSION start_row, JDIMENSION num_rows,
-		    boolean writable)
-/* Access the part of a virtual block array starting at start_row */
-/* and extending for num_rows rows.  writable is true if  */
-/* caller intends to modify the accessed area. */
-{
-  JDIMENSION end_row = start_row + num_rows;
-  JDIMENSION undef_row;
-
-  /* debugging check */
-  if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
-      ptr->mem_buffer == NULL)
-    ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
-
-  /* Make the desired part of the virtual array accessible */
-  if (start_row < ptr->cur_start_row ||
-      end_row > ptr->cur_start_row+ptr->rows_in_mem) {
-    if (! ptr->b_s_open)
-      ERREXIT(cinfo, JERR_VIRTUAL_BUG);
-    /* Flush old buffer contents if necessary */
-    if (ptr->dirty) {
-      do_barray_io(cinfo, ptr, TRUE);
-      ptr->dirty = FALSE;
-    }
-    /* Decide what part of virtual array to access.
-     * Algorithm: if target address > current window, assume forward scan,
-     * load starting at target address.  If target address < current window,
-     * assume backward scan, load so that target area is top of window.
-     * Note that when switching from forward write to forward read, will have
-     * start_row = 0, so the limiting case applies and we load from 0 anyway.
-     */
-    if (start_row > ptr->cur_start_row) {
-      ptr->cur_start_row = start_row;
-    } else {
-      /* use long arithmetic here to avoid overflow & unsigned problems */
-      long ltemp;
-
-      ltemp = (long) end_row - (long) ptr->rows_in_mem;
-      if (ltemp < 0)
-	ltemp = 0;		/* don't fall off front end of file */
-      ptr->cur_start_row = (JDIMENSION) ltemp;
-    }
-    /* Read in the selected part of the array.
-     * During the initial write pass, we will do no actual read
-     * because the selected part is all undefined.
-     */
-    do_barray_io(cinfo, ptr, FALSE);
-  }
-  /* Ensure the accessed part of the array is defined; prezero if needed.
-   * To improve locality of access, we only prezero the part of the array
-   * that the caller is about to access, not the entire in-memory array.
-   */
-  if (ptr->first_undef_row < end_row) {
-    if (ptr->first_undef_row < start_row) {
-      if (writable)		/* writer skipped over a section of array */
-	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
-      undef_row = start_row;	/* but reader is allowed to read ahead */
-    } else {
-      undef_row = ptr->first_undef_row;
-    }
-    if (writable)
-      ptr->first_undef_row = end_row;
-    if (ptr->pre_zero) {
-      size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
-      undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
-      end_row -= ptr->cur_start_row;
-      while (undef_row < end_row) {
-	jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
-	undef_row++;
-      }
-    } else {
-      if (! writable)		/* reader looking at undefined data */
-	ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
-    }
-  }
-  /* Flag the buffer dirty if caller will write in it */
-  if (writable)
-    ptr->dirty = TRUE;
-  /* Return address of proper part of the buffer */
-  return ptr->mem_buffer + (start_row - ptr->cur_start_row);
-}
-
-
-/*
- * Release all objects belonging to a specified pool.
- */
-
-METHODDEF(void)
-free_pool (j_common_ptr cinfo, int pool_id)
-{
-  my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
-  small_pool_ptr shdr_ptr;
-  large_pool_ptr lhdr_ptr;
-  size_t space_freed;
-
-  if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
-    ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id);	/* safety check */
-
-#ifdef MEM_STATS
-  if (cinfo->err->trace_level > 1)
-    print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
-#endif
-
-  /* If freeing IMAGE pool, close any virtual arrays first */
-  if (pool_id == JPOOL_IMAGE) {
-    jvirt_sarray_ptr sptr;
-    jvirt_barray_ptr bptr;
-
-    for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
-      if (sptr->b_s_open) {	/* there may be no backing store */
-	sptr->b_s_open = FALSE;	/* prevent recursive close if error */
-	(*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
-      }
-    }
-    mem->virt_sarray_list = NULL;
-    for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
-      if (bptr->b_s_open) {	/* there may be no backing store */
-	bptr->b_s_open = FALSE;	/* prevent recursive close if error */
-	(*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
-      }
-    }
-    mem->virt_barray_list = NULL;
-  }
-
-  /* Release large objects */
-  lhdr_ptr = mem->large_list[pool_id];
-  mem->large_list[pool_id] = NULL;
-
-  while (lhdr_ptr != NULL) {
-    large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
-    space_freed = lhdr_ptr->hdr.bytes_used +
-		  lhdr_ptr->hdr.bytes_left +
-		  SIZEOF(large_pool_hdr);
-    jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
-    mem->total_space_allocated -= space_freed;
-    lhdr_ptr = next_lhdr_ptr;
-  }
-
-  /* Release small objects */
-  shdr_ptr = mem->small_list[pool_id];
-  mem->small_list[pool_id] = NULL;
-
-  while (shdr_ptr != NULL) {
-    small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
-    space_freed = shdr_ptr->hdr.bytes_used +
-		  shdr_ptr->hdr.bytes_left +
-		  SIZEOF(small_pool_hdr);
-    jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
-    mem->total_space_allocated -= space_freed;
-    shdr_ptr = next_shdr_ptr;
-  }
-}
-
-
-/*
- * Close up shop entirely.
- * Note that this cannot be called unless cinfo->mem is non-NULL.
- */
-
-METHODDEF(void)
-self_destruct (j_common_ptr cinfo)
-{
-  int pool;
-
-  /* Close all backing store, release all memory.
-   * Releasing pools in reverse order might help avoid fragmentation
-   * with some (brain-damaged) malloc libraries.
-   */
-  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
-    free_pool(cinfo, pool);
-  }
-
-  /* Release the memory manager control block too. */
-  jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
-  cinfo->mem = NULL;		/* ensures I will be called only once */
-
-  jpeg_mem_term(cinfo);		/* system-dependent cleanup */
-}
-
-
-/*
- * Memory manager initialization.
- * When this is called, only the error manager pointer is valid in cinfo!
- */
-
-GLOBAL(void)
-jinit_memory_mgr (j_common_ptr cinfo)
-{
-  my_mem_ptr mem;
-  long max_to_use;
-  int pool;
-  size_t test_mac;
-
-  cinfo->mem = NULL;		/* for safety if init fails */
-
-  /* Check for configuration errors.
-   * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
-   * doesn't reflect any real hardware alignment requirement.
-   * The test is a little tricky: for X>0, X and X-1 have no one-bits
-   * in common if and only if X is a power of 2, ie has only one one-bit.
-   * Some compilers may give an "unreachable code" warning here; ignore it.
-   */
-  if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
-    ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
-  /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
-   * a multiple of SIZEOF(ALIGN_TYPE).
-   * Again, an "unreachable code" warning may be ignored here.
-   * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
-   */
-  test_mac = (size_t) MAX_ALLOC_CHUNK;
-  if ((long) test_mac != MAX_ALLOC_CHUNK ||
-      (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
-    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
-
-  max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
-
-  /* Attempt to allocate memory manager's control block */
-  mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
-
-  if (mem == NULL) {
-    jpeg_mem_term(cinfo);	/* system-dependent cleanup */
-    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
-  }
-
-  /* OK, fill in the method pointers */
-  mem->pub.alloc_small = alloc_small;
-  mem->pub.alloc_large = alloc_large;
-  mem->pub.alloc_sarray = alloc_sarray;
-  mem->pub.alloc_barray = alloc_barray;
-  mem->pub.request_virt_sarray = request_virt_sarray;
-  mem->pub.request_virt_barray = request_virt_barray;
-  mem->pub.realize_virt_arrays = realize_virt_arrays;
-  mem->pub.access_virt_sarray = access_virt_sarray;
-  mem->pub.access_virt_barray = access_virt_barray;
-  mem->pub.free_pool = free_pool;
-  mem->pub.self_destruct = self_destruct;
-
-  /* Make MAX_ALLOC_CHUNK accessible to other modules */
-  mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
-
-  /* Initialize working state */
-  mem->pub.max_memory_to_use = max_to_use;
-
-  for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
-    mem->small_list[pool] = NULL;
-    mem->large_list[pool] = NULL;
-  }
-  mem->virt_sarray_list = NULL;
-  mem->virt_barray_list = NULL;
-
-  mem->total_space_allocated = SIZEOF(my_memory_mgr);
-
-  /* Declare ourselves open for business */
-  cinfo->mem = & mem->pub;
-
-  /* Check for an environment variable JPEGMEM; if found, override the
-   * default max_memory setting from jpeg_mem_init.  Note that the
-   * surrounding application may again override this value.
-   * If your system doesn't support getenv(), define NO_GETENV to disable
-   * this feature.
-   */
-#ifndef NO_GETENV
-  { char * memenv;
-
-    if ((memenv = getenv("JPEGMEM")) != NULL) {
-      char ch = 'x';
-
-      if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
-	if (ch == 'm' || ch == 'M')
-	  max_to_use *= 1000L;
-	mem->pub.max_memory_to_use = max_to_use * 1000L;
-      }
-    }
-  }
-#endif
-
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemname.c ./Shared/jpeg-6b/jmemname.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemname.c	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemname.c	Wed Dec 31 19:00:00 1969
@@ -1,276 +0,0 @@
-/*
- * jmemname.c
- *
- * Copyright (C) 1992-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file provides a generic implementation of the system-dependent
- * portion of the JPEG memory manager.  This implementation assumes that
- * you must explicitly construct a name for each temp file.
- * Also, the problem of determining the amount of memory available
- * is shoved onto the user.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jmemsys.h"		/* import the system-dependent declarations */
-
-#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare malloc(),free() */
-extern void * malloc JPP((size_t size));
-extern void free JPP((void *ptr));
-#endif
-
-#ifndef SEEK_SET		/* pre-ANSI systems may not define this; */
-#define SEEK_SET  0		/* if not, assume 0 is correct */
-#endif
-
-#ifdef DONT_USE_B_MODE		/* define mode parameters for fopen() */
-#define READ_BINARY	"r"
-#define RW_BINARY	"w+"
-#else
-#ifdef VMS			/* VMS is very nonstandard */
-#define READ_BINARY	"rb", "ctx=stm"
-#define RW_BINARY	"w+b", "ctx=stm"
-#else				/* standard ANSI-compliant case */
-#define READ_BINARY	"rb"
-#define RW_BINARY	"w+b"
-#endif
-#endif
-
-
-/*
- * Selection of a file name for a temporary file.
- * This is system-dependent!
- *
- * The code as given is suitable for most Unix systems, and it is easily
- * modified for most non-Unix systems.  Some notes:
- *  1.  The temp file is created in the directory named by TEMP_DIRECTORY.
- *      The default value is /usr/tmp, which is the conventional place for
- *      creating large temp files on Unix.  On other systems you'll probably
- *      want to change the file location.  You can do this by editing the
- *      #define, or (preferred) by defining TEMP_DIRECTORY in jconfig.h.
- *
- *  2.  If you need to change the file name as well as its location,
- *      you can override the TEMP_FILE_NAME macro.  (Note that this is
- *      actually a printf format string; it must contain %s and %d.)
- *      Few people should need to do this.
- *
- *  3.  mktemp() is used to ensure that multiple processes running
- *      simultaneously won't select the same file names.  If your system
- *      doesn't have mktemp(), define NO_MKTEMP to do it the hard way.
- *      (If you don't have <errno.h>, also define NO_ERRNO_H.)
- *
- *  4.  You probably want to define NEED_SIGNAL_CATCHER so that cjpeg.c/djpeg.c
- *      will cause the temp files to be removed if you stop the program early.
- */
-
-#ifndef TEMP_DIRECTORY		/* can override from jconfig.h or Makefile */
-#define TEMP_DIRECTORY  "/usr/tmp/" /* recommended setting for Unix */
-#endif
-
-static int next_file_num;	/* to distinguish among several temp files */
-
-#ifdef NO_MKTEMP
-
-#ifndef TEMP_FILE_NAME		/* can override from jconfig.h or Makefile */
-#define TEMP_FILE_NAME  "%sJPG%03d.TMP"
-#endif
-
-#ifndef NO_ERRNO_H
-#include <errno.h>		/* to define ENOENT */
-#endif
-
-/* ANSI C specifies that errno is a macro, but on older systems it's more
- * likely to be a plain int variable.  And not all versions of errno.h
- * bother to declare it, so we have to in order to be most portable.  Thus:
- */
-#ifndef errno
-extern int errno;
-#endif
-
-
-LOCAL(void)
-select_file_name (char * fname)
-{
-  FILE * tfile;
-
-  /* Keep generating file names till we find one that's not in use */
-  for (;;) {
-    next_file_num++;		/* advance counter */
-    sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
-    if ((tfile = fopen(fname, READ_BINARY)) == NULL) {
-      /* fopen could have failed for a reason other than the file not
-       * being there; for example, file there but unreadable.
-       * If <errno.h> isn't available, then we cannot test the cause.
-       */
-#ifdef ENOENT
-      if (errno != ENOENT)
-	continue;
-#endif
-      break;
-    }
-    fclose(tfile);		/* oops, it's there; close tfile & try again */
-  }
-}
-
-#else /* ! NO_MKTEMP */
-
-/* Note that mktemp() requires the initial filename to end in six X's */
-#ifndef TEMP_FILE_NAME		/* can override from jconfig.h or Makefile */
-#define TEMP_FILE_NAME  "%sJPG%dXXXXXX"
-#endif
-
-LOCAL(void)
-select_file_name (char * fname)
-{
-  next_file_num++;		/* advance counter */
-  sprintf(fname, TEMP_FILE_NAME, TEMP_DIRECTORY, next_file_num);
-  mktemp(fname);		/* make sure file name is unique */
-  /* mktemp replaces the trailing XXXXXX with a unique string of characters */
-}
-
-#endif /* NO_MKTEMP */
-
-
-/*
- * Memory allocation and freeing are controlled by the regular library
- * routines malloc() and free().
- */
-
-GLOBAL(void *)
-jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void *) malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
-{
-  free(object);
-}
-
-
-/*
- * "Large" objects are treated the same as "small" ones.
- * NB: although we include FAR keywords in the routine declarations,
- * this file won't actually work in 80x86 small/medium model; at least,
- * you probably won't be able to process useful-size images in only 64KB.
- */
-
-GLOBAL(void FAR *)
-jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void FAR *) malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
-{
-  free(object);
-}
-
-
-/*
- * This routine computes the total memory space available for allocation.
- * It's impossible to do this in a portable way; our current solution is
- * to make the user tell us (with a default value set at compile time).
- * If you can actually get the available space, it's a good idea to subtract
- * a slop factor of 5% or so.
- */
-
-#ifndef DEFAULT_MAX_MEM		/* so can override from makefile */
-#define DEFAULT_MAX_MEM		1000000L /* default: one megabyte */
-#endif
-
-GLOBAL(long)
-jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
-		    long max_bytes_needed, long already_allocated)
-{
-  return cinfo->mem->max_memory_to_use - already_allocated;
-}
-
-
-/*
- * Backing store (temporary file) management.
- * Backing store objects are only used when the value returned by
- * jpeg_mem_available is less than the total space needed.  You can dispense
- * with these routines if you have plenty of virtual memory; see jmemnobs.c.
- */
-
-
-METHODDEF(void)
-read_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-		    void FAR * buffer_address,
-		    long file_offset, long byte_count)
-{
-  if (fseek(info->temp_file, file_offset, SEEK_SET))
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-  if (JFREAD(info->temp_file, buffer_address, byte_count)
-      != (size_t) byte_count)
-    ERREXIT(cinfo, JERR_TFILE_READ);
-}
-
-
-METHODDEF(void)
-write_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-		     void FAR * buffer_address,
-		     long file_offset, long byte_count)
-{
-  if (fseek(info->temp_file, file_offset, SEEK_SET))
-    ERREXIT(cinfo, JERR_TFILE_SEEK);
-  if (JFWRITE(info->temp_file, buffer_address, byte_count)
-      != (size_t) byte_count)
-    ERREXIT(cinfo, JERR_TFILE_WRITE);
-}
-
-
-METHODDEF(void)
-close_backing_store (j_common_ptr cinfo, backing_store_ptr info)
-{
-  fclose(info->temp_file);	/* close the file */
-  unlink(info->temp_name);	/* delete the file */
-/* If your system doesn't have unlink(), use remove() instead.
- * remove() is the ANSI-standard name for this function, but if
- * your system was ANSI you'd be using jmemansi.c, right?
- */
-  TRACEMSS(cinfo, 1, JTRC_TFILE_CLOSE, info->temp_name);
-}
-
-
-/*
- * Initial opening of a backing-store object.
- */
-
-GLOBAL(void)
-jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-			 long total_bytes_needed)
-{
-  select_file_name(info->temp_name);
-  if ((info->temp_file = fopen(info->temp_name, RW_BINARY)) == NULL)
-    ERREXITS(cinfo, JERR_TFILE_CREATE, info->temp_name);
-  info->read_backing_store = read_backing_store;
-  info->write_backing_store = write_backing_store;
-  info->close_backing_store = close_backing_store;
-  TRACEMSS(cinfo, 1, JTRC_TFILE_OPEN, info->temp_name);
-}
-
-
-/*
- * These routines take care of any system-dependent initialization and
- * cleanup required.
- */
-
-GLOBAL(long)
-jpeg_mem_init (j_common_ptr cinfo)
-{
-  next_file_num = 0;		/* initialize temp file name generator */
-  return DEFAULT_MAX_MEM;	/* default for max_memory_to_use */
-}
-
-GLOBAL(void)
-jpeg_mem_term (j_common_ptr cinfo)
-{
-  /* no work */
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemnobs.c ./Shared/jpeg-6b/jmemnobs.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemnobs.c	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemnobs.c	Wed Dec 31 19:00:00 1969
@@ -1,109 +0,0 @@
-/*
- * jmemnobs.c
- *
- * Copyright (C) 1992-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file provides a really simple implementation of the system-
- * dependent portion of the JPEG memory manager.  This implementation
- * assumes that no backing-store files are needed: all required space
- * can be obtained from malloc().
- * This is very portable in the sense that it'll compile on almost anything,
- * but you'd better have lots of main memory (or virtual memory) if you want
- * to process big images.
- * Note that the max_memory_to_use option is ignored by this implementation.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-#include "jmemsys.h"		/* import the system-dependent declarations */
-
-#ifndef HAVE_STDLIB_H		/* <stdlib.h> should declare malloc(),free() */
-extern void * malloc JPP((size_t size));
-extern void free JPP((void *ptr));
-#endif
-
-
-/*
- * Memory allocation and freeing are controlled by the regular library
- * routines malloc() and free().
- */
-
-GLOBAL(void *)
-jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void *) malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
-{
-  free(object);
-}
-
-
-/*
- * "Large" objects are treated the same as "small" ones.
- * NB: although we include FAR keywords in the routine declarations,
- * this file won't actually work in 80x86 small/medium model; at least,
- * you probably won't be able to process useful-size images in only 64KB.
- */
-
-GLOBAL(void FAR *)
-jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
-{
-  return (void FAR *) malloc(sizeofobject);
-}
-
-GLOBAL(void)
-jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
-{
-  free(object);
-}
-
-
-/*
- * This routine computes the total memory space available for allocation.
- * Here we always say, "we got all you want bud!"
- */
-
-GLOBAL(long)
-jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
-		    long max_bytes_needed, long already_allocated)
-{
-  return max_bytes_needed;
-}
-
-
-/*
- * Backing store (temporary file) management.
- * Since jpeg_mem_available always promised the moon,
- * this should never be called and we can just error out.
- */
-
-GLOBAL(void)
-jpeg_open_backing_store (j_common_ptr cinfo, backing_store_ptr info,
-			 long total_bytes_needed)
-{
-  ERREXIT(cinfo, JERR_NO_BACKING_STORE);
-}
-
-
-/*
- * These routines take care of any system-dependent initialization and
- * cleanup required.  Here, there isn't any.
- */
-
-GLOBAL(long)
-jpeg_mem_init (j_common_ptr cinfo)
-{
-  return 0;			/* just set max_memory_to_use to 0 */
-}
-
-GLOBAL(void)
-jpeg_mem_term (j_common_ptr cinfo)
-{
-  /* no work */
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmemsys.h ./Shared/jpeg-6b/jmemsys.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmemsys.h	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmemsys.h	Wed Dec 31 19:00:00 1969
@@ -1,198 +0,0 @@
-/*
- * jmemsys.h
- *
- * Copyright (C) 1992-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This include file defines the interface between the system-independent
- * and system-dependent portions of the JPEG memory manager.  No other
- * modules need include it.  (The system-independent portion is jmemmgr.c;
- * there are several different versions of the system-dependent portion.)
- *
- * This file works as-is for the system-dependent memory managers supplied
- * in the IJG distribution.  You may need to modify it if you write a
- * custom memory manager.  If system-dependent changes are needed in
- * this file, the best method is to #ifdef them based on a configuration
- * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR
- * and USE_MAC_MEMMGR.
- */
-
-
-/* Short forms of external names for systems with brain-damaged linkers. */
-
-#ifdef NEED_SHORT_EXTERNAL_NAMES
-#define jpeg_get_small		jGetSmall
-#define jpeg_free_small		jFreeSmall
-#define jpeg_get_large		jGetLarge
-#define jpeg_free_large		jFreeLarge
-#define jpeg_mem_available	jMemAvail
-#define jpeg_open_backing_store	jOpenBackStore
-#define jpeg_mem_init		jMemInit
-#define jpeg_mem_term		jMemTerm
-#endif /* NEED_SHORT_EXTERNAL_NAMES */
-
-
-/*
- * These two functions are used to allocate and release small chunks of
- * memory.  (Typically the total amount requested through jpeg_get_small is
- * no more than 20K or so; this will be requested in chunks of a few K each.)
- * Behavior should be the same as for the standard library functions malloc
- * and free; in particular, jpeg_get_small must return NULL on failure.
- * On most systems, these ARE malloc and free.  jpeg_free_small is passed the
- * size of the object being freed, just in case it's needed.
- * On an 80x86 machine using small-data memory model, these manage near heap.
- */
-
-EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
-EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
-				  size_t sizeofobject));
-
-/*
- * These two functions are used to allocate and release large chunks of
- * memory (up to the total free space designated by jpeg_mem_available).
- * The interface is the same as above, except that on an 80x86 machine,
- * far pointers are used.  On most other machines these are identical to
- * the jpeg_get/free_small routines; but we keep them separate anyway,
- * in case a different allocation strategy is desirable for large chunks.
- */
-
-EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
-				       size_t sizeofobject));
-EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
-				  size_t sizeofobject));
-
-/*
- * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
- * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
- * matter, but that case should never come into play).  This macro is needed
- * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
- * On those machines, we expect that jconfig.h will provide a proper value.
- * On machines with 32-bit flat address spaces, any large constant may be used.
- *
- * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
- * size_t and will be a multiple of sizeof(align_type).
- */
-
-#ifndef MAX_ALLOC_CHUNK		/* may be overridden in jconfig.h */
-#define MAX_ALLOC_CHUNK  1000000000L
-#endif
-
-/*
- * This routine computes the total space still available for allocation by
- * jpeg_get_large.  If more space than this is needed, backing store will be
- * used.  NOTE: any memory already allocated must not be counted.
- *
- * There is a minimum space requirement, corresponding to the minimum
- * feasible buffer sizes; jmemmgr.c will request that much space even if
- * jpeg_mem_available returns zero.  The maximum space needed, enough to hold
- * all working storage in memory, is also passed in case it is useful.
- * Finally, the total space already allocated is passed.  If no better
- * method is available, cinfo->mem->max_memory_to_use - already_allocated
- * is often a suitable calculation.
- *
- * It is OK for jpeg_mem_available to underestimate the space available
- * (that'll just lead to more backing-store access than is really necessary).
- * However, an overestimate will lead to failure.  Hence it's wise to subtract
- * a slop factor from the true available space.  5% should be enough.
- *
- * On machines with lots of virtual memory, any large constant may be returned.
- * Conversely, zero may be returned to always use the minimum amount of memory.
- */
-
-EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
-				     long min_bytes_needed,
-				     long max_bytes_needed,
-				     long already_allocated));
-
-
-/*
- * This structure holds whatever state is needed to access a single
- * backing-store object.  The read/write/close method pointers are called
- * by jmemmgr.c to manipulate the backing-store object; all other fields
- * are private to the system-dependent backing store routines.
- */
-
-#define TEMP_NAME_LENGTH   64	/* max length of a temporary file's name */
-
-
-#ifdef USE_MSDOS_MEMMGR		/* DOS-specific junk */
-
-typedef unsigned short XMSH;	/* type of extended-memory handles */
-typedef unsigned short EMSH;	/* type of expanded-memory handles */
-
-typedef union {
-  short file_handle;		/* DOS file handle if it's a temp file */
-  XMSH xms_handle;		/* handle if it's a chunk of XMS */
-  EMSH ems_handle;		/* handle if it's a chunk of EMS */
-} handle_union;
-
-#endif /* USE_MSDOS_MEMMGR */
-
-#ifdef USE_MAC_MEMMGR		/* Mac-specific junk */
-#include <Files.h>
-#endif /* USE_MAC_MEMMGR */
-
-
-typedef struct backing_store_struct * backing_store_ptr;
-
-typedef struct backing_store_struct {
-  /* Methods for reading/writing/closing this backing-store object */
-  JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
-				     backing_store_ptr info,
-				     void FAR * buffer_address,
-				     long file_offset, long byte_count));
-  JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
-				      backing_store_ptr info,
-				      void FAR * buffer_address,
-				      long file_offset, long byte_count));
-  JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
-				      backing_store_ptr info));
-
-  /* Private fields for system-dependent backing-store management */
-#ifdef USE_MSDOS_MEMMGR
-  /* For the MS-DOS manager (jmemdos.c), we need: */
-  handle_union handle;		/* reference to backing-store storage object */
-  char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
-#else
-#ifdef USE_MAC_MEMMGR
-  /* For the Mac manager (jmemmac.c), we need: */
-  short temp_file;		/* file reference number to temp file */
-  FSSpec tempSpec;		/* the FSSpec for the temp file */
-  char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
-#else
-  /* For a typical implementation with temp files, we need: */
-  FILE * temp_file;		/* stdio reference to temp file */
-  char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
-#endif
-#endif
-} backing_store_info;
-
-
-/*
- * Initial opening of a backing-store object.  This must fill in the
- * read/write/close pointers in the object.  The read/write routines
- * may take an error exit if the specified maximum file size is exceeded.
- * (If jpeg_mem_available always returns a large value, this routine can
- * just take an error exit.)
- */
-
-EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
-					  backing_store_ptr info,
-					  long total_bytes_needed));
-
-
-/*
- * These routines take care of any system-dependent initialization and
- * cleanup required.  jpeg_mem_init will be called before anything is
- * allocated (and, therefore, nothing in cinfo is of use except the error
- * manager pointer).  It should return a suitable default value for
- * max_memory_to_use; this may subsequently be overridden by the surrounding
- * application.  (Note that max_memory_to_use is only important if
- * jpeg_mem_available chooses to consult it ... no one else will.)
- * jpeg_mem_term may assume that all requested memory has been freed and that
- * all opened backing-store objects have been closed.
- */
-
-EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
-EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jmorecfg.h ./Shared/jpeg-6b/jmorecfg.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jmorecfg.h	Mon Dec  1 12:30:38 2003
+++ ./Shared/jpeg-6b/jmorecfg.h	Wed Dec 31 19:00:00 1969
@@ -1,363 +0,0 @@
-/*
- * jmorecfg.h
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains additional configuration options that customize the
- * JPEG software for special applications or support machine-dependent
- * optimizations.  Most users will not need to touch this file.
- */
-
-
-/*
- * Define BITS_IN_JSAMPLE as either
- *   8   for 8-bit sample values (the usual setting)
- *   12  for 12-bit sample values
- * Only 8 and 12 are legal data precisions for lossy JPEG according to the
- * JPEG standard, and the IJG code does not support anything else!
- * We do not support run-time selection of data precision, sorry.
- */
-
-#define BITS_IN_JSAMPLE  8	/* use 8 or 12 */
-
-
-/*
- * Maximum number of components (color channels) allowed in JPEG image.
- * To meet the letter of the JPEG spec, set this to 255.  However, darn
- * few applications need more than 4 channels (maybe 5 for CMYK + alpha
- * mask).  We recommend 10 as a reasonable compromise; use 4 if you are
- * really short on memory.  (Each allowed component costs a hundred or so
- * bytes of storage, whether actually used in an image or not.)
- */
-
-#define MAX_COMPONENTS  10	/* maximum number of image components */
-
-
-/*
- * Basic data types.
- * You may need to change these if you have a machine with unusual data
- * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
- * or "long" not 32 bits.  We don't care whether "int" is 16 or 32 bits,
- * but it had better be at least 16.
- */
-
-/* Representation of a single sample (pixel element value).
- * We frequently allocate large arrays of these, so it's important to keep
- * them small.  But if you have memory to burn and access to char or short
- * arrays is very slow on your hardware, you might want to change these.
- */
-
-#if BITS_IN_JSAMPLE == 8
-/* JSAMPLE should be the smallest type that will hold the values 0..255.
- * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
- */
-
-#ifdef HAVE_UNSIGNED_CHAR
-
-typedef unsigned char JSAMPLE;
-#define GETJSAMPLE(value)  ((int) (value))
-
-#else /* not HAVE_UNSIGNED_CHAR */
-
-typedef char JSAMPLE;
-#ifdef CHAR_IS_UNSIGNED
-#define GETJSAMPLE(value)  ((int) (value))
-#else
-#define GETJSAMPLE(value)  ((int) (value) & 0xFF)
-#endif /* CHAR_IS_UNSIGNED */
-
-#endif /* HAVE_UNSIGNED_CHAR */
-
-#define MAXJSAMPLE	255
-#define CENTERJSAMPLE	128
-
-#endif /* BITS_IN_JSAMPLE == 8 */
-
-
-#if BITS_IN_JSAMPLE == 12
-/* JSAMPLE should be the smallest type that will hold the values 0..4095.
- * On nearly all machines "short" will do nicely.
- */
-
-typedef short JSAMPLE;
-#define GETJSAMPLE(value)  ((int) (value))
-
-#define MAXJSAMPLE	4095
-#define CENTERJSAMPLE	2048
-
-#endif /* BITS_IN_JSAMPLE == 12 */
-
-
-/* Representation of a DCT frequency coefficient.
- * This should be a signed value of at least 16 bits; "short" is usually OK.
- * Again, we allocate large arrays of these, but you can change to int
- * if you have memory to burn and "short" is really slow.
- */
-
-typedef short JCOEF;
-
-
-/* Compressed datastreams are represented as arrays of JOCTET.
- * These must be EXACTLY 8 bits wide, at least once they are written to
- * external storage.  Note that when using the stdio data source/destination
- * managers, this is also the data type passed to fread/fwrite.
- */
-
-#ifdef HAVE_UNSIGNED_CHAR
-
-typedef unsigned char JOCTET;
-#define GETJOCTET(value)  (value)
-
-#else /* not HAVE_UNSIGNED_CHAR */
-
-typedef char JOCTET;
-#ifdef CHAR_IS_UNSIGNED
-#define GETJOCTET(value)  (value)
-#else
-#define GETJOCTET(value)  ((value) & 0xFF)
-#endif /* CHAR_IS_UNSIGNED */
-
-#endif /* HAVE_UNSIGNED_CHAR */
-
-
-/* These typedefs are used for various table entries and so forth.
- * They must be at least as wide as specified; but making them too big
- * won't cost a huge amount of memory, so we don't provide special
- * extraction code like we did for JSAMPLE.  (In other words, these
- * typedefs live at a different point on the speed/space tradeoff curve.)
- */
-
-/* UINT8 must hold at least the values 0..255. */
-
-#ifdef HAVE_UNSIGNED_CHAR
-typedef unsigned char UINT8;
-#else /* not HAVE_UNSIGNED_CHAR */
-#ifdef CHAR_IS_UNSIGNED
-typedef char UINT8;
-#else /* not CHAR_IS_UNSIGNED */
-typedef short UINT8;
-#endif /* CHAR_IS_UNSIGNED */
-#endif /* HAVE_UNSIGNED_CHAR */
-
-/* UINT16 must hold at least the values 0..65535. */
-
-#ifdef HAVE_UNSIGNED_SHORT
-typedef unsigned short UINT16;
-#else /* not HAVE_UNSIGNED_SHORT */
-typedef unsigned int UINT16;
-#endif /* HAVE_UNSIGNED_SHORT */
-
-/* INT16 must hold at least the values -32768..32767. */
-
-#ifndef XMD_H			/* X11/xmd.h correctly defines INT16 */
-typedef short INT16;
-#endif
-
-/* INT32 must hold at least signed 32-bit values. */
-
-#ifndef XMD_H			/* X11/xmd.h correctly defines INT32 */
-typedef long INT32;
-#endif
-
-/* Datatype used for image dimensions.  The JPEG standard only supports
- * images up to 64K*64K due to 16-bit fields in SOF markers.  Therefore
- * "unsigned int" is sufficient on all machines.  However, if you need to
- * handle larger images and you don't mind deviating from the spec, you
- * can change this datatype.
- */
-
-typedef unsigned int JDIMENSION;
-
-#define JPEG_MAX_DIMENSION  65500L  /* a tad under 64K to prevent overflows */
-
-
-/* These macros are used in all function definitions and extern declarations.
- * You could modify them if you need to change function linkage conventions;
- * in particular, you'll need to do that to make the library a Windows DLL.
- * Another application is to make all functions global for use with debuggers
- * or code profilers that require it.
- */
-
-/* a function called through method pointers: */
-#define METHODDEF(type)		static type
-/* a function used only in its module: */
-#define LOCAL(type)		static type
-/* a function referenced thru EXTERNs: */
-#define GLOBAL(type)		type
-/* a reference to a GLOBAL function: */
-#define EXTERN(type)		extern type
-
-
-/* This macro is used to declare a "method", that is, a function pointer.
- * We want to supply prototype parameters if the compiler can cope.
- * Note that the arglist parameter must be parenthesized!
- * Again, you can customize this if you need special linkage keywords.
- */
-
-#ifdef HAVE_PROTOTYPES
-#define JMETHOD(type,methodname,arglist)  type (*methodname) arglist
-#else
-#define JMETHOD(type,methodname,arglist)  type (*methodname) ()
-#endif
-
-
-/* Here is the pseudo-keyword for declaring pointers that must be "far"
- * on 80x86 machines.  Most of the specialized coding for 80x86 is handled
- * by just saying "FAR *" where such a pointer is needed.  In a few places
- * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
- */
-
-#ifdef NEED_FAR_POINTERS
-#define FAR  far
-#else
-#define FAR
-#endif
-
-
-/*
- * On a few systems, type boolean and/or its values FALSE, TRUE may appear
- * in standard header files.  Or you may have conflicts with application-
- * specific header files that you want to include together with these files.
- * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
- */
-
-#ifndef HAVE_BOOLEAN
-typedef int boolean;
-#endif
-#ifndef FALSE			/* in case these macros already exist */
-#define FALSE	0		/* values of boolean */
-#endif
-#ifndef TRUE
-#define TRUE	1
-#endif
-
-
-/*
- * The remaining options affect code selection within the JPEG library,
- * but they don't need to be visible to most applications using the library.
- * To minimize application namespace pollution, the symbols won't be
- * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
- */
-
-#ifdef JPEG_INTERNALS
-#define JPEG_INTERNAL_OPTIONS
-#endif
-
-#ifdef JPEG_INTERNAL_OPTIONS
-
-
-/*
- * These defines indicate whether to include various optional functions.
- * Undefining some of these symbols will produce a smaller but less capable
- * library.  Note that you can leave certain source files out of the
- * compilation/linking process if you've #undef'd the corresponding symbols.
- * (You may HAVE to do that if your compiler doesn't like null source files.)
- */
-
-/* Arithmetic coding is unsupported for legal reasons.  Complaints to IBM. */
-
-/* Capability options common to encoder and decoder: */
-
-#define DCT_ISLOW_SUPPORTED	/* slow but accurate integer algorithm */
-#define DCT_IFAST_SUPPORTED	/* faster, less accurate integer method */
-#define DCT_FLOAT_SUPPORTED	/* floating-point: accurate, fast on fast HW */
-
-/* Encoder capability options: */
-
-#undef  C_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
-#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
-#define C_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
-#define ENTROPY_OPT_SUPPORTED	    /* Optimization of entropy coding parms? */
-/* Note: if you selected 12-bit data precision, it is dangerous to turn off
- * ENTROPY_OPT_SUPPORTED.  The standard Huffman tables are only good for 8-bit
- * precision, so jchuff.c normally uses entropy optimization to compute
- * usable tables for higher precision.  If you don't want to do optimization,
- * you'll have to supply different default Huffman tables.
- * The exact same statements apply for progressive JPEG: the default tables
- * don't work for progressive mode.  (This may get fixed, however.)
- */
-#define INPUT_SMOOTHING_SUPPORTED   /* Input image smoothing option? */
-
-/* Decoder capability options: */
-
-#undef  D_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
-#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
-#define D_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
-#define SAVE_MARKERS_SUPPORTED	    /* jpeg_save_markers() needed? */
-#define BLOCK_SMOOTHING_SUPPORTED   /* Block smoothing? (Progressive only) */
-#define IDCT_SCALING_SUPPORTED	    /* Output rescaling via IDCT? */
-#undef  UPSAMPLE_SCALING_SUPPORTED  /* Output rescaling at upsample stage? */
-#define UPSAMPLE_MERGING_SUPPORTED  /* Fast path for sloppy upsampling? */
-#define QUANT_1PASS_SUPPORTED	    /* 1-pass color quantization? */
-#define QUANT_2PASS_SUPPORTED	    /* 2-pass color quantization? */
-
-/* more capability options later, no doubt */
-
-
-/*
- * Ordering of RGB data in scanlines passed to or from the application.
- * If your application wants to deal with data in the order B,G,R, just
- * change these macros.  You can also deal with formats such as R,G,B,X
- * (one extra byte per pixel) by changing RGB_PIXELSIZE.  Note that changing
- * the offsets will also change the order in which colormap data is organized.
- * RESTRICTIONS:
- * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
- * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
- *    useful if you are using JPEG color spaces other than YCbCr or grayscale.
- * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
- *    is not 3 (they don't understand about dummy color components!).  So you
- *    can't use color quantization if you change that value.
- */
-
-#define RGB_RED		0	/* Offset of Red in an RGB scanline element */
-#define RGB_GREEN	1	/* Offset of Green */
-#define RGB_BLUE	2	/* Offset of Blue */
-#define RGB_PIXELSIZE	3	/* JSAMPLEs per RGB scanline element */
-
-
-/* Definitions for speed-related optimizations. */
-
-
-/* If your compiler supports inline functions, define INLINE
- * as the inline keyword; otherwise define it as empty.
- */
-
-#ifndef INLINE
-#ifdef __GNUC__			/* for instance, GNU C knows about inline */
-#define INLINE __inline__
-#endif
-#ifndef INLINE
-#define INLINE			/* default is to define it as empty */
-#endif
-#endif
-
-
-/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
- * two 16-bit shorts is faster than multiplying two ints.  Define MULTIPLIER
- * as short on such a machine.  MULTIPLIER must be at least 16 bits wide.
- */
-
-#ifndef MULTIPLIER
-#define MULTIPLIER  int		/* type for fastest integer multiply */
-#endif
-
-
-/* FAST_FLOAT should be either float or double, whichever is done faster
- * by your compiler.  (Note that this type is only used in the floating point
- * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
- * Typically, float is faster in ANSI C compilers, while double is faster in
- * pre-ANSI compilers (because they insist on converting to double anyway).
- * The code below therefore chooses float if we have ANSI-style prototypes.
- */
-
-#ifndef FAST_FLOAT
-#ifdef HAVE_PROTOTYPES
-#define FAST_FLOAT  float
-#else
-#define FAST_FLOAT  double
-#endif
-#endif
-
-#endif /* JPEG_INTERNAL_OPTIONS */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jpeg_mem_dest.c ./Shared/jpeg-6b/jpeg_mem_dest.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jpeg_mem_dest.c	Tue Dec  2 01:59:58 2003
+++ ./Shared/jpeg-6b/jpeg_mem_dest.c	Wed Dec 31 19:00:00 1969
@@ -1,76 +0,0 @@
-//
-// Copyright 2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#include <stdio.h>
-#include "jpeglib.h"
-#include "jerror.h"
-
-typedef struct {
-	struct jpeg_destination_mgr pub;
-	JOCTET *buf;
-	size_t bufsize;
-	size_t jpegsize;
-} mem_destination_mgr;
-
-typedef mem_destination_mgr *mem_dest_ptr;
-
-METHODDEF(void) init_destination (j_compress_ptr cinfo)
-{
-	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
-
-	dest->pub.next_output_byte = dest->buf;
-	dest->pub.free_in_buffer = dest->bufsize;
-	dest->jpegsize = 0;
-}
-
-METHODDEF(boolean) empty_output_buffer (j_compress_ptr cinfo)
-{
-	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
-  
-	dest->pub.next_output_byte = dest->buf;
-	dest->pub.free_in_buffer = dest->bufsize;
-
-	return FALSE;
-	ERREXIT(cinfo, JERR_BUFFER_SIZE);
-}
-
-METHODDEF(void) term_destination(j_compress_ptr cinfo)
-{
-	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
-	dest->jpegsize = dest->bufsize - dest->pub.free_in_buffer;
-}
-
-GLOBAL(void) jpeg_mem_dest (j_compress_ptr cinfo, JOCTET* buf, size_t bufsize)
-{
-	mem_dest_ptr dest;
-
-	if (cinfo->dest == NULL) {
-		cinfo->dest = (struct jpeg_destination_mgr *)
-			(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
-																	sizeof(mem_destination_mgr));
-	}
-
-	dest = (mem_dest_ptr) cinfo->dest;
-
-	dest->pub.init_destination    = init_destination;
-	dest->pub.empty_output_buffer = empty_output_buffer;
-	dest->pub.term_destination    = term_destination;
-
-	dest->buf      = buf;
-	dest->bufsize  = bufsize;
-	dest->jpegsize = 0;
-}
-
-GLOBAL(int) jpeg_mem_size(j_compress_ptr cinfo)
-{
-	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
-	return dest->jpegsize;
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jpeg_mem_dest.cc ./Shared/jpeg-6b/jpeg_mem_dest.cc
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jpeg_mem_dest.cc	Wed Dec 31 19:00:00 1969
+++ ./Shared/jpeg-6b/jpeg_mem_dest.cc	Wed Jun  1 01:47:52 2005
@@ -0,0 +1,85 @@
+//
+// Copyright 2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#include <stdio.h>
+#include "jpeg_mem_dest.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <jerror.h>
+
+typedef struct {
+	struct jpeg_destination_mgr pub;
+	JOCTET *buf;
+	size_t bufsize;
+	size_t jpegsize;
+} mem_destination_mgr;
+
+typedef mem_destination_mgr *mem_dest_ptr;
+
+METHODDEF(void) init_destination (j_compress_ptr cinfo)
+{
+	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
+
+	dest->pub.next_output_byte = dest->buf;
+	dest->pub.free_in_buffer = dest->bufsize;
+	dest->jpegsize = 0;
+}
+
+METHODDEF(boolean) empty_output_buffer (j_compress_ptr cinfo)
+{
+	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
+  
+	dest->pub.next_output_byte = dest->buf;
+	dest->pub.free_in_buffer = dest->bufsize;
+
+	return FALSE;
+	ERREXIT(cinfo, JERR_BUFFER_SIZE);
+}
+
+METHODDEF(void) term_destination(j_compress_ptr cinfo)
+{
+	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
+	dest->jpegsize = dest->bufsize - dest->pub.free_in_buffer;
+}
+
+GLOBAL(void) jpeg_mem_dest (j_compress_ptr cinfo, JOCTET* buf, size_t bufsize)
+{
+	mem_dest_ptr dest;
+
+	if (cinfo->dest == NULL) {
+		cinfo->dest = (struct jpeg_destination_mgr *)
+			(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
+																	sizeof(mem_destination_mgr));
+	}
+
+	dest = (mem_dest_ptr) cinfo->dest;
+
+	dest->pub.init_destination    = init_destination;
+	dest->pub.empty_output_buffer = empty_output_buffer;
+	dest->pub.term_destination    = term_destination;
+
+	dest->buf      = buf;
+	dest->bufsize  = bufsize;
+	dest->jpegsize = 0;
+}
+
+GLOBAL(int) jpeg_mem_size(j_compress_ptr cinfo)
+{
+	mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
+	return dest->jpegsize;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jpeg_mem_dest.h ./Shared/jpeg-6b/jpeg_mem_dest.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jpeg_mem_dest.h	Tue Dec  2 01:59:58 2003
+++ ./Shared/jpeg-6b/jpeg_mem_dest.h	Wed Jun  1 01:47:52 2005
@@ -15,6 +15,8 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
+#include <jpeglib.h>
+	
 	void jpeg_mem_dest(j_compress_ptr cinfo, JOCTET* buf, size_t bufsize);
 	int  jpeg_mem_size(j_compress_ptr cinfo);
 #ifdef __cplusplus
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jpegint.h ./Shared/jpeg-6b/jpegint.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jpegint.h	Mon Dec  1 12:30:39 2003
+++ ./Shared/jpeg-6b/jpegint.h	Wed Dec 31 19:00:00 1969
@@ -1,392 +0,0 @@
-/*
- * jpegint.h
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file provides common declarations for the various JPEG modules.
- * These declarations are considered internal to the JPEG library; most
- * applications using the library shouldn't need to include this file.
- */
-
-
-/* Declarations for both compression & decompression */
-
-typedef enum {			/* Operating modes for buffer controllers */
-	JBUF_PASS_THRU,		/* Plain stripwise operation */
-	/* Remaining modes require a full-image buffer to have been created */
-	JBUF_SAVE_SOURCE,	/* Run source subobject only, save output */
-	JBUF_CRANK_DEST,	/* Run dest subobject only, using saved data */
-	JBUF_SAVE_AND_PASS	/* Run both subobjects, save output */
-} J_BUF_MODE;
-
-/* Values of global_state field (jdapi.c has some dependencies on ordering!) */
-#define CSTATE_START	100	/* after create_compress */
-#define CSTATE_SCANNING	101	/* start_compress done, write_scanlines OK */
-#define CSTATE_RAW_OK	102	/* start_compress done, write_raw_data OK */
-#define CSTATE_WRCOEFS	103	/* jpeg_write_coefficients done */
-#define DSTATE_START	200	/* after create_decompress */
-#define DSTATE_INHEADER	201	/* reading header markers, no SOS yet */
-#define DSTATE_READY	202	/* found SOS, ready for start_decompress */
-#define DSTATE_PRELOAD	203	/* reading multiscan file in start_decompress*/
-#define DSTATE_PRESCAN	204	/* performing dummy pass for 2-pass quant */
-#define DSTATE_SCANNING	205	/* start_decompress done, read_scanlines OK */
-#define DSTATE_RAW_OK	206	/* start_decompress done, read_raw_data OK */
-#define DSTATE_BUFIMAGE	207	/* expecting jpeg_start_output */
-#define DSTATE_BUFPOST	208	/* looking for SOS/EOI in jpeg_finish_output */
-#define DSTATE_RDCOEFS	209	/* reading file in jpeg_read_coefficients */
-#define DSTATE_STOPPING	210	/* looking for EOI in jpeg_finish_decompress */
-
-
-/* Declarations for compression modules */
-
-/* Master control module */
-struct jpeg_comp_master {
-  JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
-  JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
-  JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
-
-  /* State variables made visible to other modules */
-  boolean call_pass_startup;	/* True if pass_startup must be called */
-  boolean is_last_pass;		/* True during last pass */
-};
-
-/* Main buffer control (downsampled-data buffer) */
-struct jpeg_c_main_controller {
-  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
-  JMETHOD(void, process_data, (j_compress_ptr cinfo,
-			       JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
-			       JDIMENSION in_rows_avail));
-};
-
-/* Compression preprocessing (downsampling input buffer control) */
-struct jpeg_c_prep_controller {
-  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
-  JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
-				   JSAMPARRAY input_buf,
-				   JDIMENSION *in_row_ctr,
-				   JDIMENSION in_rows_avail,
-				   JSAMPIMAGE output_buf,
-				   JDIMENSION *out_row_group_ctr,
-				   JDIMENSION out_row_groups_avail));
-};
-
-/* Coefficient buffer control */
-struct jpeg_c_coef_controller {
-  JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
-  JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
-				   JSAMPIMAGE input_buf));
-};
-
-/* Colorspace conversion */
-struct jpeg_color_converter {
-  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
-  JMETHOD(void, color_convert, (j_compress_ptr cinfo,
-				JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
-				JDIMENSION output_row, int num_rows));
-};
-
-/* Downsampling */
-struct jpeg_downsampler {
-  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
-  JMETHOD(void, downsample, (j_compress_ptr cinfo,
-			     JSAMPIMAGE input_buf, JDIMENSION in_row_index,
-			     JSAMPIMAGE output_buf,
-			     JDIMENSION out_row_group_index));
-
-  boolean need_context_rows;	/* TRUE if need rows above & below */
-};
-
-/* Forward DCT (also controls coefficient quantization) */
-struct jpeg_forward_dct {
-  JMETHOD(void, start_pass, (j_compress_ptr cinfo));
-  /* perhaps this should be an array??? */
-  JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
-			      jpeg_component_info * compptr,
-			      JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
-			      JDIMENSION start_row, JDIMENSION start_col,
-			      JDIMENSION num_blocks));
-};
-
-/* Entropy encoding */
-struct jpeg_entropy_encoder {
-  JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
-  JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
-  JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
-};
-
-/* Marker writing */
-struct jpeg_marker_writer {
-  JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
-  JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
-  JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
-  JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
-  JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
-  /* These routines are exported to allow insertion of extra markers */
-  /* Probably only COM and APPn markers should be written this way */
-  JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
-				      unsigned int datalen));
-  JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
-};
-
-
-/* Declarations for decompression modules */
-
-/* Master control module */
-struct jpeg_decomp_master {
-  JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
-  JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
-
-  /* State variables made visible to other modules */
-  boolean is_dummy_pass;	/* True during 1st pass for 2-pass quant */
-};
-
-/* Input control module */
-struct jpeg_input_controller {
-  JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
-  JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
-  JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
-  JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
-
-  /* State variables made visible to other modules */
-  boolean has_multiple_scans;	/* True if file has multiple scans */
-  boolean eoi_reached;		/* True when EOI has been consumed */
-};
-
-/* Main buffer control (downsampled-data buffer) */
-struct jpeg_d_main_controller {
-  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
-  JMETHOD(void, process_data, (j_decompress_ptr cinfo,
-			       JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
-			       JDIMENSION out_rows_avail));
-};
-
-/* Coefficient buffer control */
-struct jpeg_d_coef_controller {
-  JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
-  JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
-  JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
-  JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
-				 JSAMPIMAGE output_buf));
-  /* Pointer to array of coefficient virtual arrays, or NULL if none */
-  jvirt_barray_ptr *coef_arrays;
-};
-
-/* Decompression postprocessing (color quantization buffer control) */
-struct jpeg_d_post_controller {
-  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
-  JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
-				    JSAMPIMAGE input_buf,
-				    JDIMENSION *in_row_group_ctr,
-				    JDIMENSION in_row_groups_avail,
-				    JSAMPARRAY output_buf,
-				    JDIMENSION *out_row_ctr,
-				    JDIMENSION out_rows_avail));
-};
-
-/* Marker reading & parsing */
-struct jpeg_marker_reader {
-  JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
-  /* Read markers until SOS or EOI.
-   * Returns same codes as are defined for jpeg_consume_input:
-   * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
-   */
-  JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
-  /* Read a restart marker --- exported for use by entropy decoder only */
-  jpeg_marker_parser_method read_restart_marker;
-
-  /* State of marker reader --- nominally internal, but applications
-   * supplying COM or APPn handlers might like to know the state.
-   */
-  boolean saw_SOI;		/* found SOI? */
-  boolean saw_SOF;		/* found SOF? */
-  int next_restart_num;		/* next restart number expected (0-7) */
-  unsigned int discarded_bytes;	/* # of bytes skipped looking for a marker */
-};
-
-/* Entropy decoding */
-struct jpeg_entropy_decoder {
-  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
-  JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
-				JBLOCKROW *MCU_data));
-
-  /* This is here to share code between baseline and progressive decoders; */
-  /* other modules probably should not use it */
-  boolean insufficient_data;	/* set TRUE after emitting warning */
-};
-
-/* Inverse DCT (also performs dequantization) */
-typedef JMETHOD(void, inverse_DCT_method_ptr,
-		(j_decompress_ptr cinfo, jpeg_component_info * compptr,
-		 JCOEFPTR coef_block,
-		 JSAMPARRAY output_buf, JDIMENSION output_col));
-
-struct jpeg_inverse_dct {
-  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
-  /* It is useful to allow each component to have a separate IDCT method. */
-  inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
-};
-
-/* Upsampling (note that upsampler must also call color converter) */
-struct jpeg_upsampler {
-  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
-  JMETHOD(void, upsample, (j_decompress_ptr cinfo,
-			   JSAMPIMAGE input_buf,
-			   JDIMENSION *in_row_group_ctr,
-			   JDIMENSION in_row_groups_avail,
-			   JSAMPARRAY output_buf,
-			   JDIMENSION *out_row_ctr,
-			   JDIMENSION out_rows_avail));
-
-  boolean need_context_rows;	/* TRUE if need rows above & below */
-};
-
-/* Colorspace conversion */
-struct jpeg_color_deconverter {
-  JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
-  JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
-				JSAMPIMAGE input_buf, JDIMENSION input_row,
-				JSAMPARRAY output_buf, int num_rows));
-};
-
-/* Color quantization or color precision reduction */
-struct jpeg_color_quantizer {
-  JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
-  JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
-				 JSAMPARRAY input_buf, JSAMPARRAY output_buf,
-				 int num_rows));
-  JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
-  JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
-};
-
-
-/* Miscellaneous useful macros */
-
-#undef MAX
-#define MAX(a,b)	((a) > (b) ? (a) : (b))
-#undef MIN
-#define MIN(a,b)	((a) < (b) ? (a) : (b))
-
-
-/* We assume that right shift corresponds to signed division by 2 with
- * rounding towards minus infinity.  This is correct for typical "arithmetic
- * shift" instructions that shift in copies of the sign bit.  But some
- * C compilers implement >> with an unsigned shift.  For these machines you
- * must define RIGHT_SHIFT_IS_UNSIGNED.
- * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
- * It is only applied with constant shift counts.  SHIFT_TEMPS must be
- * included in the variables of any routine using RIGHT_SHIFT.
- */
-
-#ifdef RIGHT_SHIFT_IS_UNSIGNED
-#define SHIFT_TEMPS	INT32 shift_temp;
-#define RIGHT_SHIFT(x,shft)  \
-	((shift_temp = (x)) < 0 ? \
-	 (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
-	 (shift_temp >> (shft)))
-#else
-#define SHIFT_TEMPS
-#define RIGHT_SHIFT(x,shft)	((x) >> (shft))
-#endif
-
-
-/* Short forms of external names for systems with brain-damaged linkers. */
-
-#ifdef NEED_SHORT_EXTERNAL_NAMES
-#define jinit_compress_master	jICompress
-#define jinit_c_master_control	jICMaster
-#define jinit_c_main_controller	jICMainC
-#define jinit_c_prep_controller	jICPrepC
-#define jinit_c_coef_controller	jICCoefC
-#define jinit_color_converter	jICColor
-#define jinit_downsampler	jIDownsampler
-#define jinit_forward_dct	jIFDCT
-#define jinit_huff_encoder	jIHEncoder
-#define jinit_phuff_encoder	jIPHEncoder
-#define jinit_marker_writer	jIMWriter
-#define jinit_master_decompress	jIDMaster
-#define jinit_d_main_controller	jIDMainC
-#define jinit_d_coef_controller	jIDCoefC
-#define jinit_d_post_controller	jIDPostC
-#define jinit_input_controller	jIInCtlr
-#define jinit_marker_reader	jIMReader
-#define jinit_huff_decoder	jIHDecoder
-#define jinit_phuff_decoder	jIPHDecoder
-#define jinit_inverse_dct	jIIDCT
-#define jinit_upsampler		jIUpsampler
-#define jinit_color_deconverter	jIDColor
-#define jinit_1pass_quantizer	jI1Quant
-#define jinit_2pass_quantizer	jI2Quant
-#define jinit_merged_upsampler	jIMUpsampler
-#define jinit_memory_mgr	jIMemMgr
-#define jdiv_round_up		jDivRound
-#define jround_up		jRound
-#define jcopy_sample_rows	jCopySamples
-#define jcopy_block_row		jCopyBlocks
-#define jzero_far		jZeroFar
-#define jpeg_zigzag_order	jZIGTable
-#define jpeg_natural_order	jZAGTable
-#endif /* NEED_SHORT_EXTERNAL_NAMES */
-
-
-/* Compression module initialization routines */
-EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
-EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
-					 boolean transcode_only));
-EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
-					  boolean need_full_buffer));
-EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
-					  boolean need_full_buffer));
-EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
-					  boolean need_full_buffer));
-EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
-EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
-EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
-EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
-EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
-EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
-/* Decompression module initialization routines */
-EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
-					  boolean need_full_buffer));
-EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
-					  boolean need_full_buffer));
-EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
-					  boolean need_full_buffer));
-EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
-EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
-/* Memory manager initialization */
-EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
-
-/* Utility routines in jutils.c */
-EXTERN(long) jdiv_round_up JPP((long a, long b));
-EXTERN(long) jround_up JPP((long a, long b));
-EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
-				    JSAMPARRAY output_array, int dest_row,
-				    int num_rows, JDIMENSION num_cols));
-EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
-				  JDIMENSION num_blocks));
-EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
-/* Constant tables in jutils.c */
-#if 0				/* This table is not actually needed in v6a */
-extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
-#endif
-extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
-
-/* Suppress undefined-structure complaints if necessary. */
-
-#ifdef INCOMPLETE_TYPES_BROKEN
-#ifndef AM_MEMORY_MANAGER	/* only jmemmgr.c defines these */
-struct jvirt_sarray_control { long dummy; };
-struct jvirt_barray_control { long dummy; };
-#endif
-#endif /* INCOMPLETE_TYPES_BROKEN */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jpeglib.h ./Shared/jpeg-6b/jpeglib.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jpeglib.h	Mon Dec  1 12:30:39 2003
+++ ./Shared/jpeg-6b/jpeglib.h	Wed Dec 31 19:00:00 1969
@@ -1,1096 +0,0 @@
-/*
- * jpeglib.h
- *
- * Copyright (C) 1991-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file defines the application interface for the JPEG library.
- * Most applications using the library need only include this file,
- * and perhaps jerror.h if they want to know the exact error codes.
- */
-
-#ifndef JPEGLIB_H
-#define JPEGLIB_H
-
-/*
- * First we include the configuration files that record how this
- * installation of the JPEG library is set up.  jconfig.h can be
- * generated automatically for many systems.  jmorecfg.h contains
- * manual configuration options that most people need not worry about.
- */
-
-#ifndef JCONFIG_INCLUDED	/* in case jinclude.h already did */
-#include "jconfig.h"		/* widely used configuration options */
-#endif
-#include "jmorecfg.h"		/* seldom changed options */
-
-
-/* Version ID for the JPEG library.
- * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
- */
-
-#define JPEG_LIB_VERSION  62	/* Version 6b */
-
-
-/* Various constants determining the sizes of things.
- * All of these are specified by the JPEG standard, so don't change them
- * if you want to be compatible.
- */
-
-#define DCTSIZE		    8	/* The basic DCT block is 8x8 samples */
-#define DCTSIZE2	    64	/* DCTSIZE squared; # of elements in a block */
-#define NUM_QUANT_TBLS      4	/* Quantization tables are numbered 0..3 */
-#define NUM_HUFF_TBLS       4	/* Huffman tables are numbered 0..3 */
-#define NUM_ARITH_TBLS      16	/* Arith-coding tables are numbered 0..15 */
-#define MAX_COMPS_IN_SCAN   4	/* JPEG limit on # of components in one scan */
-#define MAX_SAMP_FACTOR     4	/* JPEG limit on sampling factors */
-/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
- * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
- * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
- * to handle it.  We even let you do this from the jconfig.h file.  However,
- * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
- * sometimes emits noncompliant files doesn't mean you should too.
- */
-#define C_MAX_BLOCKS_IN_MCU   10 /* compressor's limit on blocks per MCU */
-#ifndef D_MAX_BLOCKS_IN_MCU
-#define D_MAX_BLOCKS_IN_MCU   10 /* decompressor's limit on blocks per MCU */
-#endif
-
-
-/* Data structures for images (arrays of samples and of DCT coefficients).
- * On 80x86 machines, the image arrays are too big for near pointers,
- * but the pointer arrays can fit in near memory.
- */
-
-typedef JSAMPLE FAR *JSAMPROW;	/* ptr to one image row of pixel samples. */
-typedef JSAMPROW *JSAMPARRAY;	/* ptr to some rows (a 2-D sample array) */
-typedef JSAMPARRAY *JSAMPIMAGE;	/* a 3-D sample array: top index is color */
-
-typedef JCOEF JBLOCK[DCTSIZE2];	/* one block of coefficients */
-typedef JBLOCK FAR *JBLOCKROW;	/* pointer to one row of coefficient blocks */
-typedef JBLOCKROW *JBLOCKARRAY;		/* a 2-D array of coefficient blocks */
-typedef JBLOCKARRAY *JBLOCKIMAGE;	/* a 3-D array of coefficient blocks */
-
-typedef JCOEF FAR *JCOEFPTR;	/* useful in a couple of places */
-
-
-/* Types for JPEG compression parameters and working tables. */
-
-
-/* DCT coefficient quantization tables. */
-
-typedef struct {
-  /* This array gives the coefficient quantizers in natural array order
-   * (not the zigzag order in which they are stored in a JPEG DQT marker).
-   * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
-   */
-  UINT16 quantval[DCTSIZE2];	/* quantization step for each coefficient */
-  /* This field is used only during compression.  It's initialized FALSE when
-   * the table is created, and set TRUE when it's been output to the file.
-   * You could suppress output of a table by setting this to TRUE.
-   * (See jpeg_suppress_tables for an example.)
-   */
-  boolean sent_table;		/* TRUE when table has been output */
-} JQUANT_TBL;
-
-
-/* Huffman coding tables. */
-
-typedef struct {
-  /* These two fields directly represent the contents of a JPEG DHT marker */
-  UINT8 bits[17];		/* bits[k] = # of symbols with codes of */
-				/* length k bits; bits[0] is unused */
-  UINT8 huffval[256];		/* The symbols, in order of incr code length */
-  /* This field is used only during compression.  It's initialized FALSE when
-   * the table is created, and set TRUE when it's been output to the file.
-   * You could suppress output of a table by setting this to TRUE.
-   * (See jpeg_suppress_tables for an example.)
-   */
-  boolean sent_table;		/* TRUE when table has been output */
-} JHUFF_TBL;
-
-
-/* Basic info about one component (color channel). */
-
-typedef struct {
-  /* These values are fixed over the whole image. */
-  /* For compression, they must be supplied by parameter setup; */
-  /* for decompression, they are read from the SOF marker. */
-  int component_id;		/* identifier for this component (0..255) */
-  int component_index;		/* its index in SOF or cinfo->comp_info[] */
-  int h_samp_factor;		/* horizontal sampling factor (1..4) */
-  int v_samp_factor;		/* vertical sampling factor (1..4) */
-  int quant_tbl_no;		/* quantization table selector (0..3) */
-  /* These values may vary between scans. */
-  /* For compression, they must be supplied by parameter setup; */
-  /* for decompression, they are read from the SOS marker. */
-  /* The decompressor output side may not use these variables. */
-  int dc_tbl_no;		/* DC entropy table selector (0..3) */
-  int ac_tbl_no;		/* AC entropy table selector (0..3) */
-  
-  /* Remaining fields should be treated as private by applications. */
-  
-  /* These values are computed during compression or decompression startup: */
-  /* Component's size in DCT blocks.
-   * Any dummy blocks added to complete an MCU are not counted; therefore
-   * these values do not depend on whether a scan is interleaved or not.
-   */
-  JDIMENSION width_in_blocks;
-  JDIMENSION height_in_blocks;
-  /* Size of a DCT block in samples.  Always DCTSIZE for compression.
-   * For decompression this is the size of the output from one DCT block,
-   * reflecting any scaling we choose to apply during the IDCT step.
-   * Values of 1,2,4,8 are likely to be supported.  Note that different
-   * components may receive different IDCT scalings.
-   */
-  int DCT_scaled_size;
-  /* The downsampled dimensions are the component's actual, unpadded number
-   * of samples at the main buffer (preprocessing/compression interface), thus
-   * downsampled_width = ceil(image_width * Hi/Hmax)
-   * and similarly for height.  For decompression, IDCT scaling is included, so
-   * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
-   */
-  JDIMENSION downsampled_width;	 /* actual width in samples */
-  JDIMENSION downsampled_height; /* actual height in samples */
-  /* This flag is used only for decompression.  In cases where some of the
-   * components will be ignored (eg grayscale output from YCbCr image),
-   * we can skip most computations for the unused components.
-   */
-  boolean component_needed;	/* do we need the value of this component? */
-
-  /* These values are computed before starting a scan of the component. */
-  /* The decompressor output side may not use these variables. */
-  int MCU_width;		/* number of blocks per MCU, horizontally */
-  int MCU_height;		/* number of blocks per MCU, vertically */
-  int MCU_blocks;		/* MCU_width * MCU_height */
-  int MCU_sample_width;		/* MCU width in samples, MCU_width*DCT_scaled_size */
-  int last_col_width;		/* # of non-dummy blocks across in last MCU */
-  int last_row_height;		/* # of non-dummy blocks down in last MCU */
-
-  /* Saved quantization table for component; NULL if none yet saved.
-   * See jdinput.c comments about the need for this information.
-   * This field is currently used only for decompression.
-   */
-  JQUANT_TBL * quant_table;
-
-  /* Private per-component storage for DCT or IDCT subsystem. */
-  void * dct_table;
-} jpeg_component_info;
-
-
-/* The script for encoding a multiple-scan file is an array of these: */
-
-typedef struct {
-  int comps_in_scan;		/* number of components encoded in this scan */
-  int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
-  int Ss, Se;			/* progressive JPEG spectral selection parms */
-  int Ah, Al;			/* progressive JPEG successive approx. parms */
-} jpeg_scan_info;
-
-/* The decompressor can save APPn and COM markers in a list of these: */
-
-typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
-
-struct jpeg_marker_struct {
-  jpeg_saved_marker_ptr next;	/* next in list, or NULL */
-  UINT8 marker;			/* marker code: JPEG_COM, or JPEG_APP0+n */
-  unsigned int original_length;	/* # bytes of data in the file */
-  unsigned int data_length;	/* # bytes of data saved at data[] */
-  JOCTET FAR * data;		/* the data contained in the marker */
-  /* the marker length word is not counted in data_length or original_length */
-};
-
-/* Known color spaces. */
-
-typedef enum {
-	JCS_UNKNOWN,		/* error/unspecified */
-	JCS_GRAYSCALE,		/* monochrome */
-	JCS_RGB,		/* red/green/blue */
-	JCS_YCbCr,		/* Y/Cb/Cr (also known as YUV) */
-	JCS_CMYK,		/* C/M/Y/K */
-	JCS_YCCK		/* Y/Cb/Cr/K */
-} J_COLOR_SPACE;
-
-/* DCT/IDCT algorithm options. */
-
-typedef enum {
-	JDCT_ISLOW,		/* slow but accurate integer algorithm */
-	JDCT_IFAST,		/* faster, less accurate integer method */
-	JDCT_FLOAT		/* floating-point: accurate, fast on fast HW */
-} J_DCT_METHOD;
-
-#ifndef JDCT_DEFAULT		/* may be overridden in jconfig.h */
-#define JDCT_DEFAULT  JDCT_ISLOW
-#endif
-#ifndef JDCT_FASTEST		/* may be overridden in jconfig.h */
-#define JDCT_FASTEST  JDCT_IFAST
-#endif
-
-/* Dithering options for decompression. */
-
-typedef enum {
-	JDITHER_NONE,		/* no dithering */
-	JDITHER_ORDERED,	/* simple ordered dither */
-	JDITHER_FS		/* Floyd-Steinberg error diffusion dither */
-} J_DITHER_MODE;
-
-
-/* Common fields between JPEG compression and decompression master structs. */
-
-#define jpeg_common_fields \
-  struct jpeg_error_mgr * err;	/* Error handler module */\
-  struct jpeg_memory_mgr * mem;	/* Memory manager module */\
-  struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
-  void * client_data;		/* Available for use by application */\
-  boolean is_decompressor;	/* So common code can tell which is which */\
-  int global_state		/* For checking call sequence validity */
-
-/* Routines that are to be used by both halves of the library are declared
- * to receive a pointer to this structure.  There are no actual instances of
- * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
- */
-struct jpeg_common_struct {
-  jpeg_common_fields;		/* Fields common to both master struct types */
-  /* Additional fields follow in an actual jpeg_compress_struct or
-   * jpeg_decompress_struct.  All three structs must agree on these
-   * initial fields!  (This would be a lot cleaner in C++.)
-   */
-};
-
-typedef struct jpeg_common_struct * j_common_ptr;
-typedef struct jpeg_compress_struct * j_compress_ptr;
-typedef struct jpeg_decompress_struct * j_decompress_ptr;
-
-
-/* Master record for a compression instance */
-
-struct jpeg_compress_struct {
-  jpeg_common_fields;		/* Fields shared with jpeg_decompress_struct */
-
-  /* Destination for compressed data */
-  struct jpeg_destination_mgr * dest;
-
-  /* Description of source image --- these fields must be filled in by
-   * outer application before starting compression.  in_color_space must
-   * be correct before you can even call jpeg_set_defaults().
-   */
-
-  JDIMENSION image_width;	/* input image width */
-  JDIMENSION image_height;	/* input image height */
-  int input_components;		/* # of color components in input image */
-  J_COLOR_SPACE in_color_space;	/* colorspace of input image */
-
-  double input_gamma;		/* image gamma of input image */
-
-  /* Compression parameters --- these fields must be set before calling
-   * jpeg_start_compress().  We recommend calling jpeg_set_defaults() to
-   * initialize everything to reasonable defaults, then changing anything
-   * the application specifically wants to change.  That way you won't get
-   * burnt when new parameters are added.  Also note that there are several
-   * helper routines to simplify changing parameters.
-   */
-
-  int data_precision;		/* bits of precision in image data */
-
-  int num_components;		/* # of color components in JPEG image */
-  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
-
-  jpeg_component_info * comp_info;
-  /* comp_info[i] describes component that appears i'th in SOF */
-  
-  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
-  /* ptrs to coefficient quantization tables, or NULL if not defined */
-  
-  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
-  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
-  /* ptrs to Huffman coding tables, or NULL if not defined */
-  
-  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
-  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
-  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
-
-  int num_scans;		/* # of entries in scan_info array */
-  const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
-  /* The default value of scan_info is NULL, which causes a single-scan
-   * sequential JPEG file to be emitted.  To create a multi-scan file,
-   * set num_scans and scan_info to point to an array of scan definitions.
-   */
-
-  boolean raw_data_in;		/* TRUE=caller supplies downsampled data */
-  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
-  boolean optimize_coding;	/* TRUE=optimize entropy encoding parms */
-  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
-  int smoothing_factor;		/* 1..100, or 0 for no input smoothing */
-  J_DCT_METHOD dct_method;	/* DCT algorithm selector */
-
-  /* The restart interval can be specified in absolute MCUs by setting
-   * restart_interval, or in MCU rows by setting restart_in_rows
-   * (in which case the correct restart_interval will be figured
-   * for each scan).
-   */
-  unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
-  int restart_in_rows;		/* if > 0, MCU rows per restart interval */
-
-  /* Parameters controlling emission of special markers. */
-
-  boolean write_JFIF_header;	/* should a JFIF marker be written? */
-  UINT8 JFIF_major_version;	/* What to write for the JFIF version number */
-  UINT8 JFIF_minor_version;
-  /* These three values are not used by the JPEG code, merely copied */
-  /* into the JFIF APP0 marker.  density_unit can be 0 for unknown, */
-  /* 1 for dots/inch, or 2 for dots/cm.  Note that the pixel aspect */
-  /* ratio is defined by X_density/Y_density even when density_unit=0. */
-  UINT8 density_unit;		/* JFIF code for pixel size units */
-  UINT16 X_density;		/* Horizontal pixel density */
-  UINT16 Y_density;		/* Vertical pixel density */
-  boolean write_Adobe_marker;	/* should an Adobe marker be written? */
-  
-  /* State variable: index of next scanline to be written to
-   * jpeg_write_scanlines().  Application may use this to control its
-   * processing loop, e.g., "while (next_scanline < image_height)".
-   */
-
-  JDIMENSION next_scanline;	/* 0 .. image_height-1  */
-
-  /* Remaining fields are known throughout compressor, but generally
-   * should not be touched by a surrounding application.
-   */
-
-  /*
-   * These fields are computed during compression startup
-   */
-  boolean progressive_mode;	/* TRUE if scan script uses progressive mode */
-  int max_h_samp_factor;	/* largest h_samp_factor */
-  int max_v_samp_factor;	/* largest v_samp_factor */
-
-  JDIMENSION total_iMCU_rows;	/* # of iMCU rows to be input to coef ctlr */
-  /* The coefficient controller receives data in units of MCU rows as defined
-   * for fully interleaved scans (whether the JPEG file is interleaved or not).
-   * There are v_samp_factor * DCTSIZE sample rows of each component in an
-   * "iMCU" (interleaved MCU) row.
-   */
-  
-  /*
-   * These fields are valid during any one scan.
-   * They describe the components and MCUs actually appearing in the scan.
-   */
-  int comps_in_scan;		/* # of JPEG components in this scan */
-  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
-  /* *cur_comp_info[i] describes component that appears i'th in SOS */
-  
-  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
-  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
-  
-  int blocks_in_MCU;		/* # of DCT blocks per MCU */
-  int MCU_membership[C_MAX_BLOCKS_IN_MCU];
-  /* MCU_membership[i] is index in cur_comp_info of component owning */
-  /* i'th block in an MCU */
-
-  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
-
-  /*
-   * Links to compression subobjects (methods and private variables of modules)
-   */
-  struct jpeg_comp_master * master;
-  struct jpeg_c_main_controller * main;
-  struct jpeg_c_prep_controller * prep;
-  struct jpeg_c_coef_controller * coef;
-  struct jpeg_marker_writer * marker;
-  struct jpeg_color_converter * cconvert;
-  struct jpeg_downsampler * downsample;
-  struct jpeg_forward_dct * fdct;
-  struct jpeg_entropy_encoder * entropy;
-  jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
-  int script_space_size;
-};
-
-
-/* Master record for a decompression instance */
-
-struct jpeg_decompress_struct {
-  jpeg_common_fields;		/* Fields shared with jpeg_compress_struct */
-
-  /* Source of compressed data */
-  struct jpeg_source_mgr * src;
-
-  /* Basic description of image --- filled in by jpeg_read_header(). */
-  /* Application may inspect these values to decide how to process image. */
-
-  JDIMENSION image_width;	/* nominal image width (from SOF marker) */
-  JDIMENSION image_height;	/* nominal image height */
-  int num_components;		/* # of color components in JPEG image */
-  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
-
-  /* Decompression processing parameters --- these fields must be set before
-   * calling jpeg_start_decompress().  Note that jpeg_read_header() initializes
-   * them to default values.
-   */
-
-  J_COLOR_SPACE out_color_space; /* colorspace for output */
-
-  unsigned int scale_num, scale_denom; /* fraction by which to scale image */
-
-  double output_gamma;		/* image gamma wanted in output */
-
-  boolean buffered_image;	/* TRUE=multiple output passes */
-  boolean raw_data_out;		/* TRUE=downsampled data wanted */
-
-  J_DCT_METHOD dct_method;	/* IDCT algorithm selector */
-  boolean do_fancy_upsampling;	/* TRUE=apply fancy upsampling */
-  boolean do_block_smoothing;	/* TRUE=apply interblock smoothing */
-
-  boolean quantize_colors;	/* TRUE=colormapped output wanted */
-  /* the following are ignored if not quantize_colors: */
-  J_DITHER_MODE dither_mode;	/* type of color dithering to use */
-  boolean two_pass_quantize;	/* TRUE=use two-pass color quantization */
-  int desired_number_of_colors;	/* max # colors to use in created colormap */
-  /* these are significant only in buffered-image mode: */
-  boolean enable_1pass_quant;	/* enable future use of 1-pass quantizer */
-  boolean enable_external_quant;/* enable future use of external colormap */
-  boolean enable_2pass_quant;	/* enable future use of 2-pass quantizer */
-
-  /* Description of actual output image that will be returned to application.
-   * These fields are computed by jpeg_start_decompress().
-   * You can also use jpeg_calc_output_dimensions() to determine these values
-   * in advance of calling jpeg_start_decompress().
-   */
-
-  JDIMENSION output_width;	/* scaled image width */
-  JDIMENSION output_height;	/* scaled image height */
-  int out_color_components;	/* # of color components in out_color_space */
-  int output_components;	/* # of color components returned */
-  /* output_components is 1 (a colormap index) when quantizing colors;
-   * otherwise it equals out_color_components.
-   */
-  int rec_outbuf_height;	/* min recommended height of scanline buffer */
-  /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
-   * high, space and time will be wasted due to unnecessary data copying.
-   * Usually rec_outbuf_height will be 1 or 2, at most 4.
-   */
-
-  /* When quantizing colors, the output colormap is described by these fields.
-   * The application can supply a colormap by setting colormap non-NULL before
-   * calling jpeg_start_decompress; otherwise a colormap is created during
-   * jpeg_start_decompress or jpeg_start_output.
-   * The map has out_color_components rows and actual_number_of_colors columns.
-   */
-  int actual_number_of_colors;	/* number of entries in use */
-  JSAMPARRAY colormap;		/* The color map as a 2-D pixel array */
-
-  /* State variables: these variables indicate the progress of decompression.
-   * The application may examine these but must not modify them.
-   */
-
-  /* Row index of next scanline to be read from jpeg_read_scanlines().
-   * Application may use this to control its processing loop, e.g.,
-   * "while (output_scanline < output_height)".
-   */
-  JDIMENSION output_scanline;	/* 0 .. output_height-1  */
-
-  /* Current input scan number and number of iMCU rows completed in scan.
-   * These indicate the progress of the decompressor input side.
-   */
-  int input_scan_number;	/* Number of SOS markers seen so far */
-  JDIMENSION input_iMCU_row;	/* Number of iMCU rows completed */
-
-  /* The "output scan number" is the notional scan being displayed by the
-   * output side.  The decompressor will not allow output scan/row number
-   * to get ahead of input scan/row, but it can fall arbitrarily far behind.
-   */
-  int output_scan_number;	/* Nominal scan number being displayed */
-  JDIMENSION output_iMCU_row;	/* Number of iMCU rows read */
-
-  /* Current progression status.  coef_bits[c][i] indicates the precision
-   * with which component c's DCT coefficient i (in zigzag order) is known.
-   * It is -1 when no data has yet been received, otherwise it is the point
-   * transform (shift) value for the most recent scan of the coefficient
-   * (thus, 0 at completion of the progression).
-   * This pointer is NULL when reading a non-progressive file.
-   */
-  int (*coef_bits)[DCTSIZE2];	/* -1 or current Al value for each coef */
-
-  /* Internal JPEG parameters --- the application usually need not look at
-   * these fields.  Note that the decompressor output side may not use
-   * any parameters that can change between scans.
-   */
-
-  /* Quantization and Huffman tables are carried forward across input
-   * datastreams when processing abbreviated JPEG datastreams.
-   */
-
-  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
-  /* ptrs to coefficient quantization tables, or NULL if not defined */
-
-  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
-  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
-  /* ptrs to Huffman coding tables, or NULL if not defined */
-
-  /* These parameters are never carried across datastreams, since they
-   * are given in SOF/SOS markers or defined to be reset by SOI.
-   */
-
-  int data_precision;		/* bits of precision in image data */
-
-  jpeg_component_info * comp_info;
-  /* comp_info[i] describes component that appears i'th in SOF */
-
-  boolean progressive_mode;	/* TRUE if SOFn specifies progressive mode */
-  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
-
-  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
-  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
-  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
-
-  unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
-
-  /* These fields record data obtained from optional markers recognized by
-   * the JPEG library.
-   */
-  boolean saw_JFIF_marker;	/* TRUE iff a JFIF APP0 marker was found */
-  /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
-  UINT8 JFIF_major_version;	/* JFIF version number */
-  UINT8 JFIF_minor_version;
-  UINT8 density_unit;		/* JFIF code for pixel size units */
-  UINT16 X_density;		/* Horizontal pixel density */
-  UINT16 Y_density;		/* Vertical pixel density */
-  boolean saw_Adobe_marker;	/* TRUE iff an Adobe APP14 marker was found */
-  UINT8 Adobe_transform;	/* Color transform code from Adobe marker */
-
-  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
-
-  /* Aside from the specific data retained from APPn markers known to the
-   * library, the uninterpreted contents of any or all APPn and COM markers
-   * can be saved in a list for examination by the application.
-   */
-  jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
-
-  /* Remaining fields are known throughout decompressor, but generally
-   * should not be touched by a surrounding application.
-   */
-
-  /*
-   * These fields are computed during decompression startup
-   */
-  int max_h_samp_factor;	/* largest h_samp_factor */
-  int max_v_samp_factor;	/* largest v_samp_factor */
-
-  int min_DCT_scaled_size;	/* smallest DCT_scaled_size of any component */
-
-  JDIMENSION total_iMCU_rows;	/* # of iMCU rows in image */
-  /* The coefficient controller's input and output progress is measured in
-   * units of "iMCU" (interleaved MCU) rows.  These are the same as MCU rows
-   * in fully interleaved JPEG scans, but are used whether the scan is
-   * interleaved or not.  We define an iMCU row as v_samp_factor DCT block
-   * rows of each component.  Therefore, the IDCT output contains
-   * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
-   */
-
-  JSAMPLE * sample_range_limit; /* table for fast range-limiting */
-
-  /*
-   * These fields are valid during any one scan.
-   * They describe the components and MCUs actually appearing in the scan.
-   * Note that the decompressor output side must not use these fields.
-   */
-  int comps_in_scan;		/* # of JPEG components in this scan */
-  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
-  /* *cur_comp_info[i] describes component that appears i'th in SOS */
-
-  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
-  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
-
-  int blocks_in_MCU;		/* # of DCT blocks per MCU */
-  int MCU_membership[D_MAX_BLOCKS_IN_MCU];
-  /* MCU_membership[i] is index in cur_comp_info of component owning */
-  /* i'th block in an MCU */
-
-  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
-
-  /* This field is shared between entropy decoder and marker parser.
-   * It is either zero or the code of a JPEG marker that has been
-   * read from the data source, but has not yet been processed.
-   */
-  int unread_marker;
-
-  /*
-   * Links to decompression subobjects (methods, private variables of modules)
-   */
-  struct jpeg_decomp_master * master;
-  struct jpeg_d_main_controller * main;
-  struct jpeg_d_coef_controller * coef;
-  struct jpeg_d_post_controller * post;
-  struct jpeg_input_controller * inputctl;
-  struct jpeg_marker_reader * marker;
-  struct jpeg_entropy_decoder * entropy;
-  struct jpeg_inverse_dct * idct;
-  struct jpeg_upsampler * upsample;
-  struct jpeg_color_deconverter * cconvert;
-  struct jpeg_color_quantizer * cquantize;
-};
-
-
-/* "Object" declarations for JPEG modules that may be supplied or called
- * directly by the surrounding application.
- * As with all objects in the JPEG library, these structs only define the
- * publicly visible methods and state variables of a module.  Additional
- * private fields may exist after the public ones.
- */
-
-
-/* Error handler object */
-
-struct jpeg_error_mgr {
-  /* Error exit handler: does not return to caller */
-  JMETHOD(void, error_exit, (j_common_ptr cinfo));
-  /* Conditionally emit a trace or warning message */
-  JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
-  /* Routine that actually outputs a trace or error message */
-  JMETHOD(void, output_message, (j_common_ptr cinfo));
-  /* Format a message string for the most recent JPEG error or message */
-  JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
-#define JMSG_LENGTH_MAX  200	/* recommended size of format_message buffer */
-  /* Reset error state variables at start of a new image */
-  JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
-  
-  /* The message ID code and any parameters are saved here.
-   * A message can have one string parameter or up to 8 int parameters.
-   */
-  int msg_code;
-#define JMSG_STR_PARM_MAX  80
-  union {
-    int i[8];
-    char s[JMSG_STR_PARM_MAX];
-  } msg_parm;
-  
-  /* Standard state variables for error facility */
-  
-  int trace_level;		/* max msg_level that will be displayed */
-  
-  /* For recoverable corrupt-data errors, we emit a warning message,
-   * but keep going unless emit_message chooses to abort.  emit_message
-   * should count warnings in num_warnings.  The surrounding application
-   * can check for bad data by seeing if num_warnings is nonzero at the
-   * end of processing.
-   */
-  long num_warnings;		/* number of corrupt-data warnings */
-
-  /* These fields point to the table(s) of error message strings.
-   * An application can change the table pointer to switch to a different
-   * message list (typically, to change the language in which errors are
-   * reported).  Some applications may wish to add additional error codes
-   * that will be handled by the JPEG library error mechanism; the second
-   * table pointer is used for this purpose.
-   *
-   * First table includes all errors generated by JPEG library itself.
-   * Error code 0 is reserved for a "no such error string" message.
-   */
-  const char * const * jpeg_message_table; /* Library errors */
-  int last_jpeg_message;    /* Table contains strings 0..last_jpeg_message */
-  /* Second table can be added by application (see cjpeg/djpeg for example).
-   * It contains strings numbered first_addon_message..last_addon_message.
-   */
-  const char * const * addon_message_table; /* Non-library errors */
-  int first_addon_message;	/* code for first string in addon table */
-  int last_addon_message;	/* code for last string in addon table */
-};
-
-
-/* Progress monitor object */
-
-struct jpeg_progress_mgr {
-  JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
-
-  long pass_counter;		/* work units completed in this pass */
-  long pass_limit;		/* total number of work units in this pass */
-  int completed_passes;		/* passes completed so far */
-  int total_passes;		/* total number of passes expected */
-};
-
-
-/* Data destination object for compression */
-
-struct jpeg_destination_mgr {
-  JOCTET * next_output_byte;	/* => next byte to write in buffer */
-  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
-
-  JMETHOD(void, init_destination, (j_compress_ptr cinfo));
-  JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
-  JMETHOD(void, term_destination, (j_compress_ptr cinfo));
-};
-
-
-/* Data source object for decompression */
-
-struct jpeg_source_mgr {
-  const JOCTET * next_input_byte; /* => next byte to read from buffer */
-  size_t bytes_in_buffer;	/* # of bytes remaining in buffer */
-
-  JMETHOD(void, init_source, (j_decompress_ptr cinfo));
-  JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
-  JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
-  JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
-  JMETHOD(void, term_source, (j_decompress_ptr cinfo));
-};
-
-
-/* Memory manager object.
- * Allocates "small" objects (a few K total), "large" objects (tens of K),
- * and "really big" objects (virtual arrays with backing store if needed).
- * The memory manager does not allow individual objects to be freed; rather,
- * each created object is assigned to a pool, and whole pools can be freed
- * at once.  This is faster and more convenient than remembering exactly what
- * to free, especially where malloc()/free() are not too speedy.
- * NB: alloc routines never return NULL.  They exit to error_exit if not
- * successful.
- */
-
-#define JPOOL_PERMANENT	0	/* lasts until master record is destroyed */
-#define JPOOL_IMAGE	1	/* lasts until done with image/datastream */
-#define JPOOL_NUMPOOLS	2
-
-typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
-typedef struct jvirt_barray_control * jvirt_barray_ptr;
-
-
-struct jpeg_memory_mgr {
-  /* Method pointers */
-  JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
-				size_t sizeofobject));
-  JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
-				     size_t sizeofobject));
-  JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
-				     JDIMENSION samplesperrow,
-				     JDIMENSION numrows));
-  JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
-				      JDIMENSION blocksperrow,
-				      JDIMENSION numrows));
-  JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
-						  int pool_id,
-						  boolean pre_zero,
-						  JDIMENSION samplesperrow,
-						  JDIMENSION numrows,
-						  JDIMENSION maxaccess));
-  JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
-						  int pool_id,
-						  boolean pre_zero,
-						  JDIMENSION blocksperrow,
-						  JDIMENSION numrows,
-						  JDIMENSION maxaccess));
-  JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
-  JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
-					   jvirt_sarray_ptr ptr,
-					   JDIMENSION start_row,
-					   JDIMENSION num_rows,
-					   boolean writable));
-  JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
-					    jvirt_barray_ptr ptr,
-					    JDIMENSION start_row,
-					    JDIMENSION num_rows,
-					    boolean writable));
-  JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
-  JMETHOD(void, self_destruct, (j_common_ptr cinfo));
-
-  /* Limit on memory allocation for this JPEG object.  (Note that this is
-   * merely advisory, not a guaranteed maximum; it only affects the space
-   * used for virtual-array buffers.)  May be changed by outer application
-   * after creating the JPEG object.
-   */
-  long max_memory_to_use;
-
-  /* Maximum allocation request accepted by alloc_large. */
-  long max_alloc_chunk;
-};
-
-
-/* Routine signature for application-supplied marker processing methods.
- * Need not pass marker code since it is stored in cinfo->unread_marker.
- */
-typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
-
-
-/* Declarations for routines called by application.
- * The JPP macro hides prototype parameters from compilers that can't cope.
- * Note JPP requires double parentheses.
- */
-
-#ifdef HAVE_PROTOTYPES
-#define JPP(arglist)	arglist
-#else
-#define JPP(arglist)	()
-#endif
-
-
-/* Short forms of external names for systems with brain-damaged linkers.
- * We shorten external names to be unique in the first six letters, which
- * is good enough for all known systems.
- * (If your compiler itself needs names to be unique in less than 15 
- * characters, you are out of luck.  Get a better compiler.)
- */
-
-#ifdef NEED_SHORT_EXTERNAL_NAMES
-#define jpeg_std_error		jStdError
-#define jpeg_CreateCompress	jCreaCompress
-#define jpeg_CreateDecompress	jCreaDecompress
-#define jpeg_destroy_compress	jDestCompress
-#define jpeg_destroy_decompress	jDestDecompress
-#define jpeg_stdio_dest		jStdDest
-#define jpeg_stdio_src		jStdSrc
-#define jpeg_set_defaults	jSetDefaults
-#define jpeg_set_colorspace	jSetColorspace
-#define jpeg_default_colorspace	jDefColorspace
-#define jpeg_set_quality	jSetQuality
-#define jpeg_set_linear_quality	jSetLQuality
-#define jpeg_add_quant_table	jAddQuantTable
-#define jpeg_quality_scaling	jQualityScaling
-#define jpeg_simple_progression	jSimProgress
-#define jpeg_suppress_tables	jSuppressTables
-#define jpeg_alloc_quant_table	jAlcQTable
-#define jpeg_alloc_huff_table	jAlcHTable
-#define jpeg_start_compress	jStrtCompress
-#define jpeg_write_scanlines	jWrtScanlines
-#define jpeg_finish_compress	jFinCompress
-#define jpeg_write_raw_data	jWrtRawData
-#define jpeg_write_marker	jWrtMarker
-#define jpeg_write_m_header	jWrtMHeader
-#define jpeg_write_m_byte	jWrtMByte
-#define jpeg_write_tables	jWrtTables
-#define jpeg_read_header	jReadHeader
-#define jpeg_start_decompress	jStrtDecompress
-#define jpeg_read_scanlines	jReadScanlines
-#define jpeg_finish_decompress	jFinDecompress
-#define jpeg_read_raw_data	jReadRawData
-#define jpeg_has_multiple_scans	jHasMultScn
-#define jpeg_start_output	jStrtOutput
-#define jpeg_finish_output	jFinOutput
-#define jpeg_input_complete	jInComplete
-#define jpeg_new_colormap	jNewCMap
-#define jpeg_consume_input	jConsumeInput
-#define jpeg_calc_output_dimensions	jCalcDimensions
-#define jpeg_save_markers	jSaveMarkers
-#define jpeg_set_marker_processor	jSetMarker
-#define jpeg_read_coefficients	jReadCoefs
-#define jpeg_write_coefficients	jWrtCoefs
-#define jpeg_copy_critical_parameters	jCopyCrit
-#define jpeg_abort_compress	jAbrtCompress
-#define jpeg_abort_decompress	jAbrtDecompress
-#define jpeg_abort		jAbort
-#define jpeg_destroy		jDestroy
-#define jpeg_resync_to_restart	jResyncRestart
-#endif /* NEED_SHORT_EXTERNAL_NAMES */
-
-
-/* Default error-management setup */
-EXTERN(struct jpeg_error_mgr *) jpeg_std_error
-	JPP((struct jpeg_error_mgr * err));
-
-/* Initialization of JPEG compression objects.
- * jpeg_create_compress() and jpeg_create_decompress() are the exported
- * names that applications should call.  These expand to calls on
- * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
- * passed for version mismatch checking.
- * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
- */
-#define jpeg_create_compress(cinfo) \
-    jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
-			(size_t) sizeof(struct jpeg_compress_struct))
-#define jpeg_create_decompress(cinfo) \
-    jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
-			  (size_t) sizeof(struct jpeg_decompress_struct))
-EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
-				      int version, size_t structsize));
-EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
-					int version, size_t structsize));
-/* Destruction of JPEG compression objects */
-EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
-EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
-
-/* Standard data source and destination managers: stdio streams. */
-/* Caller is responsible for opening the file before and closing after. */
-EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
-EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
-
-/* Default parameter setup for compression */
-EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
-/* Compression parameter setup aids */
-EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
-				      J_COLOR_SPACE colorspace));
-EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
-EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
-				   boolean force_baseline));
-EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
-					  int scale_factor,
-					  boolean force_baseline));
-EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
-				       const unsigned int *basic_table,
-				       int scale_factor,
-				       boolean force_baseline));
-EXTERN(int) jpeg_quality_scaling JPP((int quality));
-EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
-EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
-				       boolean suppress));
-EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
-EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
-
-/* Main entry points for compression */
-EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
-				      boolean write_all_tables));
-EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
-					     JSAMPARRAY scanlines,
-					     JDIMENSION num_lines));
-EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
-
-/* Replaces jpeg_write_scanlines when writing raw downsampled data. */
-EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
-					    JSAMPIMAGE data,
-					    JDIMENSION num_lines));
-
-/* Write a special marker.  See libjpeg.doc concerning safe usage. */
-EXTERN(void) jpeg_write_marker
-	JPP((j_compress_ptr cinfo, int marker,
-	     const JOCTET * dataptr, unsigned int datalen));
-/* Same, but piecemeal. */
-EXTERN(void) jpeg_write_m_header
-	JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
-EXTERN(void) jpeg_write_m_byte
-	JPP((j_compress_ptr cinfo, int val));
-
-/* Alternate compression function: just write an abbreviated table file */
-EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
-
-/* Decompression startup: read start of JPEG datastream to see what's there */
-EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
-				  boolean require_image));
-/* Return value is one of: */
-#define JPEG_SUSPENDED		0 /* Suspended due to lack of input data */
-#define JPEG_HEADER_OK		1 /* Found valid image datastream */
-#define JPEG_HEADER_TABLES_ONLY	2 /* Found valid table-specs-only datastream */
-/* If you pass require_image = TRUE (normal case), you need not check for
- * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
- * JPEG_SUSPENDED is only possible if you use a data source module that can
- * give a suspension return (the stdio source module doesn't).
- */
-
-/* Main entry points for decompression */
-EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
-EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
-					    JSAMPARRAY scanlines,
-					    JDIMENSION max_lines));
-EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
-
-/* Replaces jpeg_read_scanlines when reading raw downsampled data. */
-EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
-					   JSAMPIMAGE data,
-					   JDIMENSION max_lines));
-
-/* Additional entry points for buffered-image mode. */
-EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
-EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
-				       int scan_number));
-EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
-EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
-EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
-EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
-/* Return value is one of: */
-/* #define JPEG_SUSPENDED	0    Suspended due to lack of input data */
-#define JPEG_REACHED_SOS	1 /* Reached start of new scan */
-#define JPEG_REACHED_EOI	2 /* Reached end of image */
-#define JPEG_ROW_COMPLETED	3 /* Completed one iMCU row */
-#define JPEG_SCAN_COMPLETED	4 /* Completed last iMCU row of a scan */
-
-/* Precalculate output dimensions for current decompression parameters. */
-EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
-
-/* Control saving of COM and APPn markers into marker_list. */
-EXTERN(void) jpeg_save_markers
-	JPP((j_decompress_ptr cinfo, int marker_code,
-	     unsigned int length_limit));
-
-/* Install a special processing method for COM or APPn markers. */
-EXTERN(void) jpeg_set_marker_processor
-	JPP((j_decompress_ptr cinfo, int marker_code,
-	     jpeg_marker_parser_method routine));
-
-/* Read or write raw DCT coefficients --- useful for lossless transcoding. */
-EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
-EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
-					  jvirt_barray_ptr * coef_arrays));
-EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
-						j_compress_ptr dstinfo));
-
-/* If you choose to abort compression or decompression before completing
- * jpeg_finish_(de)compress, then you need to clean up to release memory,
- * temporary files, etc.  You can just call jpeg_destroy_(de)compress
- * if you're done with the JPEG object, but if you want to clean it up and
- * reuse it, call this:
- */
-EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
-EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
-
-/* Generic versions of jpeg_abort and jpeg_destroy that work on either
- * flavor of JPEG object.  These may be more convenient in some places.
- */
-EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
-EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
-
-/* Default restart-marker-resync procedure for use by data source modules */
-EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
-					    int desired));
-
-
-/* These marker codes are exported since applications and data source modules
- * are likely to want to use them.
- */
-
-#define JPEG_RST0	0xD0	/* RST0 marker code */
-#define JPEG_EOI	0xD9	/* EOI marker code */
-#define JPEG_APP0	0xE0	/* APP0 marker code */
-#define JPEG_COM	0xFE	/* COM marker code */
-
-
-/* If we have a brain-damaged compiler that emits warnings (or worse, errors)
- * for structure definitions that are never filled in, keep it quiet by
- * supplying dummy definitions for the various substructures.
- */
-
-#ifdef INCOMPLETE_TYPES_BROKEN
-#ifndef JPEG_INTERNALS		/* will be defined in jpegint.h */
-struct jvirt_sarray_control { long dummy; };
-struct jvirt_barray_control { long dummy; };
-struct jpeg_comp_master { long dummy; };
-struct jpeg_c_main_controller { long dummy; };
-struct jpeg_c_prep_controller { long dummy; };
-struct jpeg_c_coef_controller { long dummy; };
-struct jpeg_marker_writer { long dummy; };
-struct jpeg_color_converter { long dummy; };
-struct jpeg_downsampler { long dummy; };
-struct jpeg_forward_dct { long dummy; };
-struct jpeg_entropy_encoder { long dummy; };
-struct jpeg_decomp_master { long dummy; };
-struct jpeg_d_main_controller { long dummy; };
-struct jpeg_d_coef_controller { long dummy; };
-struct jpeg_d_post_controller { long dummy; };
-struct jpeg_input_controller { long dummy; };
-struct jpeg_marker_reader { long dummy; };
-struct jpeg_entropy_decoder { long dummy; };
-struct jpeg_inverse_dct { long dummy; };
-struct jpeg_upsampler { long dummy; };
-struct jpeg_color_deconverter { long dummy; };
-struct jpeg_color_quantizer { long dummy; };
-#endif /* JPEG_INTERNALS */
-#endif /* INCOMPLETE_TYPES_BROKEN */
-
-
-/*
- * The JPEG library modules define JPEG_INTERNALS before including this file.
- * The internal structure declarations are read only when that is true.
- * Applications using the library should not include jpegint.h, but may wish
- * to include jerror.h.
- */
-
-#ifdef JPEG_INTERNALS
-#include "jpegint.h"		/* fetch private declarations */
-#include "jerror.h"		/* fetch error codes too */
-#endif
-
-#endif /* JPEGLIB_H */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jquant1.c ./Shared/jpeg-6b/jquant1.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jquant1.c	Mon Dec  1 12:30:39 2003
+++ ./Shared/jpeg-6b/jquant1.c	Wed Dec 31 19:00:00 1969
@@ -1,856 +0,0 @@
-/*
- * jquant1.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains 1-pass color quantization (color mapping) routines.
- * These routines provide mapping to a fixed color map using equally spaced
- * color values.  Optional Floyd-Steinberg or ordered dithering is available.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-#ifdef QUANT_1PASS_SUPPORTED
-
-
-/*
- * The main purpose of 1-pass quantization is to provide a fast, if not very
- * high quality, colormapped output capability.  A 2-pass quantizer usually
- * gives better visual quality; however, for quantized grayscale output this
- * quantizer is perfectly adequate.  Dithering is highly recommended with this
- * quantizer, though you can turn it off if you really want to.
- *
- * In 1-pass quantization the colormap must be chosen in advance of seeing the
- * image.  We use a map consisting of all combinations of Ncolors[i] color
- * values for the i'th component.  The Ncolors[] values are chosen so that
- * their product, the total number of colors, is no more than that requested.
- * (In most cases, the product will be somewhat less.)
- *
- * Since the colormap is orthogonal, the representative value for each color
- * component can be determined without considering the other components;
- * then these indexes can be combined into a colormap index by a standard
- * N-dimensional-array-subscript calculation.  Most of the arithmetic involved
- * can be precalculated and stored in the lookup table colorindex[].
- * colorindex[i][j] maps pixel value j in component i to the nearest
- * representative value (grid plane) for that component; this index is
- * multiplied by the array stride for component i, so that the
- * index of the colormap entry closest to a given pixel value is just
- *    sum( colorindex[component-number][pixel-component-value] )
- * Aside from being fast, this scheme allows for variable spacing between
- * representative values with no additional lookup cost.
- *
- * If gamma correction has been applied in color conversion, it might be wise
- * to adjust the color grid spacing so that the representative colors are
- * equidistant in linear space.  At this writing, gamma correction is not
- * implemented by jdcolor, so nothing is done here.
- */
-
-
-/* Declarations for ordered dithering.
- *
- * We use a standard 16x16 ordered dither array.  The basic concept of ordered
- * dithering is described in many references, for instance Dale Schumacher's
- * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
- * In place of Schumacher's comparisons against a "threshold" value, we add a
- * "dither" value to the input pixel and then round the result to the nearest
- * output value.  The dither value is equivalent to (0.5 - threshold) times
- * the distance between output values.  For ordered dithering, we assume that
- * the output colors are equally spaced; if not, results will probably be
- * worse, since the dither may be too much or too little at a given point.
- *
- * The normal calculation would be to form pixel value + dither, range-limit
- * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
- * We can skip the separate range-limiting step by extending the colorindex
- * table in both directions.
- */
-
-#define ODITHER_SIZE  16	/* dimension of dither matrix */
-/* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
-#define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE)	/* # cells in matrix */
-#define ODITHER_MASK  (ODITHER_SIZE-1) /* mask for wrapping around counters */
-
-typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
-typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
-
-static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
-  /* Bayer's order-4 dither array.  Generated by the code given in
-   * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
-   * The values in this array must range from 0 to ODITHER_CELLS-1.
-   */
-  {   0,192, 48,240, 12,204, 60,252,  3,195, 51,243, 15,207, 63,255 },
-  { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
-  {  32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
-  { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
-  {   8,200, 56,248,  4,196, 52,244, 11,203, 59,251,  7,199, 55,247 },
-  { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
-  {  40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
-  { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
-  {   2,194, 50,242, 14,206, 62,254,  1,193, 49,241, 13,205, 61,253 },
-  { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
-  {  34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
-  { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
-  {  10,202, 58,250,  6,198, 54,246,  9,201, 57,249,  5,197, 53,245 },
-  { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
-  {  42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
-  { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
-};
-
-
-/* Declarations for Floyd-Steinberg dithering.
- *
- * Errors are accumulated into the array fserrors[], at a resolution of
- * 1/16th of a pixel count.  The error at a given pixel is propagated
- * to its not-yet-processed neighbors using the standard F-S fractions,
- *		...	(here)	7/16
- *		3/16	5/16	1/16
- * We work left-to-right on even rows, right-to-left on odd rows.
- *
- * We can get away with a single array (holding one row's worth of errors)
- * by using it to store the current row's errors at pixel columns not yet
- * processed, but the next row's errors at columns already processed.  We
- * need only a few extra variables to hold the errors immediately around the
- * current column.  (If we are lucky, those variables are in registers, but
- * even if not, they're probably cheaper to access than array elements are.)
- *
- * The fserrors[] array is indexed [component#][position].
- * We provide (#columns + 2) entries per component; the extra entry at each
- * end saves us from special-casing the first and last pixels.
- *
- * Note: on a wide image, we might not have enough room in a PC's near data
- * segment to hold the error array; so it is allocated with alloc_large.
- */
-
-#if BITS_IN_JSAMPLE == 8
-typedef INT16 FSERROR;		/* 16 bits should be enough */
-typedef int LOCFSERROR;		/* use 'int' for calculation temps */
-#else
-typedef INT32 FSERROR;		/* may need more than 16 bits */
-typedef INT32 LOCFSERROR;	/* be sure calculation temps are big enough */
-#endif
-
-typedef FSERROR FAR *FSERRPTR;	/* pointer to error array (in FAR storage!) */
-
-
-/* Private subobject */
-
-#define MAX_Q_COMPS 4		/* max components I can handle */
-
-typedef struct {
-  struct jpeg_color_quantizer pub; /* public fields */
-
-  /* Initially allocated colormap is saved here */
-  JSAMPARRAY sv_colormap;	/* The color map as a 2-D pixel array */
-  int sv_actual;		/* number of entries in use */
-
-  JSAMPARRAY colorindex;	/* Precomputed mapping for speed */
-  /* colorindex[i][j] = index of color closest to pixel value j in component i,
-   * premultiplied as described above.  Since colormap indexes must fit into
-   * JSAMPLEs, the entries of this array will too.
-   */
-  boolean is_padded;		/* is the colorindex padded for odither? */
-
-  int Ncolors[MAX_Q_COMPS];	/* # of values alloced to each component */
-
-  /* Variables for ordered dithering */
-  int row_index;		/* cur row's vertical index in dither matrix */
-  ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
-
-  /* Variables for Floyd-Steinberg dithering */
-  FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
-  boolean on_odd_row;		/* flag to remember which row we are on */
-} my_cquantizer;
-
-typedef my_cquantizer * my_cquantize_ptr;
-
-
-/*
- * Policy-making subroutines for create_colormap and create_colorindex.
- * These routines determine the colormap to be used.  The rest of the module
- * only assumes that the colormap is orthogonal.
- *
- *  * select_ncolors decides how to divvy up the available colors
- *    among the components.
- *  * output_value defines the set of representative values for a component.
- *  * largest_input_value defines the mapping from input values to
- *    representative values for a component.
- * Note that the latter two routines may impose different policies for
- * different components, though this is not currently done.
- */
-
-
-LOCAL(int)
-select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
-/* Determine allocation of desired colors to components, */
-/* and fill in Ncolors[] array to indicate choice. */
-/* Return value is total number of colors (product of Ncolors[] values). */
-{
-  int nc = cinfo->out_color_components; /* number of color components */
-  int max_colors = cinfo->desired_number_of_colors;
-  int total_colors, iroot, i, j;
-  boolean changed;
-  long temp;
-  static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
-
-  /* We can allocate at least the nc'th root of max_colors per component. */
-  /* Compute floor(nc'th root of max_colors). */
-  iroot = 1;
-  do {
-    iroot++;
-    temp = iroot;		/* set temp = iroot ** nc */
-    for (i = 1; i < nc; i++)
-      temp *= iroot;
-  } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
-  iroot--;			/* now iroot = floor(root) */
-
-  /* Must have at least 2 color values per component */
-  if (iroot < 2)
-    ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
-
-  /* Initialize to iroot color values for each component */
-  total_colors = 1;
-  for (i = 0; i < nc; i++) {
-    Ncolors[i] = iroot;
-    total_colors *= iroot;
-  }
-  /* We may be able to increment the count for one or more components without
-   * exceeding max_colors, though we know not all can be incremented.
-   * Sometimes, the first component can be incremented more than once!
-   * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
-   * In RGB colorspace, try to increment G first, then R, then B.
-   */
-  do {
-    changed = FALSE;
-    for (i = 0; i < nc; i++) {
-      j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
-      /* calculate new total_colors if Ncolors[j] is incremented */
-      temp = total_colors / Ncolors[j];
-      temp *= Ncolors[j]+1;	/* done in long arith to avoid oflo */
-      if (temp > (long) max_colors)
-	break;			/* won't fit, done with this pass */
-      Ncolors[j]++;		/* OK, apply the increment */
-      total_colors = (int) temp;
-      changed = TRUE;
-    }
-  } while (changed);
-
-  return total_colors;
-}
-
-
-LOCAL(int)
-output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
-/* Return j'th output value, where j will range from 0 to maxj */
-/* The output values must fall in 0..MAXJSAMPLE in increasing order */
-{
-  /* We always provide values 0 and MAXJSAMPLE for each component;
-   * any additional values are equally spaced between these limits.
-   * (Forcing the upper and lower values to the limits ensures that
-   * dithering can't produce a color outside the selected gamut.)
-   */
-  return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
-}
-
-
-LOCAL(int)
-largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
-/* Return largest input value that should map to j'th output value */
-/* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
-{
-  /* Breakpoints are halfway between values returned by output_value */
-  return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
-}
-
-
-/*
- * Create the colormap.
- */
-
-LOCAL(void)
-create_colormap (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  JSAMPARRAY colormap;		/* Created colormap */
-  int total_colors;		/* Number of distinct output colors */
-  int i,j,k, nci, blksize, blkdist, ptr, val;
-
-  /* Select number of colors for each component */
-  total_colors = select_ncolors(cinfo, cquantize->Ncolors);
-
-  /* Report selected color counts */
-  if (cinfo->out_color_components == 3)
-    TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
-	     total_colors, cquantize->Ncolors[0],
-	     cquantize->Ncolors[1], cquantize->Ncolors[2]);
-  else
-    TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
-
-  /* Allocate and fill in the colormap. */
-  /* The colors are ordered in the map in standard row-major order, */
-  /* i.e. rightmost (highest-indexed) color changes most rapidly. */
-
-  colormap = (*cinfo->mem->alloc_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE,
-     (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
-
-  /* blksize is number of adjacent repeated entries for a component */
-  /* blkdist is distance between groups of identical entries for a component */
-  blkdist = total_colors;
-
-  for (i = 0; i < cinfo->out_color_components; i++) {
-    /* fill in colormap entries for i'th color component */
-    nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
-    blksize = blkdist / nci;
-    for (j = 0; j < nci; j++) {
-      /* Compute j'th output value (out of nci) for component */
-      val = output_value(cinfo, i, j, nci-1);
-      /* Fill in all colormap entries that have this value of this component */
-      for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
-	/* fill in blksize entries beginning at ptr */
-	for (k = 0; k < blksize; k++)
-	  colormap[i][ptr+k] = (JSAMPLE) val;
-      }
-    }
-    blkdist = blksize;		/* blksize of this color is blkdist of next */
-  }
-
-  /* Save the colormap in private storage,
-   * where it will survive color quantization mode changes.
-   */
-  cquantize->sv_colormap = colormap;
-  cquantize->sv_actual = total_colors;
-}
-
-
-/*
- * Create the color index table.
- */
-
-LOCAL(void)
-create_colorindex (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  JSAMPROW indexptr;
-  int i,j,k, nci, blksize, val, pad;
-
-  /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
-   * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
-   * This is not necessary in the other dithering modes.  However, we
-   * flag whether it was done in case user changes dithering mode.
-   */
-  if (cinfo->dither_mode == JDITHER_ORDERED) {
-    pad = MAXJSAMPLE*2;
-    cquantize->is_padded = TRUE;
-  } else {
-    pad = 0;
-    cquantize->is_padded = FALSE;
-  }
-
-  cquantize->colorindex = (*cinfo->mem->alloc_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE,
-     (JDIMENSION) (MAXJSAMPLE+1 + pad),
-     (JDIMENSION) cinfo->out_color_components);
-
-  /* blksize is number of adjacent repeated entries for a component */
-  blksize = cquantize->sv_actual;
-
-  for (i = 0; i < cinfo->out_color_components; i++) {
-    /* fill in colorindex entries for i'th color component */
-    nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
-    blksize = blksize / nci;
-
-    /* adjust colorindex pointers to provide padding at negative indexes. */
-    if (pad)
-      cquantize->colorindex[i] += MAXJSAMPLE;
-
-    /* in loop, val = index of current output value, */
-    /* and k = largest j that maps to current val */
-    indexptr = cquantize->colorindex[i];
-    val = 0;
-    k = largest_input_value(cinfo, i, 0, nci-1);
-    for (j = 0; j <= MAXJSAMPLE; j++) {
-      while (j > k)		/* advance val if past boundary */
-	k = largest_input_value(cinfo, i, ++val, nci-1);
-      /* premultiply so that no multiplication needed in main processing */
-      indexptr[j] = (JSAMPLE) (val * blksize);
-    }
-    /* Pad at both ends if necessary */
-    if (pad)
-      for (j = 1; j <= MAXJSAMPLE; j++) {
-	indexptr[-j] = indexptr[0];
-	indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
-      }
-  }
-}
-
-
-/*
- * Create an ordered-dither array for a component having ncolors
- * distinct output values.
- */
-
-LOCAL(ODITHER_MATRIX_PTR)
-make_odither_array (j_decompress_ptr cinfo, int ncolors)
-{
-  ODITHER_MATRIX_PTR odither;
-  int j,k;
-  INT32 num,den;
-
-  odither = (ODITHER_MATRIX_PTR)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(ODITHER_MATRIX));
-  /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
-   * Hence the dither value for the matrix cell with fill order f
-   * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
-   * On 16-bit-int machine, be careful to avoid overflow.
-   */
-  den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
-  for (j = 0; j < ODITHER_SIZE; j++) {
-    for (k = 0; k < ODITHER_SIZE; k++) {
-      num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
-	    * MAXJSAMPLE;
-      /* Ensure round towards zero despite C's lack of consistency
-       * about rounding negative values in integer division...
-       */
-      odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
-    }
-  }
-  return odither;
-}
-
-
-/*
- * Create the ordered-dither tables.
- * Components having the same number of representative colors may 
- * share a dither table.
- */
-
-LOCAL(void)
-create_odither_tables (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  ODITHER_MATRIX_PTR odither;
-  int i, j, nci;
-
-  for (i = 0; i < cinfo->out_color_components; i++) {
-    nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
-    odither = NULL;		/* search for matching prior component */
-    for (j = 0; j < i; j++) {
-      if (nci == cquantize->Ncolors[j]) {
-	odither = cquantize->odither[j];
-	break;
-      }
-    }
-    if (odither == NULL)	/* need a new table? */
-      odither = make_odither_array(cinfo, nci);
-    cquantize->odither[i] = odither;
-  }
-}
-
-
-/*
- * Map some rows of pixels to the output colormapped representation.
- */
-
-METHODDEF(void)
-color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
-		JSAMPARRAY output_buf, int num_rows)
-/* General case, no dithering */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  JSAMPARRAY colorindex = cquantize->colorindex;
-  register int pixcode, ci;
-  register JSAMPROW ptrin, ptrout;
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-  register int nc = cinfo->out_color_components;
-
-  for (row = 0; row < num_rows; row++) {
-    ptrin = input_buf[row];
-    ptrout = output_buf[row];
-    for (col = width; col > 0; col--) {
-      pixcode = 0;
-      for (ci = 0; ci < nc; ci++) {
-	pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
-      }
-      *ptrout++ = (JSAMPLE) pixcode;
-    }
-  }
-}
-
-
-METHODDEF(void)
-color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
-		 JSAMPARRAY output_buf, int num_rows)
-/* Fast path for out_color_components==3, no dithering */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  register int pixcode;
-  register JSAMPROW ptrin, ptrout;
-  JSAMPROW colorindex0 = cquantize->colorindex[0];
-  JSAMPROW colorindex1 = cquantize->colorindex[1];
-  JSAMPROW colorindex2 = cquantize->colorindex[2];
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-
-  for (row = 0; row < num_rows; row++) {
-    ptrin = input_buf[row];
-    ptrout = output_buf[row];
-    for (col = width; col > 0; col--) {
-      pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
-      pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
-      pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
-      *ptrout++ = (JSAMPLE) pixcode;
-    }
-  }
-}
-
-
-METHODDEF(void)
-quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
-		     JSAMPARRAY output_buf, int num_rows)
-/* General case, with ordered dithering */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  register JSAMPROW input_ptr;
-  register JSAMPROW output_ptr;
-  JSAMPROW colorindex_ci;
-  int * dither;			/* points to active row of dither matrix */
-  int row_index, col_index;	/* current indexes into dither matrix */
-  int nc = cinfo->out_color_components;
-  int ci;
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-
-  for (row = 0; row < num_rows; row++) {
-    /* Initialize output values to 0 so can process components separately */
-    jzero_far((void FAR *) output_buf[row],
-	      (size_t) (width * SIZEOF(JSAMPLE)));
-    row_index = cquantize->row_index;
-    for (ci = 0; ci < nc; ci++) {
-      input_ptr = input_buf[row] + ci;
-      output_ptr = output_buf[row];
-      colorindex_ci = cquantize->colorindex[ci];
-      dither = cquantize->odither[ci][row_index];
-      col_index = 0;
-
-      for (col = width; col > 0; col--) {
-	/* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
-	 * select output value, accumulate into output code for this pixel.
-	 * Range-limiting need not be done explicitly, as we have extended
-	 * the colorindex table to produce the right answers for out-of-range
-	 * inputs.  The maximum dither is +- MAXJSAMPLE; this sets the
-	 * required amount of padding.
-	 */
-	*output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
-	input_ptr += nc;
-	output_ptr++;
-	col_index = (col_index + 1) & ODITHER_MASK;
-      }
-    }
-    /* Advance row index for next row */
-    row_index = (row_index + 1) & ODITHER_MASK;
-    cquantize->row_index = row_index;
-  }
-}
-
-
-METHODDEF(void)
-quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
-		      JSAMPARRAY output_buf, int num_rows)
-/* Fast path for out_color_components==3, with ordered dithering */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  register int pixcode;
-  register JSAMPROW input_ptr;
-  register JSAMPROW output_ptr;
-  JSAMPROW colorindex0 = cquantize->colorindex[0];
-  JSAMPROW colorindex1 = cquantize->colorindex[1];
-  JSAMPROW colorindex2 = cquantize->colorindex[2];
-  int * dither0;		/* points to active row of dither matrix */
-  int * dither1;
-  int * dither2;
-  int row_index, col_index;	/* current indexes into dither matrix */
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-
-  for (row = 0; row < num_rows; row++) {
-    row_index = cquantize->row_index;
-    input_ptr = input_buf[row];
-    output_ptr = output_buf[row];
-    dither0 = cquantize->odither[0][row_index];
-    dither1 = cquantize->odither[1][row_index];
-    dither2 = cquantize->odither[2][row_index];
-    col_index = 0;
-
-    for (col = width; col > 0; col--) {
-      pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
-					dither0[col_index]]);
-      pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
-					dither1[col_index]]);
-      pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
-					dither2[col_index]]);
-      *output_ptr++ = (JSAMPLE) pixcode;
-      col_index = (col_index + 1) & ODITHER_MASK;
-    }
-    row_index = (row_index + 1) & ODITHER_MASK;
-    cquantize->row_index = row_index;
-  }
-}
-
-
-METHODDEF(void)
-quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
-		    JSAMPARRAY output_buf, int num_rows)
-/* General case, with Floyd-Steinberg dithering */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  register LOCFSERROR cur;	/* current error or pixel value */
-  LOCFSERROR belowerr;		/* error for pixel below cur */
-  LOCFSERROR bpreverr;		/* error for below/prev col */
-  LOCFSERROR bnexterr;		/* error for below/next col */
-  LOCFSERROR delta;
-  register FSERRPTR errorptr;	/* => fserrors[] at column before current */
-  register JSAMPROW input_ptr;
-  register JSAMPROW output_ptr;
-  JSAMPROW colorindex_ci;
-  JSAMPROW colormap_ci;
-  int pixcode;
-  int nc = cinfo->out_color_components;
-  int dir;			/* 1 for left-to-right, -1 for right-to-left */
-  int dirnc;			/* dir * nc */
-  int ci;
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-  JSAMPLE *range_limit = cinfo->sample_range_limit;
-  SHIFT_TEMPS
-
-  for (row = 0; row < num_rows; row++) {
-    /* Initialize output values to 0 so can process components separately */
-    jzero_far((void FAR *) output_buf[row],
-	      (size_t) (width * SIZEOF(JSAMPLE)));
-    for (ci = 0; ci < nc; ci++) {
-      input_ptr = input_buf[row] + ci;
-      output_ptr = output_buf[row];
-      if (cquantize->on_odd_row) {
-	/* work right to left in this row */
-	input_ptr += (width-1) * nc; /* so point to rightmost pixel */
-	output_ptr += width-1;
-	dir = -1;
-	dirnc = -nc;
-	errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
-      } else {
-	/* work left to right in this row */
-	dir = 1;
-	dirnc = nc;
-	errorptr = cquantize->fserrors[ci]; /* => entry before first column */
-      }
-      colorindex_ci = cquantize->colorindex[ci];
-      colormap_ci = cquantize->sv_colormap[ci];
-      /* Preset error values: no error propagated to first pixel from left */
-      cur = 0;
-      /* and no error propagated to row below yet */
-      belowerr = bpreverr = 0;
-
-      for (col = width; col > 0; col--) {
-	/* cur holds the error propagated from the previous pixel on the
-	 * current line.  Add the error propagated from the previous line
-	 * to form the complete error correction term for this pixel, and
-	 * round the error term (which is expressed * 16) to an integer.
-	 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
-	 * for either sign of the error value.
-	 * Note: errorptr points to *previous* column's array entry.
-	 */
-	cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
-	/* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
-	 * The maximum error is +- MAXJSAMPLE; this sets the required size
-	 * of the range_limit array.
-	 */
-	cur += GETJSAMPLE(*input_ptr);
-	cur = GETJSAMPLE(range_limit[cur]);
-	/* Select output value, accumulate into output code for this pixel */
-	pixcode = GETJSAMPLE(colorindex_ci[cur]);
-	*output_ptr += (JSAMPLE) pixcode;
-	/* Compute actual representation error at this pixel */
-	/* Note: we can do this even though we don't have the final */
-	/* pixel code, because the colormap is orthogonal. */
-	cur -= GETJSAMPLE(colormap_ci[pixcode]);
-	/* Compute error fractions to be propagated to adjacent pixels.
-	 * Add these into the running sums, and simultaneously shift the
-	 * next-line error sums left by 1 column.
-	 */
-	bnexterr = cur;
-	delta = cur * 2;
-	cur += delta;		/* form error * 3 */
-	errorptr[0] = (FSERROR) (bpreverr + cur);
-	cur += delta;		/* form error * 5 */
-	bpreverr = belowerr + cur;
-	belowerr = bnexterr;
-	cur += delta;		/* form error * 7 */
-	/* At this point cur contains the 7/16 error value to be propagated
-	 * to the next pixel on the current line, and all the errors for the
-	 * next line have been shifted over. We are therefore ready to move on.
-	 */
-	input_ptr += dirnc;	/* advance input ptr to next column */
-	output_ptr += dir;	/* advance output ptr to next column */
-	errorptr += dir;	/* advance errorptr to current column */
-      }
-      /* Post-loop cleanup: we must unload the final error value into the
-       * final fserrors[] entry.  Note we need not unload belowerr because
-       * it is for the dummy column before or after the actual array.
-       */
-      errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
-    }
-    cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
-  }
-}
-
-
-/*
- * Allocate workspace for Floyd-Steinberg errors.
- */
-
-LOCAL(void)
-alloc_fs_workspace (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  size_t arraysize;
-  int i;
-
-  arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
-  for (i = 0; i < cinfo->out_color_components; i++) {
-    cquantize->fserrors[i] = (FSERRPTR)
-      (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
-  }
-}
-
-
-/*
- * Initialize for one-pass color quantization.
- */
-
-METHODDEF(void)
-start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  size_t arraysize;
-  int i;
-
-  /* Install my colormap. */
-  cinfo->colormap = cquantize->sv_colormap;
-  cinfo->actual_number_of_colors = cquantize->sv_actual;
-
-  /* Initialize for desired dithering mode. */
-  switch (cinfo->dither_mode) {
-  case JDITHER_NONE:
-    if (cinfo->out_color_components == 3)
-      cquantize->pub.color_quantize = color_quantize3;
-    else
-      cquantize->pub.color_quantize = color_quantize;
-    break;
-  case JDITHER_ORDERED:
-    if (cinfo->out_color_components == 3)
-      cquantize->pub.color_quantize = quantize3_ord_dither;
-    else
-      cquantize->pub.color_quantize = quantize_ord_dither;
-    cquantize->row_index = 0;	/* initialize state for ordered dither */
-    /* If user changed to ordered dither from another mode,
-     * we must recreate the color index table with padding.
-     * This will cost extra space, but probably isn't very likely.
-     */
-    if (! cquantize->is_padded)
-      create_colorindex(cinfo);
-    /* Create ordered-dither tables if we didn't already. */
-    if (cquantize->odither[0] == NULL)
-      create_odither_tables(cinfo);
-    break;
-  case JDITHER_FS:
-    cquantize->pub.color_quantize = quantize_fs_dither;
-    cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
-    /* Allocate Floyd-Steinberg workspace if didn't already. */
-    if (cquantize->fserrors[0] == NULL)
-      alloc_fs_workspace(cinfo);
-    /* Initialize the propagated errors to zero. */
-    arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
-    for (i = 0; i < cinfo->out_color_components; i++)
-      jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
-    break;
-  default:
-    ERREXIT(cinfo, JERR_NOT_COMPILED);
-    break;
-  }
-}
-
-
-/*
- * Finish up at the end of the pass.
- */
-
-METHODDEF(void)
-finish_pass_1_quant (j_decompress_ptr cinfo)
-{
-  /* no work in 1-pass case */
-}
-
-
-/*
- * Switch to a new external colormap between output passes.
- * Shouldn't get to this module!
- */
-
-METHODDEF(void)
-new_color_map_1_quant (j_decompress_ptr cinfo)
-{
-  ERREXIT(cinfo, JERR_MODE_CHANGE);
-}
-
-
-/*
- * Module initialization routine for 1-pass color quantization.
- */
-
-GLOBAL(void)
-jinit_1pass_quantizer (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize;
-
-  cquantize = (my_cquantize_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_cquantizer));
-  cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
-  cquantize->pub.start_pass = start_pass_1_quant;
-  cquantize->pub.finish_pass = finish_pass_1_quant;
-  cquantize->pub.new_color_map = new_color_map_1_quant;
-  cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
-  cquantize->odither[0] = NULL;	/* Also flag odither arrays not allocated */
-
-  /* Make sure my internal arrays won't overflow */
-  if (cinfo->out_color_components > MAX_Q_COMPS)
-    ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
-  /* Make sure colormap indexes can be represented by JSAMPLEs */
-  if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
-    ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
-
-  /* Create the colormap and color index table. */
-  create_colormap(cinfo);
-  create_colorindex(cinfo);
-
-  /* Allocate Floyd-Steinberg workspace now if requested.
-   * We do this now since it is FAR storage and may affect the memory
-   * manager's space calculations.  If the user changes to FS dither
-   * mode in a later pass, we will allocate the space then, and will
-   * possibly overrun the max_memory_to_use setting.
-   */
-  if (cinfo->dither_mode == JDITHER_FS)
-    alloc_fs_workspace(cinfo);
-}
-
-#endif /* QUANT_1PASS_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jquant2.c ./Shared/jpeg-6b/jquant2.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jquant2.c	Mon Dec  1 12:30:39 2003
+++ ./Shared/jpeg-6b/jquant2.c	Wed Dec 31 19:00:00 1969
@@ -1,1310 +0,0 @@
-/*
- * jquant2.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains 2-pass color quantization (color mapping) routines.
- * These routines provide selection of a custom color map for an image,
- * followed by mapping of the image to that color map, with optional
- * Floyd-Steinberg dithering.
- * It is also possible to use just the second pass to map to an arbitrary
- * externally-given color map.
- *
- * Note: ordered dithering is not supported, since there isn't any fast
- * way to compute intercolor distances; it's unclear that ordered dither's
- * fundamental assumptions even hold with an irregularly spaced color map.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-#ifdef QUANT_2PASS_SUPPORTED
-
-
-/*
- * This module implements the well-known Heckbert paradigm for color
- * quantization.  Most of the ideas used here can be traced back to
- * Heckbert's seminal paper
- *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display",
- *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
- *
- * In the first pass over the image, we accumulate a histogram showing the
- * usage count of each possible color.  To keep the histogram to a reasonable
- * size, we reduce the precision of the input; typical practice is to retain
- * 5 or 6 bits per color, so that 8 or 4 different input values are counted
- * in the same histogram cell.
- *
- * Next, the color-selection step begins with a box representing the whole
- * color space, and repeatedly splits the "largest" remaining box until we
- * have as many boxes as desired colors.  Then the mean color in each
- * remaining box becomes one of the possible output colors.
- * 
- * The second pass over the image maps each input pixel to the closest output
- * color (optionally after applying a Floyd-Steinberg dithering correction).
- * This mapping is logically trivial, but making it go fast enough requires
- * considerable care.
- *
- * Heckbert-style quantizers vary a good deal in their policies for choosing
- * the "largest" box and deciding where to cut it.  The particular policies
- * used here have proved out well in experimental comparisons, but better ones
- * may yet be found.
- *
- * In earlier versions of the IJG code, this module quantized in YCbCr color
- * space, processing the raw upsampled data without a color conversion step.
- * This allowed the color conversion math to be done only once per colormap
- * entry, not once per pixel.  However, that optimization precluded other
- * useful optimizations (such as merging color conversion with upsampling)
- * and it also interfered with desired capabilities such as quantizing to an
- * externally-supplied colormap.  We have therefore abandoned that approach.
- * The present code works in the post-conversion color space, typically RGB.
- *
- * To improve the visual quality of the results, we actually work in scaled
- * RGB space, giving G distances more weight than R, and R in turn more than
- * B.  To do everything in integer math, we must use integer scale factors.
- * The 2/3/1 scale factors used here correspond loosely to the relative
- * weights of the colors in the NTSC grayscale equation.
- * If you want to use this code to quantize a non-RGB color space, you'll
- * probably need to change these scale factors.
- */
-
-#define R_SCALE 2		/* scale R distances by this much */
-#define G_SCALE 3		/* scale G distances by this much */
-#define B_SCALE 1		/* and B by this much */
-
-/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
- * in jmorecfg.h.  As the code stands, it will do the right thing for R,G,B
- * and B,G,R orders.  If you define some other weird order in jmorecfg.h,
- * you'll get compile errors until you extend this logic.  In that case
- * you'll probably want to tweak the histogram sizes too.
- */
-
-#if RGB_RED == 0
-#define C0_SCALE R_SCALE
-#endif
-#if RGB_BLUE == 0
-#define C0_SCALE B_SCALE
-#endif
-#if RGB_GREEN == 1
-#define C1_SCALE G_SCALE
-#endif
-#if RGB_RED == 2
-#define C2_SCALE R_SCALE
-#endif
-#if RGB_BLUE == 2
-#define C2_SCALE B_SCALE
-#endif
-
-
-/*
- * First we have the histogram data structure and routines for creating it.
- *
- * The number of bits of precision can be adjusted by changing these symbols.
- * We recommend keeping 6 bits for G and 5 each for R and B.
- * If you have plenty of memory and cycles, 6 bits all around gives marginally
- * better results; if you are short of memory, 5 bits all around will save
- * some space but degrade the results.
- * To maintain a fully accurate histogram, we'd need to allocate a "long"
- * (preferably unsigned long) for each cell.  In practice this is overkill;
- * we can get by with 16 bits per cell.  Few of the cell counts will overflow,
- * and clamping those that do overflow to the maximum value will give close-
- * enough results.  This reduces the recommended histogram size from 256Kb
- * to 128Kb, which is a useful savings on PC-class machines.
- * (In the second pass the histogram space is re-used for pixel mapping data;
- * in that capacity, each cell must be able to store zero to the number of
- * desired colors.  16 bits/cell is plenty for that too.)
- * Since the JPEG code is intended to run in small memory model on 80x86
- * machines, we can't just allocate the histogram in one chunk.  Instead
- * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each
- * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
- * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries.  Note that
- * on 80x86 machines, the pointer row is in near memory but the actual
- * arrays are in far memory (same arrangement as we use for image arrays).
- */
-
-#define MAXNUMCOLORS  (MAXJSAMPLE+1) /* maximum size of colormap */
-
-/* These will do the right thing for either R,G,B or B,G,R color order,
- * but you may not like the results for other color orders.
- */
-#define HIST_C0_BITS  5		/* bits of precision in R/B histogram */
-#define HIST_C1_BITS  6		/* bits of precision in G histogram */
-#define HIST_C2_BITS  5		/* bits of precision in B/R histogram */
-
-/* Number of elements along histogram axes. */
-#define HIST_C0_ELEMS  (1<<HIST_C0_BITS)
-#define HIST_C1_ELEMS  (1<<HIST_C1_BITS)
-#define HIST_C2_ELEMS  (1<<HIST_C2_BITS)
-
-/* These are the amounts to shift an input value to get a histogram index. */
-#define C0_SHIFT  (BITS_IN_JSAMPLE-HIST_C0_BITS)
-#define C1_SHIFT  (BITS_IN_JSAMPLE-HIST_C1_BITS)
-#define C2_SHIFT  (BITS_IN_JSAMPLE-HIST_C2_BITS)
-
-
-typedef UINT16 histcell;	/* histogram cell; prefer an unsigned type */
-
-typedef histcell FAR * histptr;	/* for pointers to histogram cells */
-
-typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
-typedef hist1d FAR * hist2d;	/* type for the 2nd-level pointers */
-typedef hist2d * hist3d;	/* type for top-level pointer */
-
-
-/* Declarations for Floyd-Steinberg dithering.
- *
- * Errors are accumulated into the array fserrors[], at a resolution of
- * 1/16th of a pixel count.  The error at a given pixel is propagated
- * to its not-yet-processed neighbors using the standard F-S fractions,
- *		...	(here)	7/16
- *		3/16	5/16	1/16
- * We work left-to-right on even rows, right-to-left on odd rows.
- *
- * We can get away with a single array (holding one row's worth of errors)
- * by using it to store the current row's errors at pixel columns not yet
- * processed, but the next row's errors at columns already processed.  We
- * need only a few extra variables to hold the errors immediately around the
- * current column.  (If we are lucky, those variables are in registers, but
- * even if not, they're probably cheaper to access than array elements are.)
- *
- * The fserrors[] array has (#columns + 2) entries; the extra entry at
- * each end saves us from special-casing the first and last pixels.
- * Each entry is three values long, one value for each color component.
- *
- * Note: on a wide image, we might not have enough room in a PC's near data
- * segment to hold the error array; so it is allocated with alloc_large.
- */
-
-#if BITS_IN_JSAMPLE == 8
-typedef INT16 FSERROR;		/* 16 bits should be enough */
-typedef int LOCFSERROR;		/* use 'int' for calculation temps */
-#else
-typedef INT32 FSERROR;		/* may need more than 16 bits */
-typedef INT32 LOCFSERROR;	/* be sure calculation temps are big enough */
-#endif
-
-typedef FSERROR FAR *FSERRPTR;	/* pointer to error array (in FAR storage!) */
-
-
-/* Private subobject */
-
-typedef struct {
-  struct jpeg_color_quantizer pub; /* public fields */
-
-  /* Space for the eventually created colormap is stashed here */
-  JSAMPARRAY sv_colormap;	/* colormap allocated at init time */
-  int desired;			/* desired # of colors = size of colormap */
-
-  /* Variables for accumulating image statistics */
-  hist3d histogram;		/* pointer to the histogram */
-
-  boolean needs_zeroed;		/* TRUE if next pass must zero histogram */
-
-  /* Variables for Floyd-Steinberg dithering */
-  FSERRPTR fserrors;		/* accumulated errors */
-  boolean on_odd_row;		/* flag to remember which row we are on */
-  int * error_limiter;		/* table for clamping the applied error */
-} my_cquantizer;
-
-typedef my_cquantizer * my_cquantize_ptr;
-
-
-/*
- * Prescan some rows of pixels.
- * In this module the prescan simply updates the histogram, which has been
- * initialized to zeroes by start_pass.
- * An output_buf parameter is required by the method signature, but no data
- * is actually output (in fact the buffer controller is probably passing a
- * NULL pointer).
- */
-
-METHODDEF(void)
-prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
-		  JSAMPARRAY output_buf, int num_rows)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  register JSAMPROW ptr;
-  register histptr histp;
-  register hist3d histogram = cquantize->histogram;
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-
-  for (row = 0; row < num_rows; row++) {
-    ptr = input_buf[row];
-    for (col = width; col > 0; col--) {
-      /* get pixel value and index into the histogram */
-      histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
-			 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
-			 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
-      /* increment, check for overflow and undo increment if so. */
-      if (++(*histp) <= 0)
-	(*histp)--;
-      ptr += 3;
-    }
-  }
-}
-
-
-/*
- * Next we have the really interesting routines: selection of a colormap
- * given the completed histogram.
- * These routines work with a list of "boxes", each representing a rectangular
- * subset of the input color space (to histogram precision).
- */
-
-typedef struct {
-  /* The bounds of the box (inclusive); expressed as histogram indexes */
-  int c0min, c0max;
-  int c1min, c1max;
-  int c2min, c2max;
-  /* The volume (actually 2-norm) of the box */
-  INT32 volume;
-  /* The number of nonzero histogram cells within this box */
-  long colorcount;
-} box;
-
-typedef box * boxptr;
-
-
-LOCAL(boxptr)
-find_biggest_color_pop (boxptr boxlist, int numboxes)
-/* Find the splittable box with the largest color population */
-/* Returns NULL if no splittable boxes remain */
-{
-  register boxptr boxp;
-  register int i;
-  register long maxc = 0;
-  boxptr which = NULL;
-  
-  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
-    if (boxp->colorcount > maxc && boxp->volume > 0) {
-      which = boxp;
-      maxc = boxp->colorcount;
-    }
-  }
-  return which;
-}
-
-
-LOCAL(boxptr)
-find_biggest_volume (boxptr boxlist, int numboxes)
-/* Find the splittable box with the largest (scaled) volume */
-/* Returns NULL if no splittable boxes remain */
-{
-  register boxptr boxp;
-  register int i;
-  register INT32 maxv = 0;
-  boxptr which = NULL;
-  
-  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
-    if (boxp->volume > maxv) {
-      which = boxp;
-      maxv = boxp->volume;
-    }
-  }
-  return which;
-}
-
-
-LOCAL(void)
-update_box (j_decompress_ptr cinfo, boxptr boxp)
-/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
-/* and recompute its volume and population */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  hist3d histogram = cquantize->histogram;
-  histptr histp;
-  int c0,c1,c2;
-  int c0min,c0max,c1min,c1max,c2min,c2max;
-  INT32 dist0,dist1,dist2;
-  long ccount;
-  
-  c0min = boxp->c0min;  c0max = boxp->c0max;
-  c1min = boxp->c1min;  c1max = boxp->c1max;
-  c2min = boxp->c2min;  c2max = boxp->c2max;
-  
-  if (c0max > c0min)
-    for (c0 = c0min; c0 <= c0max; c0++)
-      for (c1 = c1min; c1 <= c1max; c1++) {
-	histp = & histogram[c0][c1][c2min];
-	for (c2 = c2min; c2 <= c2max; c2++)
-	  if (*histp++ != 0) {
-	    boxp->c0min = c0min = c0;
-	    goto have_c0min;
-	  }
-      }
- have_c0min:
-  if (c0max > c0min)
-    for (c0 = c0max; c0 >= c0min; c0--)
-      for (c1 = c1min; c1 <= c1max; c1++) {
-	histp = & histogram[c0][c1][c2min];
-	for (c2 = c2min; c2 <= c2max; c2++)
-	  if (*histp++ != 0) {
-	    boxp->c0max = c0max = c0;
-	    goto have_c0max;
-	  }
-      }
- have_c0max:
-  if (c1max > c1min)
-    for (c1 = c1min; c1 <= c1max; c1++)
-      for (c0 = c0min; c0 <= c0max; c0++) {
-	histp = & histogram[c0][c1][c2min];
-	for (c2 = c2min; c2 <= c2max; c2++)
-	  if (*histp++ != 0) {
-	    boxp->c1min = c1min = c1;
-	    goto have_c1min;
-	  }
-      }
- have_c1min:
-  if (c1max > c1min)
-    for (c1 = c1max; c1 >= c1min; c1--)
-      for (c0 = c0min; c0 <= c0max; c0++) {
-	histp = & histogram[c0][c1][c2min];
-	for (c2 = c2min; c2 <= c2max; c2++)
-	  if (*histp++ != 0) {
-	    boxp->c1max = c1max = c1;
-	    goto have_c1max;
-	  }
-      }
- have_c1max:
-  if (c2max > c2min)
-    for (c2 = c2min; c2 <= c2max; c2++)
-      for (c0 = c0min; c0 <= c0max; c0++) {
-	histp = & histogram[c0][c1min][c2];
-	for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
-	  if (*histp != 0) {
-	    boxp->c2min = c2min = c2;
-	    goto have_c2min;
-	  }
-      }
- have_c2min:
-  if (c2max > c2min)
-    for (c2 = c2max; c2 >= c2min; c2--)
-      for (c0 = c0min; c0 <= c0max; c0++) {
-	histp = & histogram[c0][c1min][c2];
-	for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
-	  if (*histp != 0) {
-	    boxp->c2max = c2max = c2;
-	    goto have_c2max;
-	  }
-      }
- have_c2max:
-
-  /* Update box volume.
-   * We use 2-norm rather than real volume here; this biases the method
-   * against making long narrow boxes, and it has the side benefit that
-   * a box is splittable iff norm > 0.
-   * Since the differences are expressed in histogram-cell units,
-   * we have to shift back to JSAMPLE units to get consistent distances;
-   * after which, we scale according to the selected distance scale factors.
-   */
-  dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
-  dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
-  dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
-  boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
-  
-  /* Now scan remaining volume of box and compute population */
-  ccount = 0;
-  for (c0 = c0min; c0 <= c0max; c0++)
-    for (c1 = c1min; c1 <= c1max; c1++) {
-      histp = & histogram[c0][c1][c2min];
-      for (c2 = c2min; c2 <= c2max; c2++, histp++)
-	if (*histp != 0) {
-	  ccount++;
-	}
-    }
-  boxp->colorcount = ccount;
-}
-
-
-LOCAL(int)
-median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
-	    int desired_colors)
-/* Repeatedly select and split the largest box until we have enough boxes */
-{
-  int n,lb;
-  int c0,c1,c2,cmax;
-  register boxptr b1,b2;
-
-  while (numboxes < desired_colors) {
-    /* Select box to split.
-     * Current algorithm: by population for first half, then by volume.
-     */
-    if (numboxes*2 <= desired_colors) {
-      b1 = find_biggest_color_pop(boxlist, numboxes);
-    } else {
-      b1 = find_biggest_volume(boxlist, numboxes);
-    }
-    if (b1 == NULL)		/* no splittable boxes left! */
-      break;
-    b2 = &boxlist[numboxes];	/* where new box will go */
-    /* Copy the color bounds to the new box. */
-    b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
-    b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
-    /* Choose which axis to split the box on.
-     * Current algorithm: longest scaled axis.
-     * See notes in update_box about scaling distances.
-     */
-    c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
-    c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
-    c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
-    /* We want to break any ties in favor of green, then red, blue last.
-     * This code does the right thing for R,G,B or B,G,R color orders only.
-     */
-#if RGB_RED == 0
-    cmax = c1; n = 1;
-    if (c0 > cmax) { cmax = c0; n = 0; }
-    if (c2 > cmax) { n = 2; }
-#else
-    cmax = c1; n = 1;
-    if (c2 > cmax) { cmax = c2; n = 2; }
-    if (c0 > cmax) { n = 0; }
-#endif
-    /* Choose split point along selected axis, and update box bounds.
-     * Current algorithm: split at halfway point.
-     * (Since the box has been shrunk to minimum volume,
-     * any split will produce two nonempty subboxes.)
-     * Note that lb value is max for lower box, so must be < old max.
-     */
-    switch (n) {
-    case 0:
-      lb = (b1->c0max + b1->c0min) / 2;
-      b1->c0max = lb;
-      b2->c0min = lb+1;
-      break;
-    case 1:
-      lb = (b1->c1max + b1->c1min) / 2;
-      b1->c1max = lb;
-      b2->c1min = lb+1;
-      break;
-    case 2:
-      lb = (b1->c2max + b1->c2min) / 2;
-      b1->c2max = lb;
-      b2->c2min = lb+1;
-      break;
-    }
-    /* Update stats for boxes */
-    update_box(cinfo, b1);
-    update_box(cinfo, b2);
-    numboxes++;
-  }
-  return numboxes;
-}
-
-
-LOCAL(void)
-compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
-/* Compute representative color for a box, put it in colormap[icolor] */
-{
-  /* Current algorithm: mean weighted by pixels (not colors) */
-  /* Note it is important to get the rounding correct! */
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  hist3d histogram = cquantize->histogram;
-  histptr histp;
-  int c0,c1,c2;
-  int c0min,c0max,c1min,c1max,c2min,c2max;
-  long count;
-  long total = 0;
-  long c0total = 0;
-  long c1total = 0;
-  long c2total = 0;
-  
-  c0min = boxp->c0min;  c0max = boxp->c0max;
-  c1min = boxp->c1min;  c1max = boxp->c1max;
-  c2min = boxp->c2min;  c2max = boxp->c2max;
-  
-  for (c0 = c0min; c0 <= c0max; c0++)
-    for (c1 = c1min; c1 <= c1max; c1++) {
-      histp = & histogram[c0][c1][c2min];
-      for (c2 = c2min; c2 <= c2max; c2++) {
-	if ((count = *histp++) != 0) {
-	  total += count;
-	  c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
-	  c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
-	  c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
-	}
-      }
-    }
-  
-  cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
-  cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
-  cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
-}
-
-
-LOCAL(void)
-select_colors (j_decompress_ptr cinfo, int desired_colors)
-/* Master routine for color selection */
-{
-  boxptr boxlist;
-  int numboxes;
-  int i;
-
-  /* Allocate workspace for box list */
-  boxlist = (boxptr) (*cinfo->mem->alloc_small)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
-  /* Initialize one box containing whole space */
-  numboxes = 1;
-  boxlist[0].c0min = 0;
-  boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
-  boxlist[0].c1min = 0;
-  boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
-  boxlist[0].c2min = 0;
-  boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
-  /* Shrink it to actually-used volume and set its statistics */
-  update_box(cinfo, & boxlist[0]);
-  /* Perform median-cut to produce final box list */
-  numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
-  /* Compute the representative color for each box, fill colormap */
-  for (i = 0; i < numboxes; i++)
-    compute_color(cinfo, & boxlist[i], i);
-  cinfo->actual_number_of_colors = numboxes;
-  TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
-}
-
-
-/*
- * These routines are concerned with the time-critical task of mapping input
- * colors to the nearest color in the selected colormap.
- *
- * We re-use the histogram space as an "inverse color map", essentially a
- * cache for the results of nearest-color searches.  All colors within a
- * histogram cell will be mapped to the same colormap entry, namely the one
- * closest to the cell's center.  This may not be quite the closest entry to
- * the actual input color, but it's almost as good.  A zero in the cache
- * indicates we haven't found the nearest color for that cell yet; the array
- * is cleared to zeroes before starting the mapping pass.  When we find the
- * nearest color for a cell, its colormap index plus one is recorded in the
- * cache for future use.  The pass2 scanning routines call fill_inverse_cmap
- * when they need to use an unfilled entry in the cache.
- *
- * Our method of efficiently finding nearest colors is based on the "locally
- * sorted search" idea described by Heckbert and on the incremental distance
- * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
- * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that
- * the distances from a given colormap entry to each cell of the histogram can
- * be computed quickly using an incremental method: the differences between
- * distances to adjacent cells themselves differ by a constant.  This allows a
- * fairly fast implementation of the "brute force" approach of computing the
- * distance from every colormap entry to every histogram cell.  Unfortunately,
- * it needs a work array to hold the best-distance-so-far for each histogram
- * cell (because the inner loop has to be over cells, not colormap entries).
- * The work array elements have to be INT32s, so the work array would need
- * 256Kb at our recommended precision.  This is not feasible in DOS machines.
- *
- * To get around these problems, we apply Thomas' method to compute the
- * nearest colors for only the cells within a small subbox of the histogram.
- * The work array need be only as big as the subbox, so the memory usage
- * problem is solved.  Furthermore, we need not fill subboxes that are never
- * referenced in pass2; many images use only part of the color gamut, so a
- * fair amount of work is saved.  An additional advantage of this
- * approach is that we can apply Heckbert's locality criterion to quickly
- * eliminate colormap entries that are far away from the subbox; typically
- * three-fourths of the colormap entries are rejected by Heckbert's criterion,
- * and we need not compute their distances to individual cells in the subbox.
- * The speed of this approach is heavily influenced by the subbox size: too
- * small means too much overhead, too big loses because Heckbert's criterion
- * can't eliminate as many colormap entries.  Empirically the best subbox
- * size seems to be about 1/512th of the histogram (1/8th in each direction).
- *
- * Thomas' article also describes a refined method which is asymptotically
- * faster than the brute-force method, but it is also far more complex and
- * cannot efficiently be applied to small subboxes.  It is therefore not
- * useful for programs intended to be portable to DOS machines.  On machines
- * with plenty of memory, filling the whole histogram in one shot with Thomas'
- * refined method might be faster than the present code --- but then again,
- * it might not be any faster, and it's certainly more complicated.
- */
-
-
-/* log2(histogram cells in update box) for each axis; this can be adjusted */
-#define BOX_C0_LOG  (HIST_C0_BITS-3)
-#define BOX_C1_LOG  (HIST_C1_BITS-3)
-#define BOX_C2_LOG  (HIST_C2_BITS-3)
-
-#define BOX_C0_ELEMS  (1<<BOX_C0_LOG) /* # of hist cells in update box */
-#define BOX_C1_ELEMS  (1<<BOX_C1_LOG)
-#define BOX_C2_ELEMS  (1<<BOX_C2_LOG)
-
-#define BOX_C0_SHIFT  (C0_SHIFT + BOX_C0_LOG)
-#define BOX_C1_SHIFT  (C1_SHIFT + BOX_C1_LOG)
-#define BOX_C2_SHIFT  (C2_SHIFT + BOX_C2_LOG)
-
-
-/*
- * The next three routines implement inverse colormap filling.  They could
- * all be folded into one big routine, but splitting them up this way saves
- * some stack space (the mindist[] and bestdist[] arrays need not coexist)
- * and may allow some compilers to produce better code by registerizing more
- * inner-loop variables.
- */
-
-LOCAL(int)
-find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
-		    JSAMPLE colorlist[])
-/* Locate the colormap entries close enough to an update box to be candidates
- * for the nearest entry to some cell(s) in the update box.  The update box
- * is specified by the center coordinates of its first cell.  The number of
- * candidate colormap entries is returned, and their colormap indexes are
- * placed in colorlist[].
- * This routine uses Heckbert's "locally sorted search" criterion to select
- * the colors that need further consideration.
- */
-{
-  int numcolors = cinfo->actual_number_of_colors;
-  int maxc0, maxc1, maxc2;
-  int centerc0, centerc1, centerc2;
-  int i, x, ncolors;
-  INT32 minmaxdist, min_dist, max_dist, tdist;
-  INT32 mindist[MAXNUMCOLORS];	/* min distance to colormap entry i */
-
-  /* Compute true coordinates of update box's upper corner and center.
-   * Actually we compute the coordinates of the center of the upper-corner
-   * histogram cell, which are the upper bounds of the volume we care about.
-   * Note that since ">>" rounds down, the "center" values may be closer to
-   * min than to max; hence comparisons to them must be "<=", not "<".
-   */
-  maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
-  centerc0 = (minc0 + maxc0) >> 1;
-  maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
-  centerc1 = (minc1 + maxc1) >> 1;
-  maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
-  centerc2 = (minc2 + maxc2) >> 1;
-
-  /* For each color in colormap, find:
-   *  1. its minimum squared-distance to any point in the update box
-   *     (zero if color is within update box);
-   *  2. its maximum squared-distance to any point in the update box.
-   * Both of these can be found by considering only the corners of the box.
-   * We save the minimum distance for each color in mindist[];
-   * only the smallest maximum distance is of interest.
-   */
-  minmaxdist = 0x7FFFFFFFL;
-
-  for (i = 0; i < numcolors; i++) {
-    /* We compute the squared-c0-distance term, then add in the other two. */
-    x = GETJSAMPLE(cinfo->colormap[0][i]);
-    if (x < minc0) {
-      tdist = (x - minc0) * C0_SCALE;
-      min_dist = tdist*tdist;
-      tdist = (x - maxc0) * C0_SCALE;
-      max_dist = tdist*tdist;
-    } else if (x > maxc0) {
-      tdist = (x - maxc0) * C0_SCALE;
-      min_dist = tdist*tdist;
-      tdist = (x - minc0) * C0_SCALE;
-      max_dist = tdist*tdist;
-    } else {
-      /* within cell range so no contribution to min_dist */
-      min_dist = 0;
-      if (x <= centerc0) {
-	tdist = (x - maxc0) * C0_SCALE;
-	max_dist = tdist*tdist;
-      } else {
-	tdist = (x - minc0) * C0_SCALE;
-	max_dist = tdist*tdist;
-      }
-    }
-
-    x = GETJSAMPLE(cinfo->colormap[1][i]);
-    if (x < minc1) {
-      tdist = (x - minc1) * C1_SCALE;
-      min_dist += tdist*tdist;
-      tdist = (x - maxc1) * C1_SCALE;
-      max_dist += tdist*tdist;
-    } else if (x > maxc1) {
-      tdist = (x - maxc1) * C1_SCALE;
-      min_dist += tdist*tdist;
-      tdist = (x - minc1) * C1_SCALE;
-      max_dist += tdist*tdist;
-    } else {
-      /* within cell range so no contribution to min_dist */
-      if (x <= centerc1) {
-	tdist = (x - maxc1) * C1_SCALE;
-	max_dist += tdist*tdist;
-      } else {
-	tdist = (x - minc1) * C1_SCALE;
-	max_dist += tdist*tdist;
-      }
-    }
-
-    x = GETJSAMPLE(cinfo->colormap[2][i]);
-    if (x < minc2) {
-      tdist = (x - minc2) * C2_SCALE;
-      min_dist += tdist*tdist;
-      tdist = (x - maxc2) * C2_SCALE;
-      max_dist += tdist*tdist;
-    } else if (x > maxc2) {
-      tdist = (x - maxc2) * C2_SCALE;
-      min_dist += tdist*tdist;
-      tdist = (x - minc2) * C2_SCALE;
-      max_dist += tdist*tdist;
-    } else {
-      /* within cell range so no contribution to min_dist */
-      if (x <= centerc2) {
-	tdist = (x - maxc2) * C2_SCALE;
-	max_dist += tdist*tdist;
-      } else {
-	tdist = (x - minc2) * C2_SCALE;
-	max_dist += tdist*tdist;
-      }
-    }
-
-    mindist[i] = min_dist;	/* save away the results */
-    if (max_dist < minmaxdist)
-      minmaxdist = max_dist;
-  }
-
-  /* Now we know that no cell in the update box is more than minmaxdist
-   * away from some colormap entry.  Therefore, only colors that are
-   * within minmaxdist of some part of the box need be considered.
-   */
-  ncolors = 0;
-  for (i = 0; i < numcolors; i++) {
-    if (mindist[i] <= minmaxdist)
-      colorlist[ncolors++] = (JSAMPLE) i;
-  }
-  return ncolors;
-}
-
-
-LOCAL(void)
-find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
-		  int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
-/* Find the closest colormap entry for each cell in the update box,
- * given the list of candidate colors prepared by find_nearby_colors.
- * Return the indexes of the closest entries in the bestcolor[] array.
- * This routine uses Thomas' incremental distance calculation method to
- * find the distance from a colormap entry to successive cells in the box.
- */
-{
-  int ic0, ic1, ic2;
-  int i, icolor;
-  register INT32 * bptr;	/* pointer into bestdist[] array */
-  JSAMPLE * cptr;		/* pointer into bestcolor[] array */
-  INT32 dist0, dist1;		/* initial distance values */
-  register INT32 dist2;		/* current distance in inner loop */
-  INT32 xx0, xx1;		/* distance increments */
-  register INT32 xx2;
-  INT32 inc0, inc1, inc2;	/* initial values for increments */
-  /* This array holds the distance to the nearest-so-far color for each cell */
-  INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
-
-  /* Initialize best-distance for each cell of the update box */
-  bptr = bestdist;
-  for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
-    *bptr++ = 0x7FFFFFFFL;
-  
-  /* For each color selected by find_nearby_colors,
-   * compute its distance to the center of each cell in the box.
-   * If that's less than best-so-far, update best distance and color number.
-   */
-  
-  /* Nominal steps between cell centers ("x" in Thomas article) */
-#define STEP_C0  ((1 << C0_SHIFT) * C0_SCALE)
-#define STEP_C1  ((1 << C1_SHIFT) * C1_SCALE)
-#define STEP_C2  ((1 << C2_SHIFT) * C2_SCALE)
-  
-  for (i = 0; i < numcolors; i++) {
-    icolor = GETJSAMPLE(colorlist[i]);
-    /* Compute (square of) distance from minc0/c1/c2 to this color */
-    inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
-    dist0 = inc0*inc0;
-    inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
-    dist0 += inc1*inc1;
-    inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
-    dist0 += inc2*inc2;
-    /* Form the initial difference increments */
-    inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
-    inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
-    inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
-    /* Now loop over all cells in box, updating distance per Thomas method */
-    bptr = bestdist;
-    cptr = bestcolor;
-    xx0 = inc0;
-    for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
-      dist1 = dist0;
-      xx1 = inc1;
-      for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
-	dist2 = dist1;
-	xx2 = inc2;
-	for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
-	  if (dist2 < *bptr) {
-	    *bptr = dist2;
-	    *cptr = (JSAMPLE) icolor;
-	  }
-	  dist2 += xx2;
-	  xx2 += 2 * STEP_C2 * STEP_C2;
-	  bptr++;
-	  cptr++;
-	}
-	dist1 += xx1;
-	xx1 += 2 * STEP_C1 * STEP_C1;
-      }
-      dist0 += xx0;
-      xx0 += 2 * STEP_C0 * STEP_C0;
-    }
-  }
-}
-
-
-LOCAL(void)
-fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
-/* Fill the inverse-colormap entries in the update box that contains */
-/* histogram cell c0/c1/c2.  (Only that one cell MUST be filled, but */
-/* we can fill as many others as we wish.) */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  hist3d histogram = cquantize->histogram;
-  int minc0, minc1, minc2;	/* lower left corner of update box */
-  int ic0, ic1, ic2;
-  register JSAMPLE * cptr;	/* pointer into bestcolor[] array */
-  register histptr cachep;	/* pointer into main cache array */
-  /* This array lists the candidate colormap indexes. */
-  JSAMPLE colorlist[MAXNUMCOLORS];
-  int numcolors;		/* number of candidate colors */
-  /* This array holds the actually closest colormap index for each cell. */
-  JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
-
-  /* Convert cell coordinates to update box ID */
-  c0 >>= BOX_C0_LOG;
-  c1 >>= BOX_C1_LOG;
-  c2 >>= BOX_C2_LOG;
-
-  /* Compute true coordinates of update box's origin corner.
-   * Actually we compute the coordinates of the center of the corner
-   * histogram cell, which are the lower bounds of the volume we care about.
-   */
-  minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
-  minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
-  minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
-  
-  /* Determine which colormap entries are close enough to be candidates
-   * for the nearest entry to some cell in the update box.
-   */
-  numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
-
-  /* Determine the actually nearest colors. */
-  find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
-		   bestcolor);
-
-  /* Save the best color numbers (plus 1) in the main cache array */
-  c0 <<= BOX_C0_LOG;		/* convert ID back to base cell indexes */
-  c1 <<= BOX_C1_LOG;
-  c2 <<= BOX_C2_LOG;
-  cptr = bestcolor;
-  for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
-    for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
-      cachep = & histogram[c0+ic0][c1+ic1][c2];
-      for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
-	*cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
-      }
-    }
-  }
-}
-
-
-/*
- * Map some rows of pixels to the output colormapped representation.
- */
-
-METHODDEF(void)
-pass2_no_dither (j_decompress_ptr cinfo,
-		 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
-/* This version performs no dithering */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  hist3d histogram = cquantize->histogram;
-  register JSAMPROW inptr, outptr;
-  register histptr cachep;
-  register int c0, c1, c2;
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-
-  for (row = 0; row < num_rows; row++) {
-    inptr = input_buf[row];
-    outptr = output_buf[row];
-    for (col = width; col > 0; col--) {
-      /* get pixel value and index into the cache */
-      c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
-      c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
-      c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
-      cachep = & histogram[c0][c1][c2];
-      /* If we have not seen this color before, find nearest colormap entry */
-      /* and update the cache */
-      if (*cachep == 0)
-	fill_inverse_cmap(cinfo, c0,c1,c2);
-      /* Now emit the colormap index for this cell */
-      *outptr++ = (JSAMPLE) (*cachep - 1);
-    }
-  }
-}
-
-
-METHODDEF(void)
-pass2_fs_dither (j_decompress_ptr cinfo,
-		 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
-/* This version performs Floyd-Steinberg dithering */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  hist3d histogram = cquantize->histogram;
-  register LOCFSERROR cur0, cur1, cur2;	/* current error or pixel value */
-  LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
-  LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
-  register FSERRPTR errorptr;	/* => fserrors[] at column before current */
-  JSAMPROW inptr;		/* => current input pixel */
-  JSAMPROW outptr;		/* => current output pixel */
-  histptr cachep;
-  int dir;			/* +1 or -1 depending on direction */
-  int dir3;			/* 3*dir, for advancing inptr & errorptr */
-  int row;
-  JDIMENSION col;
-  JDIMENSION width = cinfo->output_width;
-  JSAMPLE *range_limit = cinfo->sample_range_limit;
-  int *error_limit = cquantize->error_limiter;
-  JSAMPROW colormap0 = cinfo->colormap[0];
-  JSAMPROW colormap1 = cinfo->colormap[1];
-  JSAMPROW colormap2 = cinfo->colormap[2];
-  SHIFT_TEMPS
-
-  for (row = 0; row < num_rows; row++) {
-    inptr = input_buf[row];
-    outptr = output_buf[row];
-    if (cquantize->on_odd_row) {
-      /* work right to left in this row */
-      inptr += (width-1) * 3;	/* so point to rightmost pixel */
-      outptr += width-1;
-      dir = -1;
-      dir3 = -3;
-      errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
-      cquantize->on_odd_row = FALSE; /* flip for next time */
-    } else {
-      /* work left to right in this row */
-      dir = 1;
-      dir3 = 3;
-      errorptr = cquantize->fserrors; /* => entry before first real column */
-      cquantize->on_odd_row = TRUE; /* flip for next time */
-    }
-    /* Preset error values: no error propagated to first pixel from left */
-    cur0 = cur1 = cur2 = 0;
-    /* and no error propagated to row below yet */
-    belowerr0 = belowerr1 = belowerr2 = 0;
-    bpreverr0 = bpreverr1 = bpreverr2 = 0;
-
-    for (col = width; col > 0; col--) {
-      /* curN holds the error propagated from the previous pixel on the
-       * current line.  Add the error propagated from the previous line
-       * to form the complete error correction term for this pixel, and
-       * round the error term (which is expressed * 16) to an integer.
-       * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
-       * for either sign of the error value.
-       * Note: errorptr points to *previous* column's array entry.
-       */
-      cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
-      cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
-      cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
-      /* Limit the error using transfer function set by init_error_limit.
-       * See comments with init_error_limit for rationale.
-       */
-      cur0 = error_limit[cur0];
-      cur1 = error_limit[cur1];
-      cur2 = error_limit[cur2];
-      /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
-       * The maximum error is +- MAXJSAMPLE (or less with error limiting);
-       * this sets the required size of the range_limit array.
-       */
-      cur0 += GETJSAMPLE(inptr[0]);
-      cur1 += GETJSAMPLE(inptr[1]);
-      cur2 += GETJSAMPLE(inptr[2]);
-      cur0 = GETJSAMPLE(range_limit[cur0]);
-      cur1 = GETJSAMPLE(range_limit[cur1]);
-      cur2 = GETJSAMPLE(range_limit[cur2]);
-      /* Index into the cache with adjusted pixel value */
-      cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
-      /* If we have not seen this color before, find nearest colormap */
-      /* entry and update the cache */
-      if (*cachep == 0)
-	fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
-      /* Now emit the colormap index for this cell */
-      { register int pixcode = *cachep - 1;
-	*outptr = (JSAMPLE) pixcode;
-	/* Compute representation error for this pixel */
-	cur0 -= GETJSAMPLE(colormap0[pixcode]);
-	cur1 -= GETJSAMPLE(colormap1[pixcode]);
-	cur2 -= GETJSAMPLE(colormap2[pixcode]);
-      }
-      /* Compute error fractions to be propagated to adjacent pixels.
-       * Add these into the running sums, and simultaneously shift the
-       * next-line error sums left by 1 column.
-       */
-      { register LOCFSERROR bnexterr, delta;
-
-	bnexterr = cur0;	/* Process component 0 */
-	delta = cur0 * 2;
-	cur0 += delta;		/* form error * 3 */
-	errorptr[0] = (FSERROR) (bpreverr0 + cur0);
-	cur0 += delta;		/* form error * 5 */
-	bpreverr0 = belowerr0 + cur0;
-	belowerr0 = bnexterr;
-	cur0 += delta;		/* form error * 7 */
-	bnexterr = cur1;	/* Process component 1 */
-	delta = cur1 * 2;
-	cur1 += delta;		/* form error * 3 */
-	errorptr[1] = (FSERROR) (bpreverr1 + cur1);
-	cur1 += delta;		/* form error * 5 */
-	bpreverr1 = belowerr1 + cur1;
-	belowerr1 = bnexterr;
-	cur1 += delta;		/* form error * 7 */
-	bnexterr = cur2;	/* Process component 2 */
-	delta = cur2 * 2;
-	cur2 += delta;		/* form error * 3 */
-	errorptr[2] = (FSERROR) (bpreverr2 + cur2);
-	cur2 += delta;		/* form error * 5 */
-	bpreverr2 = belowerr2 + cur2;
-	belowerr2 = bnexterr;
-	cur2 += delta;		/* form error * 7 */
-      }
-      /* At this point curN contains the 7/16 error value to be propagated
-       * to the next pixel on the current line, and all the errors for the
-       * next line have been shifted over.  We are therefore ready to move on.
-       */
-      inptr += dir3;		/* Advance pixel pointers to next column */
-      outptr += dir;
-      errorptr += dir3;		/* advance errorptr to current column */
-    }
-    /* Post-loop cleanup: we must unload the final error values into the
-     * final fserrors[] entry.  Note we need not unload belowerrN because
-     * it is for the dummy column before or after the actual array.
-     */
-    errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
-    errorptr[1] = (FSERROR) bpreverr1;
-    errorptr[2] = (FSERROR) bpreverr2;
-  }
-}
-
-
-/*
- * Initialize the error-limiting transfer function (lookup table).
- * The raw F-S error computation can potentially compute error values of up to
- * +- MAXJSAMPLE.  But we want the maximum correction applied to a pixel to be
- * much less, otherwise obviously wrong pixels will be created.  (Typical
- * effects include weird fringes at color-area boundaries, isolated bright
- * pixels in a dark area, etc.)  The standard advice for avoiding this problem
- * is to ensure that the "corners" of the color cube are allocated as output
- * colors; then repeated errors in the same direction cannot cause cascading
- * error buildup.  However, that only prevents the error from getting
- * completely out of hand; Aaron Giles reports that error limiting improves
- * the results even with corner colors allocated.
- * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
- * well, but the smoother transfer function used below is even better.  Thanks
- * to Aaron Giles for this idea.
- */
-
-LOCAL(void)
-init_error_limit (j_decompress_ptr cinfo)
-/* Allocate and fill in the error_limiter table */
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  int * table;
-  int in, out;
-
-  table = (int *) (*cinfo->mem->alloc_small)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
-  table += MAXJSAMPLE;		/* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
-  cquantize->error_limiter = table;
-
-#define STEPSIZE ((MAXJSAMPLE+1)/16)
-  /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
-  out = 0;
-  for (in = 0; in < STEPSIZE; in++, out++) {
-    table[in] = out; table[-in] = -out;
-  }
-  /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
-  for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
-    table[in] = out; table[-in] = -out;
-  }
-  /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
-  for (; in <= MAXJSAMPLE; in++) {
-    table[in] = out; table[-in] = -out;
-  }
-#undef STEPSIZE
-}
-
-
-/*
- * Finish up at the end of each pass.
- */
-
-METHODDEF(void)
-finish_pass1 (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-
-  /* Select the representative colors and fill in cinfo->colormap */
-  cinfo->colormap = cquantize->sv_colormap;
-  select_colors(cinfo, cquantize->desired);
-  /* Force next pass to zero the color index table */
-  cquantize->needs_zeroed = TRUE;
-}
-
-
-METHODDEF(void)
-finish_pass2 (j_decompress_ptr cinfo)
-{
-  /* no work */
-}
-
-
-/*
- * Initialize for each processing pass.
- */
-
-METHODDEF(void)
-start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-  hist3d histogram = cquantize->histogram;
-  int i;
-
-  /* Only F-S dithering or no dithering is supported. */
-  /* If user asks for ordered dither, give him F-S. */
-  if (cinfo->dither_mode != JDITHER_NONE)
-    cinfo->dither_mode = JDITHER_FS;
-
-  if (is_pre_scan) {
-    /* Set up method pointers */
-    cquantize->pub.color_quantize = prescan_quantize;
-    cquantize->pub.finish_pass = finish_pass1;
-    cquantize->needs_zeroed = TRUE; /* Always zero histogram */
-  } else {
-    /* Set up method pointers */
-    if (cinfo->dither_mode == JDITHER_FS)
-      cquantize->pub.color_quantize = pass2_fs_dither;
-    else
-      cquantize->pub.color_quantize = pass2_no_dither;
-    cquantize->pub.finish_pass = finish_pass2;
-
-    /* Make sure color count is acceptable */
-    i = cinfo->actual_number_of_colors;
-    if (i < 1)
-      ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
-    if (i > MAXNUMCOLORS)
-      ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
-
-    if (cinfo->dither_mode == JDITHER_FS) {
-      size_t arraysize = (size_t) ((cinfo->output_width + 2) *
-				   (3 * SIZEOF(FSERROR)));
-      /* Allocate Floyd-Steinberg workspace if we didn't already. */
-      if (cquantize->fserrors == NULL)
-	cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
-	  ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
-      /* Initialize the propagated errors to zero. */
-      jzero_far((void FAR *) cquantize->fserrors, arraysize);
-      /* Make the error-limit table if we didn't already. */
-      if (cquantize->error_limiter == NULL)
-	init_error_limit(cinfo);
-      cquantize->on_odd_row = FALSE;
-    }
-
-  }
-  /* Zero the histogram or inverse color map, if necessary */
-  if (cquantize->needs_zeroed) {
-    for (i = 0; i < HIST_C0_ELEMS; i++) {
-      jzero_far((void FAR *) histogram[i],
-		HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
-    }
-    cquantize->needs_zeroed = FALSE;
-  }
-}
-
-
-/*
- * Switch to a new external colormap between output passes.
- */
-
-METHODDEF(void)
-new_color_map_2_quant (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
-
-  /* Reset the inverse color map */
-  cquantize->needs_zeroed = TRUE;
-}
-
-
-/*
- * Module initialization routine for 2-pass color quantization.
- */
-
-GLOBAL(void)
-jinit_2pass_quantizer (j_decompress_ptr cinfo)
-{
-  my_cquantize_ptr cquantize;
-  int i;
-
-  cquantize = (my_cquantize_ptr)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				SIZEOF(my_cquantizer));
-  cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
-  cquantize->pub.start_pass = start_pass_2_quant;
-  cquantize->pub.new_color_map = new_color_map_2_quant;
-  cquantize->fserrors = NULL;	/* flag optional arrays not allocated */
-  cquantize->error_limiter = NULL;
-
-  /* Make sure jdmaster didn't give me a case I can't handle */
-  if (cinfo->out_color_components != 3)
-    ERREXIT(cinfo, JERR_NOTIMPL);
-
-  /* Allocate the histogram/inverse colormap storage */
-  cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
-  for (i = 0; i < HIST_C0_ELEMS; i++) {
-    cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
-  }
-  cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
-
-  /* Allocate storage for the completed colormap, if required.
-   * We do this now since it is FAR storage and may affect
-   * the memory manager's space calculations.
-   */
-  if (cinfo->enable_2pass_quant) {
-    /* Make sure color count is acceptable */
-    int desired = cinfo->desired_number_of_colors;
-    /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
-    if (desired < 8)
-      ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
-    /* Make sure colormap indexes can be represented by JSAMPLEs */
-    if (desired > MAXNUMCOLORS)
-      ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
-    cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
-    cquantize->desired = desired;
-  } else
-    cquantize->sv_colormap = NULL;
-
-  /* Only F-S dithering or no dithering is supported. */
-  /* If user asks for ordered dither, give him F-S. */
-  if (cinfo->dither_mode != JDITHER_NONE)
-    cinfo->dither_mode = JDITHER_FS;
-
-  /* Allocate Floyd-Steinberg workspace if necessary.
-   * This isn't really needed until pass 2, but again it is FAR storage.
-   * Although we will cope with a later change in dither_mode,
-   * we do not promise to honor max_memory_to_use if dither_mode changes.
-   */
-  if (cinfo->dither_mode == JDITHER_FS) {
-    cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
-    /* Might as well create the error-limiting table too. */
-    init_error_limit(cinfo);
-  }
-}
-
-#endif /* QUANT_2PASS_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jutils.c ./Shared/jpeg-6b/jutils.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jutils.c	Mon Dec  1 12:30:39 2003
+++ ./Shared/jpeg-6b/jutils.c	Wed Dec 31 19:00:00 1969
@@ -1,179 +0,0 @@
-/*
- * jutils.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains tables and miscellaneous utility routines needed
- * for both compression and decompression.
- * Note we prefix all global names with "j" to minimize conflicts with
- * a surrounding application.
- */
-
-#define JPEG_INTERNALS
-#include "jinclude.h"
-#include "jpeglib.h"
-
-
-/*
- * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
- * of a DCT block read in natural order (left to right, top to bottom).
- */
-
-#if 0				/* This table is not actually needed in v6a */
-
-const int jpeg_zigzag_order[DCTSIZE2] = {
-   0,  1,  5,  6, 14, 15, 27, 28,
-   2,  4,  7, 13, 16, 26, 29, 42,
-   3,  8, 12, 17, 25, 30, 41, 43,
-   9, 11, 18, 24, 31, 40, 44, 53,
-  10, 19, 23, 32, 39, 45, 52, 54,
-  20, 22, 33, 38, 46, 51, 55, 60,
-  21, 34, 37, 47, 50, 56, 59, 61,
-  35, 36, 48, 49, 57, 58, 62, 63
-};
-
-#endif
-
-/*
- * jpeg_natural_order[i] is the natural-order position of the i'th element
- * of zigzag order.
- *
- * When reading corrupted data, the Huffman decoders could attempt
- * to reference an entry beyond the end of this array (if the decoded
- * zero run length reaches past the end of the block).  To prevent
- * wild stores without adding an inner-loop test, we put some extra
- * "63"s after the real entries.  This will cause the extra coefficient
- * to be stored in location 63 of the block, not somewhere random.
- * The worst case would be a run-length of 15, which means we need 16
- * fake entries.
- */
-
-const int jpeg_natural_order[DCTSIZE2+16] = {
-  0,  1,  8, 16,  9,  2,  3, 10,
- 17, 24, 32, 25, 18, 11,  4,  5,
- 12, 19, 26, 33, 40, 48, 41, 34,
- 27, 20, 13,  6,  7, 14, 21, 28,
- 35, 42, 49, 56, 57, 50, 43, 36,
- 29, 22, 15, 23, 30, 37, 44, 51,
- 58, 59, 52, 45, 38, 31, 39, 46,
- 53, 60, 61, 54, 47, 55, 62, 63,
- 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
- 63, 63, 63, 63, 63, 63, 63, 63
-};
-
-
-/*
- * Arithmetic utilities
- */
-
-GLOBAL(long)
-jdiv_round_up (long a, long b)
-/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
-/* Assumes a >= 0, b > 0 */
-{
-  return (a + b - 1L) / b;
-}
-
-
-GLOBAL(long)
-jround_up (long a, long b)
-/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
-/* Assumes a >= 0, b > 0 */
-{
-  a += b - 1L;
-  return a - (a % b);
-}
-
-
-/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
- * and coefficient-block arrays.  This won't work on 80x86 because the arrays
- * are FAR and we're assuming a small-pointer memory model.  However, some
- * DOS compilers provide far-pointer versions of memcpy() and memset() even
- * in the small-model libraries.  These will be used if USE_FMEM is defined.
- * Otherwise, the routines below do it the hard way.  (The performance cost
- * is not all that great, because these routines aren't very heavily used.)
- */
-
-#ifndef NEED_FAR_POINTERS	/* normal case, same as regular macros */
-#define FMEMCOPY(dest,src,size)	MEMCOPY(dest,src,size)
-#define FMEMZERO(target,size)	MEMZERO(target,size)
-#else				/* 80x86 case, define if we can */
-#ifdef USE_FMEM
-#define FMEMCOPY(dest,src,size)	_fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
-#define FMEMZERO(target,size)	_fmemset((void FAR *)(target), 0, (size_t)(size))
-#endif
-#endif
-
-
-GLOBAL(void)
-jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
-		   JSAMPARRAY output_array, int dest_row,
-		   int num_rows, JDIMENSION num_cols)
-/* Copy some rows of samples from one place to another.
- * num_rows rows are copied from input_array[source_row++]
- * to output_array[dest_row++]; these areas may overlap for duplication.
- * The source and destination arrays must be at least as wide as num_cols.
- */
-{
-  register JSAMPROW inptr, outptr;
-#ifdef FMEMCOPY
-  register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
-#else
-  register JDIMENSION count;
-#endif
-  register int row;
-
-  input_array += source_row;
-  output_array += dest_row;
-
-  for (row = num_rows; row > 0; row--) {
-    inptr = *input_array++;
-    outptr = *output_array++;
-#ifdef FMEMCOPY
-    FMEMCOPY(outptr, inptr, count);
-#else
-    for (count = num_cols; count > 0; count--)
-      *outptr++ = *inptr++;	/* needn't bother with GETJSAMPLE() here */
-#endif
-  }
-}
-
-
-GLOBAL(void)
-jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
-		 JDIMENSION num_blocks)
-/* Copy a row of coefficient blocks from one place to another. */
-{
-#ifdef FMEMCOPY
-  FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
-#else
-  register JCOEFPTR inptr, outptr;
-  register long count;
-
-  inptr = (JCOEFPTR) input_row;
-  outptr = (JCOEFPTR) output_row;
-  for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
-    *outptr++ = *inptr++;
-  }
-#endif
-}
-
-
-GLOBAL(void)
-jzero_far (void FAR * target, size_t bytestozero)
-/* Zero out a chunk of FAR memory. */
-/* This might be sample-array data, block-array data, or alloc_large data. */
-{
-#ifdef FMEMZERO
-  FMEMZERO(target, bytestozero);
-#else
-  register char FAR * ptr = (char FAR *) target;
-  register size_t count;
-
-  for (count = bytestozero; count > 0; count--) {
-    *ptr++ = 0;
-  }
-#endif
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/jversion.h ./Shared/jpeg-6b/jversion.h
--- ../Tekkotsu_2.3/Shared/jpeg-6b/jversion.h	Mon Dec  1 12:30:39 2003
+++ ./Shared/jpeg-6b/jversion.h	Wed Dec 31 19:00:00 1969
@@ -1,14 +0,0 @@
-/*
- * jversion.h
- *
- * Copyright (C) 1991-1998, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains software version identification.
- */
-
-
-#define JVERSION	"6b  27-Mar-1998"
-
-#define JCOPYRIGHT	"Copyright (C) 1998, Thomas G. Lane"
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/libjpeg.doc ./Shared/jpeg-6b/libjpeg.doc
--- ../Tekkotsu_2.3/Shared/jpeg-6b/libjpeg.doc	Mon Dec  1 12:30:39 2003
+++ ./Shared/jpeg-6b/libjpeg.doc	Wed Dec 31 19:00:00 1969
@@ -1,3006 +0,0 @@
-USING THE IJG JPEG LIBRARY
-
-Copyright (C) 1994-1998, Thomas G. Lane.
-This file is part of the Independent JPEG Group's software.
-For conditions of distribution and use, see the accompanying README file.
-
-
-This file describes how to use the IJG JPEG library within an application
-program.  Read it if you want to write a program that uses the library.
-
-The file example.c provides heavily commented skeleton code for calling the
-JPEG library.  Also see jpeglib.h (the include file to be used by application
-programs) for full details about data structures and function parameter lists.
-The library source code, of course, is the ultimate reference.
-
-Note that there have been *major* changes from the application interface
-presented by IJG version 4 and earlier versions.  The old design had several
-inherent limitations, and it had accumulated a lot of cruft as we added
-features while trying to minimize application-interface changes.  We have
-sacrificed backward compatibility in the version 5 rewrite, but we think the
-improvements justify this.
-
-
-TABLE OF CONTENTS
------------------
-
-Overview:
-	Functions provided by the library
-	Outline of typical usage
-Basic library usage:
-	Data formats
-	Compression details
-	Decompression details
-	Mechanics of usage: include files, linking, etc
-Advanced features:
-	Compression parameter selection
-	Decompression parameter selection
-	Special color spaces
-	Error handling
-	Compressed data handling (source and destination managers)
-	I/O suspension
-	Progressive JPEG support
-	Buffered-image mode
-	Abbreviated datastreams and multiple images
-	Special markers
-	Raw (downsampled) image data
-	Really raw data: DCT coefficients
-	Progress monitoring
-	Memory management
-	Memory usage
-	Library compile-time options
-	Portability considerations
-	Notes for MS-DOS implementors
-
-You should read at least the overview and basic usage sections before trying
-to program with the library.  The sections on advanced features can be read
-if and when you need them.
-
-
-OVERVIEW
-========
-
-Functions provided by the library
----------------------------------
-
-The IJG JPEG library provides C code to read and write JPEG-compressed image
-files.  The surrounding application program receives or supplies image data a
-scanline at a time, using a straightforward uncompressed image format.  All
-details of color conversion and other preprocessing/postprocessing can be
-handled by the library.
-
-The library includes a substantial amount of code that is not covered by the
-JPEG standard but is necessary for typical applications of JPEG.  These
-functions preprocess the image before JPEG compression or postprocess it after
-decompression.  They include colorspace conversion, downsampling/upsampling,
-and color quantization.  The application indirectly selects use of this code
-by specifying the format in which it wishes to supply or receive image data.
-For example, if colormapped output is requested, then the decompression
-library automatically invokes color quantization.
-
-A wide range of quality vs. speed tradeoffs are possible in JPEG processing,
-and even more so in decompression postprocessing.  The decompression library
-provides multiple implementations that cover most of the useful tradeoffs,
-ranging from very-high-quality down to fast-preview operation.  On the
-compression side we have generally not provided low-quality choices, since
-compression is normally less time-critical.  It should be understood that the
-low-quality modes may not meet the JPEG standard's accuracy requirements;
-nonetheless, they are useful for viewers.
-
-A word about functions *not* provided by the library.  We handle a subset of
-the ISO JPEG standard; most baseline, extended-sequential, and progressive
-JPEG processes are supported.  (Our subset includes all features now in common
-use.)  Unsupported ISO options include:
-	* Hierarchical storage
-	* Lossless JPEG
-	* Arithmetic entropy coding (unsupported for legal reasons)
-	* DNL marker
-	* Nonintegral subsampling ratios
-We support both 8- and 12-bit data precision, but this is a compile-time
-choice rather than a run-time choice; hence it is difficult to use both
-precisions in a single application.
-
-By itself, the library handles only interchange JPEG datastreams --- in
-particular the widely used JFIF file format.  The library can be used by
-surrounding code to process interchange or abbreviated JPEG datastreams that
-are embedded in more complex file formats.  (For example, this library is
-used by the free LIBTIFF library to support JPEG compression in TIFF.)
-
-
-Outline of typical usage
-------------------------
-
-The rough outline of a JPEG compression operation is:
-
-	Allocate and initialize a JPEG compression object
-	Specify the destination for the compressed data (eg, a file)
-	Set parameters for compression, including image size & colorspace
-	jpeg_start_compress(...);
-	while (scan lines remain to be written)
-		jpeg_write_scanlines(...);
-	jpeg_finish_compress(...);
-	Release the JPEG compression object
-
-A JPEG compression object holds parameters and working state for the JPEG
-library.  We make creation/destruction of the object separate from starting
-or finishing compression of an image; the same object can be re-used for a
-series of image compression operations.  This makes it easy to re-use the
-same parameter settings for a sequence of images.  Re-use of a JPEG object
-also has important implications for processing abbreviated JPEG datastreams,
-as discussed later.
-
-The image data to be compressed is supplied to jpeg_write_scanlines() from
-in-memory buffers.  If the application is doing file-to-file compression,
-reading image data from the source file is the application's responsibility.
-The library emits compressed data by calling a "data destination manager",
-which typically will write the data into a file; but the application can
-provide its own destination manager to do something else.
-
-Similarly, the rough outline of a JPEG decompression operation is:
-
-	Allocate and initialize a JPEG decompression object
-	Specify the source of the compressed data (eg, a file)
-	Call jpeg_read_header() to obtain image info
-	Set parameters for decompression
-	jpeg_start_decompress(...);
-	while (scan lines remain to be read)
-		jpeg_read_scanlines(...);
-	jpeg_finish_decompress(...);
-	Release the JPEG decompression object
-
-This is comparable to the compression outline except that reading the
-datastream header is a separate step.  This is helpful because information
-about the image's size, colorspace, etc is available when the application
-selects decompression parameters.  For example, the application can choose an
-output scaling ratio that will fit the image into the available screen size.
-
-The decompression library obtains compressed data by calling a data source
-manager, which typically will read the data from a file; but other behaviors
-can be obtained with a custom source manager.  Decompressed data is delivered
-into in-memory buffers passed to jpeg_read_scanlines().
-
-It is possible to abort an incomplete compression or decompression operation
-by calling jpeg_abort(); or, if you do not need to retain the JPEG object,
-simply release it by calling jpeg_destroy().
-
-JPEG compression and decompression objects are two separate struct types.
-However, they share some common fields, and certain routines such as
-jpeg_destroy() can work on either type of object.
-
-The JPEG library has no static variables: all state is in the compression
-or decompression object.  Therefore it is possible to process multiple
-compression and decompression operations concurrently, using multiple JPEG
-objects.
-
-Both compression and decompression can be done in an incremental memory-to-
-memory fashion, if suitable source/destination managers are used.  See the
-section on "I/O suspension" for more details.
-
-
-BASIC LIBRARY USAGE
-===================
-
-Data formats
-------------
-
-Before diving into procedural details, it is helpful to understand the
-image data format that the JPEG library expects or returns.
-
-The standard input image format is a rectangular array of pixels, with each
-pixel having the same number of "component" or "sample" values (color
-channels).  You must specify how many components there are and the colorspace
-interpretation of the components.  Most applications will use RGB data
-(three components per pixel) or grayscale data (one component per pixel).
-PLEASE NOTE THAT RGB DATA IS THREE SAMPLES PER PIXEL, GRAYSCALE ONLY ONE.
-A remarkable number of people manage to miss this, only to find that their
-programs don't work with grayscale JPEG files.
-
-There is no provision for colormapped input.  JPEG files are always full-color
-or full grayscale (or sometimes another colorspace such as CMYK).  You can
-feed in a colormapped image by expanding it to full-color format.  However
-JPEG often doesn't work very well with source data that has been colormapped,
-because of dithering noise.  This is discussed in more detail in the JPEG FAQ
-and the other references mentioned in the README file.
-
-Pixels are stored by scanlines, with each scanline running from left to
-right.  The component values for each pixel are adjacent in the row; for
-example, R,G,B,R,G,B,R,G,B,... for 24-bit RGB color.  Each scanline is an
-array of data type JSAMPLE --- which is typically "unsigned char", unless
-you've changed jmorecfg.h.  (You can also change the RGB pixel layout, say
-to B,G,R order, by modifying jmorecfg.h.  But see the restrictions listed in
-that file before doing so.)
-
-A 2-D array of pixels is formed by making a list of pointers to the starts of
-scanlines; so the scanlines need not be physically adjacent in memory.  Even
-if you process just one scanline at a time, you must make a one-element
-pointer array to conform to this structure.  Pointers to JSAMPLE rows are of
-type JSAMPROW, and the pointer to the pointer array is of type JSAMPARRAY.
-
-The library accepts or supplies one or more complete scanlines per call.
-It is not possible to process part of a row at a time.  Scanlines are always
-processed top-to-bottom.  You can process an entire image in one call if you
-have it all in memory, but usually it's simplest to process one scanline at
-a time.
-
-For best results, source data values should have the precision specified by
-BITS_IN_JSAMPLE (normally 8 bits).  For instance, if you choose to compress
-data that's only 6 bits/channel, you should left-justify each value in a
-byte before passing it to the compressor.  If you need to compress data
-that has more than 8 bits/channel, compile with BITS_IN_JSAMPLE = 12.
-(See "Library compile-time options", later.)
-
-
-The data format returned by the decompressor is the same in all details,
-except that colormapped output is supported.  (Again, a JPEG file is never
-colormapped.  But you can ask the decompressor to perform on-the-fly color
-quantization to deliver colormapped output.)  If you request colormapped
-output then the returned data array contains a single JSAMPLE per pixel;
-its value is an index into a color map.  The color map is represented as
-a 2-D JSAMPARRAY in which each row holds the values of one color component,
-that is, colormap[i][j] is the value of the i'th color component for pixel
-value (map index) j.  Note that since the colormap indexes are stored in
-JSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE
-(ie, at most 256 colors for an 8-bit JPEG library).
-
-
-Compression details
--------------------
-
-Here we revisit the JPEG compression outline given in the overview.
-
-1. Allocate and initialize a JPEG compression object.
-
-A JPEG compression object is a "struct jpeg_compress_struct".  (It also has
-a bunch of subsidiary structures which are allocated via malloc(), but the
-application doesn't control those directly.)  This struct can be just a local
-variable in the calling routine, if a single routine is going to execute the
-whole JPEG compression sequence.  Otherwise it can be static or allocated
-from malloc().
-
-You will also need a structure representing a JPEG error handler.  The part
-of this that the library cares about is a "struct jpeg_error_mgr".  If you
-are providing your own error handler, you'll typically want to embed the
-jpeg_error_mgr struct in a larger structure; this is discussed later under
-"Error handling".  For now we'll assume you are just using the default error
-handler.  The default error handler will print JPEG error/warning messages
-on stderr, and it will call exit() if a fatal error occurs.
-
-You must initialize the error handler structure, store a pointer to it into
-the JPEG object's "err" field, and then call jpeg_create_compress() to
-initialize the rest of the JPEG object.
-
-Typical code for this step, if you are using the default error handler, is
-
-	struct jpeg_compress_struct cinfo;
-	struct jpeg_error_mgr jerr;
-	...
-	cinfo.err = jpeg_std_error(&jerr);
-	jpeg_create_compress(&cinfo);
-
-jpeg_create_compress allocates a small amount of memory, so it could fail
-if you are out of memory.  In that case it will exit via the error handler;
-that's why the error handler must be initialized first.
-
-
-2. Specify the destination for the compressed data (eg, a file).
-
-As previously mentioned, the JPEG library delivers compressed data to a
-"data destination" module.  The library includes one data destination
-module which knows how to write to a stdio stream.  You can use your own
-destination module if you want to do something else, as discussed later.
-
-If you use the standard destination module, you must open the target stdio
-stream beforehand.  Typical code for this step looks like:
-
-	FILE * outfile;
-	...
-	if ((outfile = fopen(filename, "wb")) == NULL) {
-	    fprintf(stderr, "can't open %s\n", filename);
-	    exit(1);
-	}
-	jpeg_stdio_dest(&cinfo, outfile);
-
-where the last line invokes the standard destination module.
-
-WARNING: it is critical that the binary compressed data be delivered to the
-output file unchanged.  On non-Unix systems the stdio library may perform
-newline translation or otherwise corrupt binary data.  To suppress this
-behavior, you may need to use a "b" option to fopen (as shown above), or use
-setmode() or another routine to put the stdio stream in binary mode.  See
-cjpeg.c and djpeg.c for code that has been found to work on many systems.
-
-You can select the data destination after setting other parameters (step 3),
-if that's more convenient.  You may not change the destination between
-calling jpeg_start_compress() and jpeg_finish_compress().
-
-
-3. Set parameters for compression, including image size & colorspace.
-
-You must supply information about the source image by setting the following
-fields in the JPEG object (cinfo structure):
-
-	image_width		Width of image, in pixels
-	image_height		Height of image, in pixels
-	input_components	Number of color channels (samples per pixel)
-	in_color_space		Color space of source image
-
-The image dimensions are, hopefully, obvious.  JPEG supports image dimensions
-of 1 to 64K pixels in either direction.  The input color space is typically
-RGB or grayscale, and input_components is 3 or 1 accordingly.  (See "Special
-color spaces", later, for more info.)  The in_color_space field must be
-assigned one of the J_COLOR_SPACE enum constants, typically JCS_RGB or
-JCS_GRAYSCALE.
-
-JPEG has a large number of compression parameters that determine how the
-image is encoded.  Most applications don't need or want to know about all
-these parameters.  You can set all the parameters to reasonable defaults by
-calling jpeg_set_defaults(); then, if there are particular values you want
-to change, you can do so after that.  The "Compression parameter selection"
-section tells about all the parameters.
-
-You must set in_color_space correctly before calling jpeg_set_defaults(),
-because the defaults depend on the source image colorspace.  However the
-other three source image parameters need not be valid until you call
-jpeg_start_compress().  There's no harm in calling jpeg_set_defaults() more
-than once, if that happens to be convenient.
-
-Typical code for a 24-bit RGB source image is
-
-	cinfo.image_width = Width; 	/* image width and height, in pixels */
-	cinfo.image_height = Height;
-	cinfo.input_components = 3;	/* # of color components per pixel */
-	cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
-
-	jpeg_set_defaults(&cinfo);
-	/* Make optional parameter settings here */
-
-
-4. jpeg_start_compress(...);
-
-After you have established the data destination and set all the necessary
-source image info and other parameters, call jpeg_start_compress() to begin
-a compression cycle.  This will initialize internal state, allocate working
-storage, and emit the first few bytes of the JPEG datastream header.
-
-Typical code:
-
-	jpeg_start_compress(&cinfo, TRUE);
-
-The "TRUE" parameter ensures that a complete JPEG interchange datastream
-will be written.  This is appropriate in most cases.  If you think you might
-want to use an abbreviated datastream, read the section on abbreviated
-datastreams, below.
-
-Once you have called jpeg_start_compress(), you may not alter any JPEG
-parameters or other fields of the JPEG object until you have completed
-the compression cycle.
-
-
-5. while (scan lines remain to be written)
-	jpeg_write_scanlines(...);
-
-Now write all the required image data by calling jpeg_write_scanlines()
-one or more times.  You can pass one or more scanlines in each call, up
-to the total image height.  In most applications it is convenient to pass
-just one or a few scanlines at a time.  The expected format for the passed
-data is discussed under "Data formats", above.
-
-Image data should be written in top-to-bottom scanline order.  The JPEG spec
-contains some weasel wording about how top and bottom are application-defined
-terms (a curious interpretation of the English language...) but if you want
-your files to be compatible with everyone else's, you WILL use top-to-bottom
-order.  If the source data must be read in bottom-to-top order, you can use
-the JPEG library's virtual array mechanism to invert the data efficiently.
-Examples of this can be found in the sample application cjpeg.
-
-The library maintains a count of the number of scanlines written so far
-in the next_scanline field of the JPEG object.  Usually you can just use
-this variable as the loop counter, so that the loop test looks like
-"while (cinfo.next_scanline < cinfo.image_height)".
-
-Code for this step depends heavily on the way that you store the source data.
-example.c shows the following code for the case of a full-size 2-D source
-array containing 3-byte RGB pixels:
-
-	JSAMPROW row_pointer[1];	/* pointer to a single row */
-	int row_stride;			/* physical row width in buffer */
-
-	row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
-
-	while (cinfo.next_scanline < cinfo.image_height) {
-	    row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
-	    jpeg_write_scanlines(&cinfo, row_pointer, 1);
-	}
-
-jpeg_write_scanlines() returns the number of scanlines actually written.
-This will normally be equal to the number passed in, so you can usually
-ignore the return value.  It is different in just two cases:
-  * If you try to write more scanlines than the declared image height,
-    the additional scanlines are ignored.
-  * If you use a suspending data destination manager, output buffer overrun
-    will cause the compressor to return before accepting all the passed lines.
-    This feature is discussed under "I/O suspension", below.  The normal
-    stdio destination manager will NOT cause this to happen.
-In any case, the return value is the same as the change in the value of
-next_scanline.
-
-
-6. jpeg_finish_compress(...);
-
-After all the image data has been written, call jpeg_finish_compress() to
-complete the compression cycle.  This step is ESSENTIAL to ensure that the
-last bufferload of data is written to the data destination.
-jpeg_finish_compress() also releases working memory associated with the JPEG
-object.
-
-Typical code:
-
-	jpeg_finish_compress(&cinfo);
-
-If using the stdio destination manager, don't forget to close the output
-stdio stream (if necessary) afterwards.
-
-If you have requested a multi-pass operating mode, such as Huffman code
-optimization, jpeg_finish_compress() will perform the additional passes using
-data buffered by the first pass.  In this case jpeg_finish_compress() may take
-quite a while to complete.  With the default compression parameters, this will
-not happen.
-
-It is an error to call jpeg_finish_compress() before writing the necessary
-total number of scanlines.  If you wish to abort compression, call
-jpeg_abort() as discussed below.
-
-After completing a compression cycle, you may dispose of the JPEG object
-as discussed next, or you may use it to compress another image.  In that case
-return to step 2, 3, or 4 as appropriate.  If you do not change the
-destination manager, the new datastream will be written to the same target.
-If you do not change any JPEG parameters, the new datastream will be written
-with the same parameters as before.  Note that you can change the input image
-dimensions freely between cycles, but if you change the input colorspace, you
-should call jpeg_set_defaults() to adjust for the new colorspace; and then
-you'll need to repeat all of step 3.
-
-
-7. Release the JPEG compression object.
-
-When you are done with a JPEG compression object, destroy it by calling
-jpeg_destroy_compress().  This will free all subsidiary memory (regardless of
-the previous state of the object).  Or you can call jpeg_destroy(), which
-works for either compression or decompression objects --- this may be more
-convenient if you are sharing code between compression and decompression
-cases.  (Actually, these routines are equivalent except for the declared type
-of the passed pointer.  To avoid gripes from ANSI C compilers, jpeg_destroy()
-should be passed a j_common_ptr.)
-
-If you allocated the jpeg_compress_struct structure from malloc(), freeing
-it is your responsibility --- jpeg_destroy() won't.  Ditto for the error
-handler structure.
-
-Typical code:
-
-	jpeg_destroy_compress(&cinfo);
-
-
-8. Aborting.
-
-If you decide to abort a compression cycle before finishing, you can clean up
-in either of two ways:
-
-* If you don't need the JPEG object any more, just call
-  jpeg_destroy_compress() or jpeg_destroy() to release memory.  This is
-  legitimate at any point after calling jpeg_create_compress() --- in fact,
-  it's safe even if jpeg_create_compress() fails.
-
-* If you want to re-use the JPEG object, call jpeg_abort_compress(), or call
-  jpeg_abort() which works on both compression and decompression objects.
-  This will return the object to an idle state, releasing any working memory.
-  jpeg_abort() is allowed at any time after successful object creation.
-
-Note that cleaning up the data destination, if required, is your
-responsibility; neither of these routines will call term_destination().
-(See "Compressed data handling", below, for more about that.)
-
-jpeg_destroy() and jpeg_abort() are the only safe calls to make on a JPEG
-object that has reported an error by calling error_exit (see "Error handling"
-for more info).  The internal state of such an object is likely to be out of
-whack.  Either of these two routines will return the object to a known state.
-
-
-Decompression details
----------------------
-
-Here we revisit the JPEG decompression outline given in the overview.
-
-1. Allocate and initialize a JPEG decompression object.
-
-This is just like initialization for compression, as discussed above,
-except that the object is a "struct jpeg_decompress_struct" and you
-call jpeg_create_decompress().  Error handling is exactly the same.
-
-Typical code:
-
-	struct jpeg_decompress_struct cinfo;
-	struct jpeg_error_mgr jerr;
-	...
-	cinfo.err = jpeg_std_error(&jerr);
-	jpeg_create_decompress(&cinfo);
-
-(Both here and in the IJG code, we usually use variable name "cinfo" for
-both compression and decompression objects.)
-
-
-2. Specify the source of the compressed data (eg, a file).
-
-As previously mentioned, the JPEG library reads compressed data from a "data
-source" module.  The library includes one data source module which knows how
-to read from a stdio stream.  You can use your own source module if you want
-to do something else, as discussed later.
-
-If you use the standard source module, you must open the source stdio stream
-beforehand.  Typical code for this step looks like:
-
-	FILE * infile;
-	...
-	if ((infile = fopen(filename, "rb")) == NULL) {
-	    fprintf(stderr, "can't open %s\n", filename);
-	    exit(1);
-	}
-	jpeg_stdio_src(&cinfo, infile);
-
-where the last line invokes the standard source module.
-
-WARNING: it is critical that the binary compressed data be read unchanged.
-On non-Unix systems the stdio library may perform newline translation or
-otherwise corrupt binary data.  To suppress this behavior, you may need to use
-a "b" option to fopen (as shown above), or use setmode() or another routine to
-put the stdio stream in binary mode.  See cjpeg.c and djpeg.c for code that
-has been found to work on many systems.
-
-You may not change the data source between calling jpeg_read_header() and
-jpeg_finish_decompress().  If you wish to read a series of JPEG images from
-a single source file, you should repeat the jpeg_read_header() to
-jpeg_finish_decompress() sequence without reinitializing either the JPEG
-object or the data source module; this prevents buffered input data from
-being discarded.
-
-
-3. Call jpeg_read_header() to obtain image info.
-
-Typical code for this step is just
-
-	jpeg_read_header(&cinfo, TRUE);
-
-This will read the source datastream header markers, up to the beginning
-of the compressed data proper.  On return, the image dimensions and other
-info have been stored in the JPEG object.  The application may wish to
-consult this information before selecting decompression parameters.
-
-More complex code is necessary if
-  * A suspending data source is used --- in that case jpeg_read_header()
-    may return before it has read all the header data.  See "I/O suspension",
-    below.  The normal stdio source manager will NOT cause this to happen.
-  * Abbreviated JPEG files are to be processed --- see the section on
-    abbreviated datastreams.  Standard applications that deal only in
-    interchange JPEG files need not be concerned with this case either.
-
-It is permissible to stop at this point if you just wanted to find out the
-image dimensions and other header info for a JPEG file.  In that case,
-call jpeg_destroy() when you are done with the JPEG object, or call
-jpeg_abort() to return it to an idle state before selecting a new data
-source and reading another header.
-
-
-4. Set parameters for decompression.
-
-jpeg_read_header() sets appropriate default decompression parameters based on
-the properties of the image (in particular, its colorspace).  However, you
-may well want to alter these defaults before beginning the decompression.
-For example, the default is to produce full color output from a color file.
-If you want colormapped output you must ask for it.  Other options allow the
-returned image to be scaled and allow various speed/quality tradeoffs to be
-selected.  "Decompression parameter selection", below, gives details.
-
-If the defaults are appropriate, nothing need be done at this step.
-
-Note that all default values are set by each call to jpeg_read_header().
-If you reuse a decompression object, you cannot expect your parameter
-settings to be preserved across cycles, as you can for compression.
-You must set desired parameter values each time.
-
-
-5. jpeg_start_decompress(...);
-
-Once the parameter values are satisfactory, call jpeg_start_decompress() to
-begin decompression.  This will initialize internal state, allocate working
-memory, and prepare for returning data.
-
-Typical code is just
-
-	jpeg_start_decompress(&cinfo);
-
-If you have requested a multi-pass operating mode, such as 2-pass color
-quantization, jpeg_start_decompress() will do everything needed before data
-output can begin.  In this case jpeg_start_decompress() may take quite a while
-to complete.  With a single-scan (non progressive) JPEG file and default
-decompression parameters, this will not happen; jpeg_start_decompress() will
-return quickly.
-
-After this call, the final output image dimensions, including any requested
-scaling, are available in the JPEG object; so is the selected colormap, if
-colormapped output has been requested.  Useful fields include
-
-	output_width		image width and height, as scaled
-	output_height
-	out_color_components	# of color components in out_color_space
-	output_components	# of color components returned per pixel
-	colormap		the selected colormap, if any
-	actual_number_of_colors		number of entries in colormap
-
-output_components is 1 (a colormap index) when quantizing colors; otherwise it
-equals out_color_components.  It is the number of JSAMPLE values that will be
-emitted per pixel in the output arrays.
-
-Typically you will need to allocate data buffers to hold the incoming image.
-You will need output_width * output_components JSAMPLEs per scanline in your
-output buffer, and a total of output_height scanlines will be returned.
-
-Note: if you are using the JPEG library's internal memory manager to allocate
-data buffers (as djpeg does), then the manager's protocol requires that you
-request large buffers *before* calling jpeg_start_decompress().  This is a
-little tricky since the output_XXX fields are not normally valid then.  You
-can make them valid by calling jpeg_calc_output_dimensions() after setting the
-relevant parameters (scaling, output color space, and quantization flag).
-
-
-6. while (scan lines remain to be read)
-	jpeg_read_scanlines(...);
-
-Now you can read the decompressed image data by calling jpeg_read_scanlines()
-one or more times.  At each call, you pass in the maximum number of scanlines
-to be read (ie, the height of your working buffer); jpeg_read_scanlines()
-will return up to that many lines.  The return value is the number of lines
-actually read.  The format of the returned data is discussed under "Data
-formats", above.  Don't forget that grayscale and color JPEGs will return
-different data formats!
-
-Image data is returned in top-to-bottom scanline order.  If you must write
-out the image in bottom-to-top order, you can use the JPEG library's virtual
-array mechanism to invert the data efficiently.  Examples of this can be
-found in the sample application djpeg.
-
-The library maintains a count of the number of scanlines returned so far
-in the output_scanline field of the JPEG object.  Usually you can just use
-this variable as the loop counter, so that the loop test looks like
-"while (cinfo.output_scanline < cinfo.output_height)".  (Note that the test
-should NOT be against image_height, unless you never use scaling.  The
-image_height field is the height of the original unscaled image.)
-The return value always equals the change in the value of output_scanline.
-
-If you don't use a suspending data source, it is safe to assume that
-jpeg_read_scanlines() reads at least one scanline per call, until the
-bottom of the image has been reached.
-
-If you use a buffer larger than one scanline, it is NOT safe to assume that
-jpeg_read_scanlines() fills it.  (The current implementation returns only a
-few scanlines per call, no matter how large a buffer you pass.)  So you must
-always provide a loop that calls jpeg_read_scanlines() repeatedly until the
-whole image has been read.
-
-
-7. jpeg_finish_decompress(...);
-
-After all the image data has been read, call jpeg_finish_decompress() to
-complete the decompression cycle.  This causes working memory associated
-with the JPEG object to be released.
-
-Typical code:
-
-	jpeg_finish_decompress(&cinfo);
-
-If using the stdio source manager, don't forget to close the source stdio
-stream if necessary.
-
-It is an error to call jpeg_finish_decompress() before reading the correct
-total number of scanlines.  If you wish to abort decompression, call
-jpeg_abort() as discussed below.
-
-After completing a decompression cycle, you may dispose of the JPEG object as
-discussed next, or you may use it to decompress another image.  In that case
-return to step 2 or 3 as appropriate.  If you do not change the source
-manager, the next image will be read from the same source.
-
-
-8. Release the JPEG decompression object.
-
-When you are done with a JPEG decompression object, destroy it by calling
-jpeg_destroy_decompress() or jpeg_destroy().  The previous discussion of
-destroying compression objects applies here too.
-
-Typical code:
-
-	jpeg_destroy_decompress(&cinfo);
-
-
-9. Aborting.
-
-You can abort a decompression cycle by calling jpeg_destroy_decompress() or
-jpeg_destroy() if you don't need the JPEG object any more, or
-jpeg_abort_decompress() or jpeg_abort() if you want to reuse the object.
-The previous discussion of aborting compression cycles applies here too.
-
-
-Mechanics of usage: include files, linking, etc
------------------------------------------------
-
-Applications using the JPEG library should include the header file jpeglib.h
-to obtain declarations of data types and routines.  Before including
-jpeglib.h, include system headers that define at least the typedefs FILE and
-size_t.  On ANSI-conforming systems, including <stdio.h> is sufficient; on
-older Unix systems, you may need <sys/types.h> to define size_t.
-
-If the application needs to refer to individual JPEG library error codes, also
-include jerror.h to define those symbols.
-
-jpeglib.h indirectly includes the files jconfig.h and jmorecfg.h.  If you are
-installing the JPEG header files in a system directory, you will want to
-install all four files: jpeglib.h, jerror.h, jconfig.h, jmorecfg.h.
-
-The most convenient way to include the JPEG code into your executable program
-is to prepare a library file ("libjpeg.a", or a corresponding name on non-Unix
-machines) and reference it at your link step.  If you use only half of the
-library (only compression or only decompression), only that much code will be
-included from the library, unless your linker is hopelessly brain-damaged.
-The supplied makefiles build libjpeg.a automatically (see install.doc).
-
-While you can build the JPEG library as a shared library if the whim strikes
-you, we don't really recommend it.  The trouble with shared libraries is that
-at some point you'll probably try to substitute a new version of the library
-without recompiling the calling applications.  That generally doesn't work
-because the parameter struct declarations usually change with each new
-version.  In other words, the library's API is *not* guaranteed binary
-compatible across versions; we only try to ensure source-code compatibility.
-(In hindsight, it might have been smarter to hide the parameter structs from
-applications and introduce a ton of access functions instead.  Too late now,
-however.)
-
-On some systems your application may need to set up a signal handler to ensure
-that temporary files are deleted if the program is interrupted.  This is most
-critical if you are on MS-DOS and use the jmemdos.c memory manager back end;
-it will try to grab extended memory for temp files, and that space will NOT be
-freed automatically.  See cjpeg.c or djpeg.c for an example signal handler.
-
-It may be worth pointing out that the core JPEG library does not actually
-require the stdio library: only the default source/destination managers and
-error handler need it.  You can use the library in a stdio-less environment
-if you replace those modules and use jmemnobs.c (or another memory manager of
-your own devising).  More info about the minimum system library requirements
-may be found in jinclude.h.
-
-
-ADVANCED FEATURES
-=================
-
-Compression parameter selection
--------------------------------
-
-This section describes all the optional parameters you can set for JPEG
-compression, as well as the "helper" routines provided to assist in this
-task.  Proper setting of some parameters requires detailed understanding
-of the JPEG standard; if you don't know what a parameter is for, it's best
-not to mess with it!  See REFERENCES in the README file for pointers to
-more info about JPEG.
-
-It's a good idea to call jpeg_set_defaults() first, even if you plan to set
-all the parameters; that way your code is more likely to work with future JPEG
-libraries that have additional parameters.  For the same reason, we recommend
-you use a helper routine where one is provided, in preference to twiddling
-cinfo fields directly.
-
-The helper routines are:
-
-jpeg_set_defaults (j_compress_ptr cinfo)
-	This routine sets all JPEG parameters to reasonable defaults, using
-	only the input image's color space (field in_color_space, which must
-	already be set in cinfo).  Many applications will only need to use
-	this routine and perhaps jpeg_set_quality().
-
-jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
-	Sets the JPEG file's colorspace (field jpeg_color_space) as specified,
-	and sets other color-space-dependent parameters appropriately.  See
-	"Special color spaces", below, before using this.  A large number of
-	parameters, including all per-component parameters, are set by this
-	routine; if you want to twiddle individual parameters you should call
-	jpeg_set_colorspace() before rather than after.
-
-jpeg_default_colorspace (j_compress_ptr cinfo)
-	Selects an appropriate JPEG colorspace based on cinfo->in_color_space,
-	and calls jpeg_set_colorspace().  This is actually a subroutine of
-	jpeg_set_defaults().  It's broken out in case you want to change
-	just the colorspace-dependent JPEG parameters.
-
-jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
-	Constructs JPEG quantization tables appropriate for the indicated
-	quality setting.  The quality value is expressed on the 0..100 scale
-	recommended by IJG (cjpeg's "-quality" switch uses this routine).
-	Note that the exact mapping from quality values to tables may change
-	in future IJG releases as more is learned about DCT quantization.
-	If the force_baseline parameter is TRUE, then the quantization table
-	entries are constrained to the range 1..255 for full JPEG baseline
-	compatibility.  In the current implementation, this only makes a
-	difference for quality settings below 25, and it effectively prevents
-	very small/low quality files from being generated.  The IJG decoder
-	is capable of reading the non-baseline files generated at low quality
-	settings when force_baseline is FALSE, but other decoders may not be.
-
-jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
-			 boolean force_baseline)
-	Same as jpeg_set_quality() except that the generated tables are the
-	sample tables given in the JPEC spec section K.1, multiplied by the
-	specified scale factor (which is expressed as a percentage; thus
-	scale_factor = 100 reproduces the spec's tables).  Note that larger
-	scale factors give lower quality.  This entry point is useful for
-	conforming to the Adobe PostScript DCT conventions, but we do not
-	recommend linear scaling as a user-visible quality scale otherwise.
-	force_baseline again constrains the computed table entries to 1..255.
-
-int jpeg_quality_scaling (int quality)
-	Converts a value on the IJG-recommended quality scale to a linear
-	scaling percentage.  Note that this routine may change or go away
-	in future releases --- IJG may choose to adopt a scaling method that
-	can't be expressed as a simple scalar multiplier, in which case the
-	premise of this routine collapses.  Caveat user.
-
-jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
-		      const unsigned int *basic_table,
-		      int scale_factor, boolean force_baseline)
-	Allows an arbitrary quantization table to be created.  which_tbl
-	indicates which table slot to fill.  basic_table points to an array
-	of 64 unsigned ints given in normal array order.  These values are
-	multiplied by scale_factor/100 and then clamped to the range 1..65535
-	(or to 1..255 if force_baseline is TRUE).
-	CAUTION: prior to library version 6a, jpeg_add_quant_table expected
-	the basic table to be given in JPEG zigzag order.  If you need to
-	write code that works with either older or newer versions of this
-	routine, you must check the library version number.  Something like
-	"#if JPEG_LIB_VERSION >= 61" is the right test.
-
-jpeg_simple_progression (j_compress_ptr cinfo)
-	Generates a default scan script for writing a progressive-JPEG file.
-	This is the recommended method of creating a progressive file,
-	unless you want to make a custom scan sequence.  You must ensure that
-	the JPEG color space is set correctly before calling this routine.
-
-
-Compression parameters (cinfo fields) include:
-
-J_DCT_METHOD dct_method
-	Selects the algorithm used for the DCT step.  Choices are:
-		JDCT_ISLOW: slow but accurate integer algorithm
-		JDCT_IFAST: faster, less accurate integer method
-		JDCT_FLOAT: floating-point method
-		JDCT_DEFAULT: default method (normally JDCT_ISLOW)
-		JDCT_FASTEST: fastest method (normally JDCT_IFAST)
-	The FLOAT method is very slightly more accurate than the ISLOW method,
-	but may give different results on different machines due to varying
-	roundoff behavior.  The integer methods should give the same results
-	on all machines.  On machines with sufficiently fast FP hardware, the
-	floating-point method may also be the fastest.  The IFAST method is
-	considerably less accurate than the other two; its use is not
-	recommended if high quality is a concern.  JDCT_DEFAULT and
-	JDCT_FASTEST are macros configurable by each installation.
-
-J_COLOR_SPACE jpeg_color_space
-int num_components
-	The JPEG color space and corresponding number of components; see
-	"Special color spaces", below, for more info.  We recommend using
-	jpeg_set_color_space() if you want to change these.
-
-boolean optimize_coding
-	TRUE causes the compressor to compute optimal Huffman coding tables
-	for the image.  This requires an extra pass over the data and
-	therefore costs a good deal of space and time.  The default is
-	FALSE, which tells the compressor to use the supplied or default
-	Huffman tables.  In most cases optimal tables save only a few percent
-	of file size compared to the default tables.  Note that when this is
-	TRUE, you need not supply Huffman tables at all, and any you do
-	supply will be overwritten.
-
-unsigned int restart_interval
-int restart_in_rows
-	To emit restart markers in the JPEG file, set one of these nonzero.
-	Set restart_interval to specify the exact interval in MCU blocks.
-	Set restart_in_rows to specify the interval in MCU rows.  (If
-	restart_in_rows is not 0, then restart_interval is set after the
-	image width in MCUs is computed.)  Defaults are zero (no restarts).
-	One restart marker per MCU row is often a good choice.
-	NOTE: the overhead of restart markers is higher in grayscale JPEG
-	files than in color files, and MUCH higher in progressive JPEGs.
-	If you use restarts, you may want to use larger intervals in those
-	cases.
-
-const jpeg_scan_info * scan_info
-int num_scans
-	By default, scan_info is NULL; this causes the compressor to write a
-	single-scan sequential JPEG file.  If not NULL, scan_info points to
-	an array of scan definition records of length num_scans.  The
-	compressor will then write a JPEG file having one scan for each scan
-	definition record.  This is used to generate noninterleaved or
-	progressive JPEG files.  The library checks that the scan array
-	defines a valid JPEG scan sequence.  (jpeg_simple_progression creates
-	a suitable scan definition array for progressive JPEG.)  This is
-	discussed further under "Progressive JPEG support".
-
-int smoothing_factor
-	If non-zero, the input image is smoothed; the value should be 1 for
-	minimal smoothing to 100 for maximum smoothing.  Consult jcsample.c
-	for details of the smoothing algorithm.  The default is zero.
-
-boolean write_JFIF_header
-	If TRUE, a JFIF APP0 marker is emitted.  jpeg_set_defaults() and
-	jpeg_set_colorspace() set this TRUE if a JFIF-legal JPEG color space
-	(ie, YCbCr or grayscale) is selected, otherwise FALSE.
-
-UINT8 JFIF_major_version
-UINT8 JFIF_minor_version
-	The version number to be written into the JFIF marker.
-	jpeg_set_defaults() initializes the version to 1.01 (major=minor=1).
-	You should set it to 1.02 (major=1, minor=2) if you plan to write
-	any JFIF 1.02 extension markers.
-
-UINT8 density_unit
-UINT16 X_density
-UINT16 Y_density
-	The resolution information to be written into the JFIF marker;
-	not used otherwise.  density_unit may be 0 for unknown,
-	1 for dots/inch, or 2 for dots/cm.  The default values are 0,1,1
-	indicating square pixels of unknown size.
-
-boolean write_Adobe_marker
-	If TRUE, an Adobe APP14 marker is emitted.  jpeg_set_defaults() and
-	jpeg_set_colorspace() set this TRUE if JPEG color space RGB, CMYK,
-	or YCCK is selected, otherwise FALSE.  It is generally a bad idea
-	to set both write_JFIF_header and write_Adobe_marker.  In fact,
-	you probably shouldn't change the default settings at all --- the
-	default behavior ensures that the JPEG file's color space can be
-	recognized by the decoder.
-
-JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]
-	Pointers to coefficient quantization tables, one per table slot,
-	or NULL if no table is defined for a slot.  Usually these should
-	be set via one of the above helper routines; jpeg_add_quant_table()
-	is general enough to define any quantization table.  The other
-	routines will set up table slot 0 for luminance quality and table
-	slot 1 for chrominance.
-
-JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]
-JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]
-	Pointers to Huffman coding tables, one per table slot, or NULL if
-	no table is defined for a slot.  Slots 0 and 1 are filled with the
-	JPEG sample tables by jpeg_set_defaults().  If you need to allocate
-	more table structures, jpeg_alloc_huff_table() may be used.
-	Note that optimal Huffman tables can be computed for an image
-	by setting optimize_coding, as discussed above; there's seldom
-	any need to mess with providing your own Huffman tables.
-
-There are some additional cinfo fields which are not documented here
-because you currently can't change them; for example, you can't set
-arith_code TRUE because arithmetic coding is unsupported.
-
-
-Per-component parameters are stored in the struct cinfo.comp_info[i] for
-component number i.  Note that components here refer to components of the
-JPEG color space, *not* the source image color space.  A suitably large
-comp_info[] array is allocated by jpeg_set_defaults(); if you choose not
-to use that routine, it's up to you to allocate the array.
-
-int component_id
-	The one-byte identifier code to be recorded in the JPEG file for
-	this component.  For the standard color spaces, we recommend you
-	leave the default values alone.
-
-int h_samp_factor
-int v_samp_factor
-	Horizontal and vertical sampling factors for the component; must
-	be 1..4 according to the JPEG standard.  Note that larger sampling
-	factors indicate a higher-resolution component; many people find
-	this behavior quite unintuitive.  The default values are 2,2 for
-	luminance components and 1,1 for chrominance components, except
-	for grayscale where 1,1 is used.
-
-int quant_tbl_no
-	Quantization table number for component.  The default value is
-	0 for luminance components and 1 for chrominance components.
-
-int dc_tbl_no
-int ac_tbl_no
-	DC and AC entropy coding table numbers.  The default values are
-	0 for luminance components and 1 for chrominance components.
-
-int component_index
-	Must equal the component's index in comp_info[].  (Beginning in
-	release v6, the compressor library will fill this in automatically;
-	you don't have to.)
-
-
-Decompression parameter selection
----------------------------------
-
-Decompression parameter selection is somewhat simpler than compression
-parameter selection, since all of the JPEG internal parameters are
-recorded in the source file and need not be supplied by the application.
-(Unless you are working with abbreviated files, in which case see
-"Abbreviated datastreams", below.)  Decompression parameters control
-the postprocessing done on the image to deliver it in a format suitable
-for the application's use.  Many of the parameters control speed/quality
-tradeoffs, in which faster decompression may be obtained at the price of
-a poorer-quality image.  The defaults select the highest quality (slowest)
-processing.
-
-The following fields in the JPEG object are set by jpeg_read_header() and
-may be useful to the application in choosing decompression parameters:
-
-JDIMENSION image_width			Width and height of image
-JDIMENSION image_height
-int num_components			Number of color components
-J_COLOR_SPACE jpeg_color_space		Colorspace of image
-boolean saw_JFIF_marker			TRUE if a JFIF APP0 marker was seen
-  UINT8 JFIF_major_version		Version information from JFIF marker
-  UINT8 JFIF_minor_version
-  UINT8 density_unit			Resolution data from JFIF marker
-  UINT16 X_density
-  UINT16 Y_density
-boolean saw_Adobe_marker		TRUE if an Adobe APP14 marker was seen
-  UINT8 Adobe_transform			Color transform code from Adobe marker
-
-The JPEG color space, unfortunately, is something of a guess since the JPEG
-standard proper does not provide a way to record it.  In practice most files
-adhere to the JFIF or Adobe conventions, and the decoder will recognize these
-correctly.  See "Special color spaces", below, for more info.
-
-
-The decompression parameters that determine the basic properties of the
-returned image are:
-
-J_COLOR_SPACE out_color_space
-	Output color space.  jpeg_read_header() sets an appropriate default
-	based on jpeg_color_space; typically it will be RGB or grayscale.
-	The application can change this field to request output in a different
-	colorspace.  For example, set it to JCS_GRAYSCALE to get grayscale
-	output from a color file.  (This is useful for previewing: grayscale
-	output is faster than full color since the color components need not
-	be processed.)  Note that not all possible color space transforms are
-	currently implemented; you may need to extend jdcolor.c if you want an
-	unusual conversion.
-
-unsigned int scale_num, scale_denom
-	Scale the image by the fraction scale_num/scale_denom.  Default is
-	1/1, or no scaling.  Currently, the only supported scaling ratios
-	are 1/1, 1/2, 1/4, and 1/8.  (The library design allows for arbitrary
-	scaling ratios but this is not likely to be implemented any time soon.)
-	Smaller scaling ratios permit significantly faster decoding since
-	fewer pixels need be processed and a simpler IDCT method can be used.
-
-boolean quantize_colors
-	If set TRUE, colormapped output will be delivered.  Default is FALSE,
-	meaning that full-color output will be delivered.
-
-The next three parameters are relevant only if quantize_colors is TRUE.
-
-int desired_number_of_colors
-	Maximum number of colors to use in generating a library-supplied color
-	map (the actual number of colors is returned in a different field).
-	Default 256.  Ignored when the application supplies its own color map.
-
-boolean two_pass_quantize
-	If TRUE, an extra pass over the image is made to select a custom color
-	map for the image.  This usually looks a lot better than the one-size-
-	fits-all colormap that is used otherwise.  Default is TRUE.  Ignored
-	when the application supplies its own color map.
-
-J_DITHER_MODE dither_mode
-	Selects color dithering method.  Supported values are:
-		JDITHER_NONE	no dithering: fast, very low quality
-		JDITHER_ORDERED	ordered dither: moderate speed and quality
-		JDITHER_FS	Floyd-Steinberg dither: slow, high quality
-	Default is JDITHER_FS.  (At present, ordered dither is implemented
-	only in the single-pass, standard-colormap case.  If you ask for
-	ordered dither when two_pass_quantize is TRUE or when you supply
-	an external color map, you'll get F-S dithering.)
-
-When quantize_colors is TRUE, the target color map is described by the next
-two fields.  colormap is set to NULL by jpeg_read_header().  The application
-can supply a color map by setting colormap non-NULL and setting
-actual_number_of_colors to the map size.  Otherwise, jpeg_start_decompress()
-selects a suitable color map and sets these two fields itself.
-[Implementation restriction: at present, an externally supplied colormap is
-only accepted for 3-component output color spaces.]
-
-JSAMPARRAY colormap
-	The color map, represented as a 2-D pixel array of out_color_components
-	rows and actual_number_of_colors columns.  Ignored if not quantizing.
-	CAUTION: if the JPEG library creates its own colormap, the storage
-	pointed to by this field is released by jpeg_finish_decompress().
-	Copy the colormap somewhere else first, if you want to save it.
-
-int actual_number_of_colors
-	The number of colors in the color map.
-
-Additional decompression parameters that the application may set include:
-
-J_DCT_METHOD dct_method
-	Selects the algorithm used for the DCT step.  Choices are the same
-	as described above for compression.
-
-boolean do_fancy_upsampling
-	If TRUE, do careful upsampling of chroma components.  If FALSE,
-	a faster but sloppier method is used.  Default is TRUE.  The visual
-	impact of the sloppier method is often very small.
-
-boolean do_block_smoothing
-	If TRUE, interblock smoothing is applied in early stages of decoding
-	progressive JPEG files; if FALSE, not.  Default is TRUE.  Early
-	progression stages look "fuzzy" with smoothing, "blocky" without.
-	In any case, block smoothing ceases to be applied after the first few
-	AC coefficients are known to full accuracy, so it is relevant only
-	when using buffered-image mode for progressive images.
-
-boolean enable_1pass_quant
-boolean enable_external_quant
-boolean enable_2pass_quant
-	These are significant only in buffered-image mode, which is
-	described in its own section below.
-
-
-The output image dimensions are given by the following fields.  These are
-computed from the source image dimensions and the decompression parameters
-by jpeg_start_decompress().  You can also call jpeg_calc_output_dimensions()
-to obtain the values that will result from the current parameter settings.
-This can be useful if you are trying to pick a scaling ratio that will get
-close to a desired target size.  It's also important if you are using the
-JPEG library's memory manager to allocate output buffer space, because you
-are supposed to request such buffers *before* jpeg_start_decompress().
-
-JDIMENSION output_width		Actual dimensions of output image.
-JDIMENSION output_height
-int out_color_components	Number of color components in out_color_space.
-int output_components		Number of color components returned.
-int rec_outbuf_height		Recommended height of scanline buffer.
-
-When quantizing colors, output_components is 1, indicating a single color map
-index per pixel.  Otherwise it equals out_color_components.  The output arrays
-are required to be output_width * output_components JSAMPLEs wide.
-
-rec_outbuf_height is the recommended minimum height (in scanlines) of the
-buffer passed to jpeg_read_scanlines().  If the buffer is smaller, the
-library will still work, but time will be wasted due to unnecessary data
-copying.  In high-quality modes, rec_outbuf_height is always 1, but some
-faster, lower-quality modes set it to larger values (typically 2 to 4).
-If you are going to ask for a high-speed processing mode, you may as well
-go to the trouble of honoring rec_outbuf_height so as to avoid data copying.
-(An output buffer larger than rec_outbuf_height lines is OK, but won't
-provide any material speed improvement over that height.)
-
-
-Special color spaces
---------------------
-
-The JPEG standard itself is "color blind" and doesn't specify any particular
-color space.  It is customary to convert color data to a luminance/chrominance
-color space before compressing, since this permits greater compression.  The
-existing de-facto JPEG file format standards specify YCbCr or grayscale data
-(JFIF), or grayscale, RGB, YCbCr, CMYK, or YCCK (Adobe).  For special
-applications such as multispectral images, other color spaces can be used,
-but it must be understood that such files will be unportable.
-
-The JPEG library can handle the most common colorspace conversions (namely
-RGB <=> YCbCr and CMYK <=> YCCK).  It can also deal with data of an unknown
-color space, passing it through without conversion.  If you deal extensively
-with an unusual color space, you can easily extend the library to understand
-additional color spaces and perform appropriate conversions.
-
-For compression, the source data's color space is specified by field
-in_color_space.  This is transformed to the JPEG file's color space given
-by jpeg_color_space.  jpeg_set_defaults() chooses a reasonable JPEG color
-space depending on in_color_space, but you can override this by calling
-jpeg_set_colorspace().  Of course you must select a supported transformation.
-jccolor.c currently supports the following transformations:
-	RGB => YCbCr
-	RGB => GRAYSCALE
-	YCbCr => GRAYSCALE
-	CMYK => YCCK
-plus the null transforms: GRAYSCALE => GRAYSCALE, RGB => RGB,
-YCbCr => YCbCr, CMYK => CMYK, YCCK => YCCK, and UNKNOWN => UNKNOWN.
-
-The de-facto file format standards (JFIF and Adobe) specify APPn markers that
-indicate the color space of the JPEG file.  It is important to ensure that
-these are written correctly, or omitted if the JPEG file's color space is not
-one of the ones supported by the de-facto standards.  jpeg_set_colorspace()
-will set the compression parameters to include or omit the APPn markers
-properly, so long as it is told the truth about the JPEG color space.
-For example, if you are writing some random 3-component color space without
-conversion, don't try to fake out the library by setting in_color_space and
-jpeg_color_space to JCS_YCbCr; use JCS_UNKNOWN.  You may want to write an
-APPn marker of your own devising to identify the colorspace --- see "Special
-markers", below.
-
-When told that the color space is UNKNOWN, the library will default to using
-luminance-quality compression parameters for all color components.  You may
-well want to change these parameters.  See the source code for
-jpeg_set_colorspace(), in jcparam.c, for details.
-
-For decompression, the JPEG file's color space is given in jpeg_color_space,
-and this is transformed to the output color space out_color_space.
-jpeg_read_header's setting of jpeg_color_space can be relied on if the file
-conforms to JFIF or Adobe conventions, but otherwise it is no better than a
-guess.  If you know the JPEG file's color space for certain, you can override
-jpeg_read_header's guess by setting jpeg_color_space.  jpeg_read_header also
-selects a default output color space based on (its guess of) jpeg_color_space;
-set out_color_space to override this.  Again, you must select a supported
-transformation.  jdcolor.c currently supports
-	YCbCr => GRAYSCALE
-	YCbCr => RGB
-	GRAYSCALE => RGB
-	YCCK => CMYK
-as well as the null transforms.  (Since GRAYSCALE=>RGB is provided, an
-application can force grayscale JPEGs to look like color JPEGs if it only
-wants to handle one case.)
-
-The two-pass color quantizer, jquant2.c, is specialized to handle RGB data
-(it weights distances appropriately for RGB colors).  You'll need to modify
-the code if you want to use it for non-RGB output color spaces.  Note that
-jquant2.c is used to map to an application-supplied colormap as well as for
-the normal two-pass colormap selection process.
-
-CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG
-files: 0 represents 100% ink coverage, rather than 0% ink as you'd expect.
-This is arguably a bug in Photoshop, but if you need to work with Photoshop
-CMYK files, you will have to deal with it in your application.  We cannot
-"fix" this in the library by inverting the data during the CMYK<=>YCCK
-transform, because that would break other applications, notably Ghostscript.
-Photoshop versions prior to 3.0 write EPS files containing JPEG-encoded CMYK
-data in the same inverted-YCCK representation used in bare JPEG files, but
-the surrounding PostScript code performs an inversion using the PS image
-operator.  I am told that Photoshop 3.0 will write uninverted YCCK in
-EPS/JPEG files, and will omit the PS-level inversion.  (But the data
-polarity used in bare JPEG files will not change in 3.0.)  In either case,
-the JPEG library must not invert the data itself, or else Ghostscript would
-read these EPS files incorrectly.
-
-
-Error handling
---------------
-
-When the default error handler is used, any error detected inside the JPEG
-routines will cause a message to be printed on stderr, followed by exit().
-You can supply your own error handling routines to override this behavior
-and to control the treatment of nonfatal warnings and trace/debug messages.
-The file example.c illustrates the most common case, which is to have the
-application regain control after an error rather than exiting.
-
-The JPEG library never writes any message directly; it always goes through
-the error handling routines.  Three classes of messages are recognized:
-  * Fatal errors: the library cannot continue.
-  * Warnings: the library can continue, but the data is corrupt, and a
-    damaged output image is likely to result.
-  * Trace/informational messages.  These come with a trace level indicating
-    the importance of the message; you can control the verbosity of the
-    program by adjusting the maximum trace level that will be displayed.
-
-You may, if you wish, simply replace the entire JPEG error handling module
-(jerror.c) with your own code.  However, you can avoid code duplication by
-only replacing some of the routines depending on the behavior you need.
-This is accomplished by calling jpeg_std_error() as usual, but then overriding
-some of the method pointers in the jpeg_error_mgr struct, as illustrated by
-example.c.
-
-All of the error handling routines will receive a pointer to the JPEG object
-(a j_common_ptr which points to either a jpeg_compress_struct or a
-jpeg_decompress_struct; if you need to tell which, test the is_decompressor
-field).  This struct includes a pointer to the error manager struct in its
-"err" field.  Frequently, custom error handler routines will need to access
-additional data which is not known to the JPEG library or the standard error
-handler.  The most convenient way to do this is to embed either the JPEG
-object or the jpeg_error_mgr struct in a larger structure that contains
-additional fields; then casting the passed pointer provides access to the
-additional fields.  Again, see example.c for one way to do it.  (Beginning
-with IJG version 6b, there is also a void pointer "client_data" in each
-JPEG object, which the application can also use to find related data.
-The library does not touch client_data at all.)
-
-The individual methods that you might wish to override are:
-
-error_exit (j_common_ptr cinfo)
-	Receives control for a fatal error.  Information sufficient to
-	generate the error message has been stored in cinfo->err; call
-	output_message to display it.  Control must NOT return to the caller;
-	generally this routine will exit() or longjmp() somewhere.
-	Typically you would override this routine to get rid of the exit()
-	default behavior.  Note that if you continue processing, you should
-	clean up the JPEG object with jpeg_abort() or jpeg_destroy().
-
-output_message (j_common_ptr cinfo)
-	Actual output of any JPEG message.  Override this to send messages
-	somewhere other than stderr.  Note that this method does not know
-	how to generate a message, only where to send it.
-
-format_message (j_common_ptr cinfo, char * buffer)
-	Constructs a readable error message string based on the error info
-	stored in cinfo->err.  This method is called by output_message.  Few
-	applications should need to override this method.  One possible
-	reason for doing so is to implement dynamic switching of error message
-	language.
-
-emit_message (j_common_ptr cinfo, int msg_level)
-	Decide whether or not to emit a warning or trace message; if so,
-	calls output_message.  The main reason for overriding this method
-	would be to abort on warnings.  msg_level is -1 for warnings,
-	0 and up for trace messages.
-
-Only error_exit() and emit_message() are called from the rest of the JPEG
-library; the other two are internal to the error handler.
-
-The actual message texts are stored in an array of strings which is pointed to
-by the field err->jpeg_message_table.  The messages are numbered from 0 to
-err->last_jpeg_message, and it is these code numbers that are used in the
-JPEG library code.  You could replace the message texts (for instance, with
-messages in French or German) by changing the message table pointer.  See
-jerror.h for the default texts.  CAUTION: this table will almost certainly
-change or grow from one library version to the next.
-
-It may be useful for an application to add its own message texts that are
-handled by the same mechanism.  The error handler supports a second "add-on"
-message table for this purpose.  To define an addon table, set the pointer
-err->addon_message_table and the message numbers err->first_addon_message and
-err->last_addon_message.  If you number the addon messages beginning at 1000
-or so, you won't have to worry about conflicts with the library's built-in
-messages.  See the sample applications cjpeg/djpeg for an example of using
-addon messages (the addon messages are defined in cderror.h).
-
-Actual invocation of the error handler is done via macros defined in jerror.h:
-	ERREXITn(...)	for fatal errors
-	WARNMSn(...)	for corrupt-data warnings
-	TRACEMSn(...)	for trace and informational messages.
-These macros store the message code and any additional parameters into the
-error handler struct, then invoke the error_exit() or emit_message() method.
-The variants of each macro are for varying numbers of additional parameters.
-The additional parameters are inserted into the generated message using
-standard printf() format codes.
-
-See jerror.h and jerror.c for further details.
-
-
-Compressed data handling (source and destination managers)
-----------------------------------------------------------
-
-The JPEG compression library sends its compressed data to a "destination
-manager" module.  The default destination manager just writes the data to a
-stdio stream, but you can provide your own manager to do something else.
-Similarly, the decompression library calls a "source manager" to obtain the
-compressed data; you can provide your own source manager if you want the data
-to come from somewhere other than a stdio stream.
-
-In both cases, compressed data is processed a bufferload at a time: the
-destination or source manager provides a work buffer, and the library invokes
-the manager only when the buffer is filled or emptied.  (You could define a
-one-character buffer to force the manager to be invoked for each byte, but
-that would be rather inefficient.)  The buffer's size and location are
-controlled by the manager, not by the library.  For example, if you desired to
-decompress a JPEG datastream that was all in memory, you could just make the
-buffer pointer and length point to the original data in memory.  Then the
-buffer-reload procedure would be invoked only if the decompressor ran off the
-end of the datastream, which would indicate an erroneous datastream.
-
-The work buffer is defined as an array of datatype JOCTET, which is generally
-"char" or "unsigned char".  On a machine where char is not exactly 8 bits
-wide, you must define JOCTET as a wider data type and then modify the data
-source and destination modules to transcribe the work arrays into 8-bit units
-on external storage.
-
-A data destination manager struct contains a pointer and count defining the
-next byte to write in the work buffer and the remaining free space:
-
-	JOCTET * next_output_byte;  /* => next byte to write in buffer */
-	size_t free_in_buffer;      /* # of byte spaces remaining in buffer */
-
-The library increments the pointer and decrements the count until the buffer
-is filled.  The manager's empty_output_buffer method must reset the pointer
-and count.  The manager is expected to remember the buffer's starting address
-and total size in private fields not visible to the library.
-
-A data destination manager provides three methods:
-
-init_destination (j_compress_ptr cinfo)
-	Initialize destination.  This is called by jpeg_start_compress()
-	before any data is actually written.  It must initialize
-	next_output_byte and free_in_buffer.  free_in_buffer must be
-	initialized to a positive value.
-
-empty_output_buffer (j_compress_ptr cinfo)
-	This is called whenever the buffer has filled (free_in_buffer
-	reaches zero).  In typical applications, it should write out the
-	*entire* buffer (use the saved start address and buffer length;
-	ignore the current state of next_output_byte and free_in_buffer).
-	Then reset the pointer & count to the start of the buffer, and
-	return TRUE indicating that the buffer has been dumped.
-	free_in_buffer must be set to a positive value when TRUE is
-	returned.  A FALSE return should only be used when I/O suspension is
-	desired (this operating mode is discussed in the next section).
-
-term_destination (j_compress_ptr cinfo)
-	Terminate destination --- called by jpeg_finish_compress() after all
-	data has been written.  In most applications, this must flush any
-	data remaining in the buffer.  Use either next_output_byte or
-	free_in_buffer to determine how much data is in the buffer.
-
-term_destination() is NOT called by jpeg_abort() or jpeg_destroy().  If you
-want the destination manager to be cleaned up during an abort, you must do it
-yourself.
-
-You will also need code to create a jpeg_destination_mgr struct, fill in its
-method pointers, and insert a pointer to the struct into the "dest" field of
-the JPEG compression object.  This can be done in-line in your setup code if
-you like, but it's probably cleaner to provide a separate routine similar to
-the jpeg_stdio_dest() routine of the supplied destination manager.
-
-Decompression source managers follow a parallel design, but with some
-additional frammishes.  The source manager struct contains a pointer and count
-defining the next byte to read from the work buffer and the number of bytes
-remaining:
-
-	const JOCTET * next_input_byte; /* => next byte to read from buffer */
-	size_t bytes_in_buffer;         /* # of bytes remaining in buffer */
-
-The library increments the pointer and decrements the count until the buffer
-is emptied.  The manager's fill_input_buffer method must reset the pointer and
-count.  In most applications, the manager must remember the buffer's starting
-address and total size in private fields not visible to the library.
-
-A data source manager provides five methods:
-
-init_source (j_decompress_ptr cinfo)
-	Initialize source.  This is called by jpeg_read_header() before any
-	data is actually read.  Unlike init_destination(), it may leave
-	bytes_in_buffer set to 0 (in which case a fill_input_buffer() call
-	will occur immediately).
-
-fill_input_buffer (j_decompress_ptr cinfo)
-	This is called whenever bytes_in_buffer has reached zero and more
-	data is wanted.  In typical applications, it should read fresh data
-	into the buffer (ignoring the current state of next_input_byte and
-	bytes_in_buffer), reset the pointer & count to the start of the
-	buffer, and return TRUE indicating that the buffer has been reloaded.
-	It is not necessary to fill the buffer entirely, only to obtain at
-	least one more byte.  bytes_in_buffer MUST be set to a positive value
-	if TRUE is returned.  A FALSE return should only be used when I/O
-	suspension is desired (this mode is discussed in the next section).
-
-skip_input_data (j_decompress_ptr cinfo, long num_bytes)
-	Skip num_bytes worth of data.  The buffer pointer and count should
-	be advanced over num_bytes input bytes, refilling the buffer as
-	needed.  This is used to skip over a potentially large amount of
-	uninteresting data (such as an APPn marker).  In some applications
-	it may be possible to optimize away the reading of the skipped data,
-	but it's not clear that being smart is worth much trouble; large
-	skips are uncommon.  bytes_in_buffer may be zero on return.
-	A zero or negative skip count should be treated as a no-op.
-
-resync_to_restart (j_decompress_ptr cinfo, int desired)
-	This routine is called only when the decompressor has failed to find
-	a restart (RSTn) marker where one is expected.  Its mission is to
-	find a suitable point for resuming decompression.  For most
-	applications, we recommend that you just use the default resync
-	procedure, jpeg_resync_to_restart().  However, if you are able to back
-	up in the input data stream, or if you have a-priori knowledge about
-	the likely location of restart markers, you may be able to do better.
-	Read the read_restart_marker() and jpeg_resync_to_restart() routines
-	in jdmarker.c if you think you'd like to implement your own resync
-	procedure.
-
-term_source (j_decompress_ptr cinfo)
-	Terminate source --- called by jpeg_finish_decompress() after all
-	data has been read.  Often a no-op.
-
-For both fill_input_buffer() and skip_input_data(), there is no such thing
-as an EOF return.  If the end of the file has been reached, the routine has
-a choice of exiting via ERREXIT() or inserting fake data into the buffer.
-In most cases, generating a warning message and inserting a fake EOI marker
-is the best course of action --- this will allow the decompressor to output
-however much of the image is there.  In pathological cases, the decompressor
-may swallow the EOI and again demand data ... just keep feeding it fake EOIs.
-jdatasrc.c illustrates the recommended error recovery behavior.
-
-term_source() is NOT called by jpeg_abort() or jpeg_destroy().  If you want
-the source manager to be cleaned up during an abort, you must do it yourself.
-
-You will also need code to create a jpeg_source_mgr struct, fill in its method
-pointers, and insert a pointer to the struct into the "src" field of the JPEG
-decompression object.  This can be done in-line in your setup code if you
-like, but it's probably cleaner to provide a separate routine similar to the
-jpeg_stdio_src() routine of the supplied source manager.
-
-For more information, consult the stdio source and destination managers
-in jdatasrc.c and jdatadst.c.
-
-
-I/O suspension
---------------
-
-Some applications need to use the JPEG library as an incremental memory-to-
-memory filter: when the compressed data buffer is filled or emptied, they want
-control to return to the outer loop, rather than expecting that the buffer can
-be emptied or reloaded within the data source/destination manager subroutine.
-The library supports this need by providing an "I/O suspension" mode, which we
-describe in this section.
-
-The I/O suspension mode is not a panacea: nothing is guaranteed about the
-maximum amount of time spent in any one call to the library, so it will not
-eliminate response-time problems in single-threaded applications.  If you
-need guaranteed response time, we suggest you "bite the bullet" and implement
-a real multi-tasking capability.
-
-To use I/O suspension, cooperation is needed between the calling application
-and the data source or destination manager; you will always need a custom
-source/destination manager.  (Please read the previous section if you haven't
-already.)  The basic idea is that the empty_output_buffer() or
-fill_input_buffer() routine is a no-op, merely returning FALSE to indicate
-that it has done nothing.  Upon seeing this, the JPEG library suspends
-operation and returns to its caller.  The surrounding application is
-responsible for emptying or refilling the work buffer before calling the
-JPEG library again.
-
-Compression suspension:
-
-For compression suspension, use an empty_output_buffer() routine that returns
-FALSE; typically it will not do anything else.  This will cause the
-compressor to return to the caller of jpeg_write_scanlines(), with the return
-value indicating that not all the supplied scanlines have been accepted.
-The application must make more room in the output buffer, adjust the output
-buffer pointer/count appropriately, and then call jpeg_write_scanlines()
-again, pointing to the first unconsumed scanline.
-
-When forced to suspend, the compressor will backtrack to a convenient stopping
-point (usually the start of the current MCU); it will regenerate some output
-data when restarted.  Therefore, although empty_output_buffer() is only
-called when the buffer is filled, you should NOT write out the entire buffer
-after a suspension.  Write only the data up to the current position of
-next_output_byte/free_in_buffer.  The data beyond that point will be
-regenerated after resumption.
-
-Because of the backtracking behavior, a good-size output buffer is essential
-for efficiency; you don't want the compressor to suspend often.  (In fact, an
-overly small buffer could lead to infinite looping, if a single MCU required
-more data than would fit in the buffer.)  We recommend a buffer of at least
-several Kbytes.  You may want to insert explicit code to ensure that you don't
-call jpeg_write_scanlines() unless there is a reasonable amount of space in
-the output buffer; in other words, flush the buffer before trying to compress
-more data.
-
-The compressor does not allow suspension while it is trying to write JPEG
-markers at the beginning and end of the file.  This means that:
-  * At the beginning of a compression operation, there must be enough free
-    space in the output buffer to hold the header markers (typically 600 or
-    so bytes).  The recommended buffer size is bigger than this anyway, so
-    this is not a problem as long as you start with an empty buffer.  However,
-    this restriction might catch you if you insert large special markers, such
-    as a JFIF thumbnail image, without flushing the buffer afterwards.
-  * When you call jpeg_finish_compress(), there must be enough space in the
-    output buffer to emit any buffered data and the final EOI marker.  In the
-    current implementation, half a dozen bytes should suffice for this, but
-    for safety's sake we recommend ensuring that at least 100 bytes are free
-    before calling jpeg_finish_compress().
-
-A more significant restriction is that jpeg_finish_compress() cannot suspend.
-This means you cannot use suspension with multi-pass operating modes, namely
-Huffman code optimization and multiple-scan output.  Those modes write the
-whole file during jpeg_finish_compress(), which will certainly result in
-buffer overrun.  (Note that this restriction applies only to compression,
-not decompression.  The decompressor supports input suspension in all of its
-operating modes.)
-
-Decompression suspension:
-
-For decompression suspension, use a fill_input_buffer() routine that simply
-returns FALSE (except perhaps during error recovery, as discussed below).
-This will cause the decompressor to return to its caller with an indication
-that suspension has occurred.  This can happen at four places:
-  * jpeg_read_header(): will return JPEG_SUSPENDED.
-  * jpeg_start_decompress(): will return FALSE, rather than its usual TRUE.
-  * jpeg_read_scanlines(): will return the number of scanlines already
-	completed (possibly 0).
-  * jpeg_finish_decompress(): will return FALSE, rather than its usual TRUE.
-The surrounding application must recognize these cases, load more data into
-the input buffer, and repeat the call.  In the case of jpeg_read_scanlines(),
-increment the passed pointers past any scanlines successfully read.
-
-Just as with compression, the decompressor will typically backtrack to a
-convenient restart point before suspending.  When fill_input_buffer() is
-called, next_input_byte/bytes_in_buffer point to the current restart point,
-which is where the decompressor will backtrack to if FALSE is returned.
-The data beyond that position must NOT be discarded if you suspend; it needs
-to be re-read upon resumption.  In most implementations, you'll need to shift
-this data down to the start of your work buffer and then load more data after
-it.  Again, this behavior means that a several-Kbyte work buffer is essential
-for decent performance; furthermore, you should load a reasonable amount of
-new data before resuming decompression.  (If you loaded, say, only one new
-byte each time around, you could waste a LOT of cycles.)
-
-The skip_input_data() source manager routine requires special care in a
-suspension scenario.  This routine is NOT granted the ability to suspend the
-decompressor; it can decrement bytes_in_buffer to zero, but no more.  If the
-requested skip distance exceeds the amount of data currently in the input
-buffer, then skip_input_data() must set bytes_in_buffer to zero and record the
-additional skip distance somewhere else.  The decompressor will immediately
-call fill_input_buffer(), which should return FALSE, which will cause a
-suspension return.  The surrounding application must then arrange to discard
-the recorded number of bytes before it resumes loading the input buffer.
-(Yes, this design is rather baroque, but it avoids complexity in the far more
-common case where a non-suspending source manager is used.)
-
-If the input data has been exhausted, we recommend that you emit a warning
-and insert dummy EOI markers just as a non-suspending data source manager
-would do.  This can be handled either in the surrounding application logic or
-within fill_input_buffer(); the latter is probably more efficient.  If
-fill_input_buffer() knows that no more data is available, it can set the
-pointer/count to point to a dummy EOI marker and then return TRUE just as
-though it had read more data in a non-suspending situation.
-
-The decompressor does not attempt to suspend within standard JPEG markers;
-instead it will backtrack to the start of the marker and reprocess the whole
-marker next time.  Hence the input buffer must be large enough to hold the
-longest standard marker in the file.  Standard JPEG markers should normally
-not exceed a few hundred bytes each (DHT tables are typically the longest).
-We recommend at least a 2K buffer for performance reasons, which is much
-larger than any correct marker is likely to be.  For robustness against
-damaged marker length counts, you may wish to insert a test in your
-application for the case that the input buffer is completely full and yet
-the decoder has suspended without consuming any data --- otherwise, if this
-situation did occur, it would lead to an endless loop.  (The library can't
-provide this test since it has no idea whether "the buffer is full", or
-even whether there is a fixed-size input buffer.)
-
-The input buffer would need to be 64K to allow for arbitrary COM or APPn
-markers, but these are handled specially: they are either saved into allocated
-memory, or skipped over by calling skip_input_data().  In the former case,
-suspension is handled correctly, and in the latter case, the problem of
-buffer overrun is placed on skip_input_data's shoulders, as explained above.
-Note that if you provide your own marker handling routine for large markers,
-you should consider how to deal with buffer overflow.
-
-Multiple-buffer management:
-
-In some applications it is desirable to store the compressed data in a linked
-list of buffer areas, so as to avoid data copying.  This can be handled by
-having empty_output_buffer() or fill_input_buffer() set the pointer and count
-to reference the next available buffer; FALSE is returned only if no more
-buffers are available.  Although seemingly straightforward, there is a
-pitfall in this approach: the backtrack that occurs when FALSE is returned
-could back up into an earlier buffer.  For example, when fill_input_buffer()
-is called, the current pointer & count indicate the backtrack restart point.
-Since fill_input_buffer() will set the pointer and count to refer to a new
-buffer, the restart position must be saved somewhere else.  Suppose a second
-call to fill_input_buffer() occurs in the same library call, and no
-additional input data is available, so fill_input_buffer must return FALSE.
-If the JPEG library has not moved the pointer/count forward in the current
-buffer, then *the correct restart point is the saved position in the prior
-buffer*.  Prior buffers may be discarded only after the library establishes
-a restart point within a later buffer.  Similar remarks apply for output into
-a chain of buffers.
-
-The library will never attempt to backtrack over a skip_input_data() call,
-so any skipped data can be permanently discarded.  You still have to deal
-with the case of skipping not-yet-received data, however.
-
-It's much simpler to use only a single buffer; when fill_input_buffer() is
-called, move any unconsumed data (beyond the current pointer/count) down to
-the beginning of this buffer and then load new data into the remaining buffer
-space.  This approach requires a little more data copying but is far easier
-to get right.
-
-
-Progressive JPEG support
-------------------------
-
-Progressive JPEG rearranges the stored data into a series of scans of
-increasing quality.  In situations where a JPEG file is transmitted across a
-slow communications link, a decoder can generate a low-quality image very
-quickly from the first scan, then gradually improve the displayed quality as
-more scans are received.  The final image after all scans are complete is
-identical to that of a regular (sequential) JPEG file of the same quality
-setting.  Progressive JPEG files are often slightly smaller than equivalent
-sequential JPEG files, but the possibility of incremental display is the main
-reason for using progressive JPEG.
-
-The IJG encoder library generates progressive JPEG files when given a
-suitable "scan script" defining how to divide the data into scans.
-Creation of progressive JPEG files is otherwise transparent to the encoder.
-Progressive JPEG files can also be read transparently by the decoder library.
-If the decoding application simply uses the library as defined above, it
-will receive a final decoded image without any indication that the file was
-progressive.  Of course, this approach does not allow incremental display.
-To perform incremental display, an application needs to use the decoder
-library's "buffered-image" mode, in which it receives a decoded image
-multiple times.
-
-Each displayed scan requires about as much work to decode as a full JPEG
-image of the same size, so the decoder must be fairly fast in relation to the
-data transmission rate in order to make incremental display useful.  However,
-it is possible to skip displaying the image and simply add the incoming bits
-to the decoder's coefficient buffer.  This is fast because only Huffman
-decoding need be done, not IDCT, upsampling, colorspace conversion, etc.
-The IJG decoder library allows the application to switch dynamically between
-displaying the image and simply absorbing the incoming bits.  A properly
-coded application can automatically adapt the number of display passes to
-suit the time available as the image is received.  Also, a final
-higher-quality display cycle can be performed from the buffered data after
-the end of the file is reached.
-
-Progressive compression:
-
-To create a progressive JPEG file (or a multiple-scan sequential JPEG file),
-set the scan_info cinfo field to point to an array of scan descriptors, and
-perform compression as usual.  Instead of constructing your own scan list,
-you can call the jpeg_simple_progression() helper routine to create a
-recommended progression sequence; this method should be used by all
-applications that don't want to get involved in the nitty-gritty of
-progressive scan sequence design.  (If you want to provide user control of
-scan sequences, you may wish to borrow the scan script reading code found
-in rdswitch.c, so that you can read scan script files just like cjpeg's.)
-When scan_info is not NULL, the compression library will store DCT'd data
-into a buffer array as jpeg_write_scanlines() is called, and will emit all
-the requested scans during jpeg_finish_compress().  This implies that
-multiple-scan output cannot be created with a suspending data destination
-manager, since jpeg_finish_compress() does not support suspension.  We
-should also note that the compressor currently forces Huffman optimization
-mode when creating a progressive JPEG file, because the default Huffman
-tables are unsuitable for progressive files.
-
-Progressive decompression:
-
-When buffered-image mode is not used, the decoder library will read all of
-a multi-scan file during jpeg_start_decompress(), so that it can provide a
-final decoded image.  (Here "multi-scan" means either progressive or
-multi-scan sequential.)  This makes multi-scan files transparent to the
-decoding application.  However, existing applications that used suspending
-input with version 5 of the IJG library will need to be modified to check
-for a suspension return from jpeg_start_decompress().
-
-To perform incremental display, an application must use the library's
-buffered-image mode.  This is described in the next section.
-
-
-Buffered-image mode
--------------------
-
-In buffered-image mode, the library stores the partially decoded image in a
-coefficient buffer, from which it can be read out as many times as desired.
-This mode is typically used for incremental display of progressive JPEG files,
-but it can be used with any JPEG file.  Each scan of a progressive JPEG file
-adds more data (more detail) to the buffered image.  The application can
-display in lockstep with the source file (one display pass per input scan),
-or it can allow input processing to outrun display processing.  By making
-input and display processing run independently, it is possible for the
-application to adapt progressive display to a wide range of data transmission
-rates.
-
-The basic control flow for buffered-image decoding is
-
-	jpeg_create_decompress()
-	set data source
-	jpeg_read_header()
-	set overall decompression parameters
-	cinfo.buffered_image = TRUE;	/* select buffered-image mode */
-	jpeg_start_decompress()
-	for (each output pass) {
-	    adjust output decompression parameters if required
-	    jpeg_start_output()		/* start a new output pass */
-	    for (all scanlines in image) {
-	        jpeg_read_scanlines()
-	        display scanlines
-	    }
-	    jpeg_finish_output()	/* terminate output pass */
-	}
-	jpeg_finish_decompress()
-	jpeg_destroy_decompress()
-
-This differs from ordinary unbuffered decoding in that there is an additional
-level of looping.  The application can choose how many output passes to make
-and how to display each pass.
-
-The simplest approach to displaying progressive images is to do one display
-pass for each scan appearing in the input file.  In this case the outer loop
-condition is typically
-	while (! jpeg_input_complete(&cinfo))
-and the start-output call should read
-	jpeg_start_output(&cinfo, cinfo.input_scan_number);
-The second parameter to jpeg_start_output() indicates which scan of the input
-file is to be displayed; the scans are numbered starting at 1 for this
-purpose.  (You can use a loop counter starting at 1 if you like, but using
-the library's input scan counter is easier.)  The library automatically reads
-data as necessary to complete each requested scan, and jpeg_finish_output()
-advances to the next scan or end-of-image marker (hence input_scan_number
-will be incremented by the time control arrives back at jpeg_start_output()).
-With this technique, data is read from the input file only as needed, and
-input and output processing run in lockstep.
-
-After reading the final scan and reaching the end of the input file, the
-buffered image remains available; it can be read additional times by
-repeating the jpeg_start_output()/jpeg_read_scanlines()/jpeg_finish_output()
-sequence.  For example, a useful technique is to use fast one-pass color
-quantization for display passes made while the image is arriving, followed by
-a final display pass using two-pass quantization for highest quality.  This
-is done by changing the library parameters before the final output pass.
-Changing parameters between passes is discussed in detail below.
-
-In general the last scan of a progressive file cannot be recognized as such
-until after it is read, so a post-input display pass is the best approach if
-you want special processing in the final pass.
-
-When done with the image, be sure to call jpeg_finish_decompress() to release
-the buffered image (or just use jpeg_destroy_decompress()).
-
-If input data arrives faster than it can be displayed, the application can
-cause the library to decode input data in advance of what's needed to produce
-output.  This is done by calling the routine jpeg_consume_input().
-The return value is one of the following:
-	JPEG_REACHED_SOS:    reached an SOS marker (the start of a new scan)
-	JPEG_REACHED_EOI:    reached the EOI marker (end of image)
-	JPEG_ROW_COMPLETED:  completed reading one MCU row of compressed data
-	JPEG_SCAN_COMPLETED: completed reading last MCU row of current scan
-	JPEG_SUSPENDED:      suspended before completing any of the above
-(JPEG_SUSPENDED can occur only if a suspending data source is used.)  This
-routine can be called at any time after initializing the JPEG object.  It
-reads some additional data and returns when one of the indicated significant
-events occurs.  (If called after the EOI marker is reached, it will
-immediately return JPEG_REACHED_EOI without attempting to read more data.)
-
-The library's output processing will automatically call jpeg_consume_input()
-whenever the output processing overtakes the input; thus, simple lockstep
-display requires no direct calls to jpeg_consume_input().  But by adding
-calls to jpeg_consume_input(), you can absorb data in advance of what is
-being displayed.  This has two benefits:
-  * You can limit buildup of unprocessed data in your input buffer.
-  * You can eliminate extra display passes by paying attention to the
-    state of the library's input processing.
-
-The first of these benefits only requires interspersing calls to
-jpeg_consume_input() with your display operations and any other processing
-you may be doing.  To avoid wasting cycles due to backtracking, it's best to
-call jpeg_consume_input() only after a hundred or so new bytes have arrived.
-This is discussed further under "I/O suspension", above.  (Note: the JPEG
-library currently is not thread-safe.  You must not call jpeg_consume_input()
-from one thread of control if a different library routine is working on the
-same JPEG object in another thread.)
-
-When input arrives fast enough that more than one new scan is available
-before you start a new output pass, you may as well skip the output pass
-corresponding to the completed scan.  This occurs for free if you pass
-cinfo.input_scan_number as the target scan number to jpeg_start_output().
-The input_scan_number field is simply the index of the scan currently being
-consumed by the input processor.  You can ensure that this is up-to-date by
-emptying the input buffer just before calling jpeg_start_output(): call
-jpeg_consume_input() repeatedly until it returns JPEG_SUSPENDED or
-JPEG_REACHED_EOI.
-
-The target scan number passed to jpeg_start_output() is saved in the
-cinfo.output_scan_number field.  The library's output processing calls
-jpeg_consume_input() whenever the current input scan number and row within
-that scan is less than or equal to the current output scan number and row.
-Thus, input processing can "get ahead" of the output processing but is not
-allowed to "fall behind".  You can achieve several different effects by
-manipulating this interlock rule.  For example, if you pass a target scan
-number greater than the current input scan number, the output processor will
-wait until that scan starts to arrive before producing any output.  (To avoid
-an infinite loop, the target scan number is automatically reset to the last
-scan number when the end of image is reached.  Thus, if you specify a large
-target scan number, the library will just absorb the entire input file and
-then perform an output pass.  This is effectively the same as what
-jpeg_start_decompress() does when you don't select buffered-image mode.)
-When you pass a target scan number equal to the current input scan number,
-the image is displayed no faster than the current input scan arrives.  The
-final possibility is to pass a target scan number less than the current input
-scan number; this disables the input/output interlock and causes the output
-processor to simply display whatever it finds in the image buffer, without
-waiting for input.  (However, the library will not accept a target scan
-number less than one, so you can't avoid waiting for the first scan.)
-
-When data is arriving faster than the output display processing can advance
-through the image, jpeg_consume_input() will store data into the buffered
-image beyond the point at which the output processing is reading data out
-again.  If the input arrives fast enough, it may "wrap around" the buffer to
-the point where the input is more than one whole scan ahead of the output.
-If the output processing simply proceeds through its display pass without
-paying attention to the input, the effect seen on-screen is that the lower
-part of the image is one or more scans better in quality than the upper part.
-Then, when the next output scan is started, you have a choice of what target
-scan number to use.  The recommended choice is to use the current input scan
-number at that time, which implies that you've skipped the output scans
-corresponding to the input scans that were completed while you processed the
-previous output scan.  In this way, the decoder automatically adapts its
-speed to the arriving data, by skipping output scans as necessary to keep up
-with the arriving data.
-
-When using this strategy, you'll want to be sure that you perform a final
-output pass after receiving all the data; otherwise your last display may not
-be full quality across the whole screen.  So the right outer loop logic is
-something like this:
-	do {
-	    absorb any waiting input by calling jpeg_consume_input()
-	    final_pass = jpeg_input_complete(&cinfo);
-	    adjust output decompression parameters if required
-	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
-	    ...
-	    jpeg_finish_output()
-	} while (! final_pass);
-rather than quitting as soon as jpeg_input_complete() returns TRUE.  This
-arrangement makes it simple to use higher-quality decoding parameters
-for the final pass.  But if you don't want to use special parameters for
-the final pass, the right loop logic is like this:
-	for (;;) {
-	    absorb any waiting input by calling jpeg_consume_input()
-	    jpeg_start_output(&cinfo, cinfo.input_scan_number);
-	    ...
-	    jpeg_finish_output()
-	    if (jpeg_input_complete(&cinfo) &&
-	        cinfo.input_scan_number == cinfo.output_scan_number)
-	      break;
-	}
-In this case you don't need to know in advance whether an output pass is to
-be the last one, so it's not necessary to have reached EOF before starting
-the final output pass; rather, what you want to test is whether the output
-pass was performed in sync with the final input scan.  This form of the loop
-will avoid an extra output pass whenever the decoder is able (or nearly able)
-to keep up with the incoming data.
-
-When the data transmission speed is high, you might begin a display pass,
-then find that much or all of the file has arrived before you can complete
-the pass.  (You can detect this by noting the JPEG_REACHED_EOI return code
-from jpeg_consume_input(), or equivalently by testing jpeg_input_complete().)
-In this situation you may wish to abort the current display pass and start a
-new one using the newly arrived information.  To do so, just call
-jpeg_finish_output() and then start a new pass with jpeg_start_output().
-
-A variant strategy is to abort and restart display if more than one complete
-scan arrives during an output pass; this can be detected by noting
-JPEG_REACHED_SOS returns and/or examining cinfo.input_scan_number.  This
-idea should be employed with caution, however, since the display process
-might never get to the bottom of the image before being aborted, resulting
-in the lower part of the screen being several passes worse than the upper.
-In most cases it's probably best to abort an output pass only if the whole
-file has arrived and you want to begin the final output pass immediately.
-
-When receiving data across a communication link, we recommend always using
-the current input scan number for the output target scan number; if a
-higher-quality final pass is to be done, it should be started (aborting any
-incomplete output pass) as soon as the end of file is received.  However,
-many other strategies are possible.  For example, the application can examine
-the parameters of the current input scan and decide whether to display it or
-not.  If the scan contains only chroma data, one might choose not to use it
-as the target scan, expecting that the scan will be small and will arrive
-quickly.  To skip to the next scan, call jpeg_consume_input() until it
-returns JPEG_REACHED_SOS or JPEG_REACHED_EOI.  Or just use the next higher
-number as the target scan for jpeg_start_output(); but that method doesn't
-let you inspect the next scan's parameters before deciding to display it.
-
-
-In buffered-image mode, jpeg_start_decompress() never performs input and
-thus never suspends.  An application that uses input suspension with
-buffered-image mode must be prepared for suspension returns from these
-routines:
-* jpeg_start_output() performs input only if you request 2-pass quantization
-  and the target scan isn't fully read yet.  (This is discussed below.)
-* jpeg_read_scanlines(), as always, returns the number of scanlines that it
-  was able to produce before suspending.
-* jpeg_finish_output() will read any markers following the target scan,
-  up to the end of the file or the SOS marker that begins another scan.
-  (But it reads no input if jpeg_consume_input() has already reached the
-  end of the file or a SOS marker beyond the target output scan.)
-* jpeg_finish_decompress() will read until the end of file, and thus can
-  suspend if the end hasn't already been reached (as can be tested by
-  calling jpeg_input_complete()).
-jpeg_start_output(), jpeg_finish_output(), and jpeg_finish_decompress()
-all return TRUE if they completed their tasks, FALSE if they had to suspend.
-In the event of a FALSE return, the application must load more input data
-and repeat the call.  Applications that use non-suspending data sources need
-not check the return values of these three routines.
-
-
-It is possible to change decoding parameters between output passes in the
-buffered-image mode.  The decoder library currently supports only very
-limited changes of parameters.  ONLY THE FOLLOWING parameter changes are
-allowed after jpeg_start_decompress() is called:
-* dct_method can be changed before each call to jpeg_start_output().
-  For example, one could use a fast DCT method for early scans, changing
-  to a higher quality method for the final scan.
-* dither_mode can be changed before each call to jpeg_start_output();
-  of course this has no impact if not using color quantization.  Typically
-  one would use ordered dither for initial passes, then switch to
-  Floyd-Steinberg dither for the final pass.  Caution: changing dither mode
-  can cause more memory to be allocated by the library.  Although the amount
-  of memory involved is not large (a scanline or so), it may cause the
-  initial max_memory_to_use specification to be exceeded, which in the worst
-  case would result in an out-of-memory failure.
-* do_block_smoothing can be changed before each call to jpeg_start_output().
-  This setting is relevant only when decoding a progressive JPEG image.
-  During the first DC-only scan, block smoothing provides a very "fuzzy" look
-  instead of the very "blocky" look seen without it; which is better seems a
-  matter of personal taste.  But block smoothing is nearly always a win
-  during later stages, especially when decoding a successive-approximation
-  image: smoothing helps to hide the slight blockiness that otherwise shows
-  up on smooth gradients until the lowest coefficient bits are sent.
-* Color quantization mode can be changed under the rules described below.
-  You *cannot* change between full-color and quantized output (because that
-  would alter the required I/O buffer sizes), but you can change which
-  quantization method is used.
-
-When generating color-quantized output, changing quantization method is a
-very useful way of switching between high-speed and high-quality display.
-The library allows you to change among its three quantization methods:
-1. Single-pass quantization to a fixed color cube.
-   Selected by cinfo.two_pass_quantize = FALSE and cinfo.colormap = NULL.
-2. Single-pass quantization to an application-supplied colormap.
-   Selected by setting cinfo.colormap to point to the colormap (the value of
-   two_pass_quantize is ignored); also set cinfo.actual_number_of_colors.
-3. Two-pass quantization to a colormap chosen specifically for the image.
-   Selected by cinfo.two_pass_quantize = TRUE and cinfo.colormap = NULL.
-   (This is the default setting selected by jpeg_read_header, but it is
-   probably NOT what you want for the first pass of progressive display!)
-These methods offer successively better quality and lesser speed.  However,
-only the first method is available for quantizing in non-RGB color spaces.
-
-IMPORTANT: because the different quantizer methods have very different
-working-storage requirements, the library requires you to indicate which
-one(s) you intend to use before you call jpeg_start_decompress().  (If we did
-not require this, the max_memory_to_use setting would be a complete fiction.)
-You do this by setting one or more of these three cinfo fields to TRUE:
-	enable_1pass_quant		Fixed color cube colormap
-	enable_external_quant		Externally-supplied colormap
-	enable_2pass_quant		Two-pass custom colormap
-All three are initialized FALSE by jpeg_read_header().  But
-jpeg_start_decompress() automatically sets TRUE the one selected by the
-current two_pass_quantize and colormap settings, so you only need to set the
-enable flags for any other quantization methods you plan to change to later.
-
-After setting the enable flags correctly at jpeg_start_decompress() time, you
-can change to any enabled quantization method by setting two_pass_quantize
-and colormap properly just before calling jpeg_start_output().  The following
-special rules apply:
-1. You must explicitly set cinfo.colormap to NULL when switching to 1-pass
-   or 2-pass mode from a different mode, or when you want the 2-pass
-   quantizer to be re-run to generate a new colormap.
-2. To switch to an external colormap, or to change to a different external
-   colormap than was used on the prior pass, you must call
-   jpeg_new_colormap() after setting cinfo.colormap.
-NOTE: if you want to use the same colormap as was used in the prior pass,
-you should not do either of these things.  This will save some nontrivial
-switchover costs.
-(These requirements exist because cinfo.colormap will always be non-NULL
-after completing a prior output pass, since both the 1-pass and 2-pass
-quantizers set it to point to their output colormaps.  Thus you have to
-do one of these two things to notify the library that something has changed.
-Yup, it's a bit klugy, but it's necessary to do it this way for backwards
-compatibility.)
-
-Note that in buffered-image mode, the library generates any requested colormap
-during jpeg_start_output(), not during jpeg_start_decompress().
-
-When using two-pass quantization, jpeg_start_output() makes a pass over the
-buffered image to determine the optimum color map; it therefore may take a
-significant amount of time, whereas ordinarily it does little work.  The
-progress monitor hook is called during this pass, if defined.  It is also
-important to realize that if the specified target scan number is greater than
-or equal to the current input scan number, jpeg_start_output() will attempt
-to consume input as it makes this pass.  If you use a suspending data source,
-you need to check for a FALSE return from jpeg_start_output() under these
-conditions.  The combination of 2-pass quantization and a not-yet-fully-read
-target scan is the only case in which jpeg_start_output() will consume input.
-
-
-Application authors who support buffered-image mode may be tempted to use it
-for all JPEG images, even single-scan ones.  This will work, but it is
-inefficient: there is no need to create an image-sized coefficient buffer for
-single-scan images.  Requesting buffered-image mode for such an image wastes
-memory.  Worse, it can cost time on large images, since the buffered data has
-to be swapped out or written to a temporary file.  If you are concerned about
-maximum performance on baseline JPEG files, you should use buffered-image
-mode only when the incoming file actually has multiple scans.  This can be
-tested by calling jpeg_has_multiple_scans(), which will return a correct
-result at any time after jpeg_read_header() completes.
-
-It is also worth noting that when you use jpeg_consume_input() to let input
-processing get ahead of output processing, the resulting pattern of access to
-the coefficient buffer is quite nonsequential.  It's best to use the memory
-manager jmemnobs.c if you can (ie, if you have enough real or virtual main
-memory).  If not, at least make sure that max_memory_to_use is set as high as
-possible.  If the JPEG memory manager has to use a temporary file, you will
-probably see a lot of disk traffic and poor performance.  (This could be
-improved with additional work on the memory manager, but we haven't gotten
-around to it yet.)
-
-In some applications it may be convenient to use jpeg_consume_input() for all
-input processing, including reading the initial markers; that is, you may
-wish to call jpeg_consume_input() instead of jpeg_read_header() during
-startup.  This works, but note that you must check for JPEG_REACHED_SOS and
-JPEG_REACHED_EOI return codes as the equivalent of jpeg_read_header's codes.
-Once the first SOS marker has been reached, you must call
-jpeg_start_decompress() before jpeg_consume_input() will consume more input;
-it'll just keep returning JPEG_REACHED_SOS until you do.  If you read a
-tables-only file this way, jpeg_consume_input() will return JPEG_REACHED_EOI
-without ever returning JPEG_REACHED_SOS; be sure to check for this case.
-If this happens, the decompressor will not read any more input until you call
-jpeg_abort() to reset it.  It is OK to call jpeg_consume_input() even when not
-using buffered-image mode, but in that case it's basically a no-op after the
-initial markers have been read: it will just return JPEG_SUSPENDED.
-
-
-Abbreviated datastreams and multiple images
--------------------------------------------
-
-A JPEG compression or decompression object can be reused to process multiple
-images.  This saves a small amount of time per image by eliminating the
-"create" and "destroy" operations, but that isn't the real purpose of the
-feature.  Rather, reuse of an object provides support for abbreviated JPEG
-datastreams.  Object reuse can also simplify processing a series of images in
-a single input or output file.  This section explains these features.
-
-A JPEG file normally contains several hundred bytes worth of quantization
-and Huffman tables.  In a situation where many images will be stored or
-transmitted with identical tables, this may represent an annoying overhead.
-The JPEG standard therefore permits tables to be omitted.  The standard
-defines three classes of JPEG datastreams:
-  * "Interchange" datastreams contain an image and all tables needed to decode
-     the image.  These are the usual kind of JPEG file.
-  * "Abbreviated image" datastreams contain an image, but are missing some or
-    all of the tables needed to decode that image.
-  * "Abbreviated table specification" (henceforth "tables-only") datastreams
-    contain only table specifications.
-To decode an abbreviated image, it is necessary to load the missing table(s)
-into the decoder beforehand.  This can be accomplished by reading a separate
-tables-only file.  A variant scheme uses a series of images in which the first
-image is an interchange (complete) datastream, while subsequent ones are
-abbreviated and rely on the tables loaded by the first image.  It is assumed
-that once the decoder has read a table, it will remember that table until a
-new definition for the same table number is encountered.
-
-It is the application designer's responsibility to figure out how to associate
-the correct tables with an abbreviated image.  While abbreviated datastreams
-can be useful in a closed environment, their use is strongly discouraged in
-any situation where data exchange with other applications might be needed.
-Caveat designer.
-
-The JPEG library provides support for reading and writing any combination of
-tables-only datastreams and abbreviated images.  In both compression and
-decompression objects, a quantization or Huffman table will be retained for
-the lifetime of the object, unless it is overwritten by a new table definition.
-
-
-To create abbreviated image datastreams, it is only necessary to tell the
-compressor not to emit some or all of the tables it is using.  Each
-quantization and Huffman table struct contains a boolean field "sent_table",
-which normally is initialized to FALSE.  For each table used by the image, the
-header-writing process emits the table and sets sent_table = TRUE unless it is
-already TRUE.  (In normal usage, this prevents outputting the same table
-definition multiple times, as would otherwise occur because the chroma
-components typically share tables.)  Thus, setting this field to TRUE before
-calling jpeg_start_compress() will prevent the table from being written at
-all.
-
-If you want to create a "pure" abbreviated image file containing no tables,
-just call "jpeg_suppress_tables(&cinfo, TRUE)" after constructing all the
-tables.  If you want to emit some but not all tables, you'll need to set the
-individual sent_table fields directly.
-
-To create an abbreviated image, you must also call jpeg_start_compress()
-with a second parameter of FALSE, not TRUE.  Otherwise jpeg_start_compress()
-will force all the sent_table fields to FALSE.  (This is a safety feature to
-prevent abbreviated images from being created accidentally.)
-
-To create a tables-only file, perform the same parameter setup that you
-normally would, but instead of calling jpeg_start_compress() and so on, call
-jpeg_write_tables(&cinfo).  This will write an abbreviated datastream
-containing only SOI, DQT and/or DHT markers, and EOI.  All the quantization
-and Huffman tables that are currently defined in the compression object will
-be emitted unless their sent_tables flag is already TRUE, and then all the
-sent_tables flags will be set TRUE.
-
-A sure-fire way to create matching tables-only and abbreviated image files
-is to proceed as follows:
-
-	create JPEG compression object
-	set JPEG parameters
-	set destination to tables-only file
-	jpeg_write_tables(&cinfo);
-	set destination to image file
-	jpeg_start_compress(&cinfo, FALSE);
-	write data...
-	jpeg_finish_compress(&cinfo);
-
-Since the JPEG parameters are not altered between writing the table file and
-the abbreviated image file, the same tables are sure to be used.  Of course,
-you can repeat the jpeg_start_compress() ... jpeg_finish_compress() sequence
-many times to produce many abbreviated image files matching the table file.
-
-You cannot suppress output of the computed Huffman tables when Huffman
-optimization is selected.  (If you could, there'd be no way to decode the
-image...)  Generally, you don't want to set optimize_coding = TRUE when
-you are trying to produce abbreviated files.
-
-In some cases you might want to compress an image using tables which are
-not stored in the application, but are defined in an interchange or
-tables-only file readable by the application.  This can be done by setting up
-a JPEG decompression object to read the specification file, then copying the
-tables into your compression object.  See jpeg_copy_critical_parameters()
-for an example of copying quantization tables.
-
-
-To read abbreviated image files, you simply need to load the proper tables
-into the decompression object before trying to read the abbreviated image.
-If the proper tables are stored in the application program, you can just
-allocate the table structs and fill in their contents directly.  For example,
-to load a fixed quantization table into table slot "n":
-
-    if (cinfo.quant_tbl_ptrs[n] == NULL)
-      cinfo.quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) &cinfo);
-    quant_ptr = cinfo.quant_tbl_ptrs[n];	/* quant_ptr is JQUANT_TBL* */
-    for (i = 0; i < 64; i++) {
-      /* Qtable[] is desired quantization table, in natural array order */
-      quant_ptr->quantval[i] = Qtable[i];
-    }
-
-Code to load a fixed Huffman table is typically (for AC table "n"):
-
-    if (cinfo.ac_huff_tbl_ptrs[n] == NULL)
-      cinfo.ac_huff_tbl_ptrs[n] = jpeg_alloc_huff_table((j_common_ptr) &cinfo);
-    huff_ptr = cinfo.ac_huff_tbl_ptrs[n];	/* huff_ptr is JHUFF_TBL* */
-    for (i = 1; i <= 16; i++) {
-      /* counts[i] is number of Huffman codes of length i bits, i=1..16 */
-      huff_ptr->bits[i] = counts[i];
-    }
-    for (i = 0; i < 256; i++) {
-      /* symbols[] is the list of Huffman symbols, in code-length order */
-      huff_ptr->huffval[i] = symbols[i];
-    }
-
-(Note that trying to set cinfo.quant_tbl_ptrs[n] to point directly at a
-constant JQUANT_TBL object is not safe.  If the incoming file happened to
-contain a quantization table definition, your master table would get
-overwritten!  Instead allocate a working table copy and copy the master table
-into it, as illustrated above.  Ditto for Huffman tables, of course.)
-
-You might want to read the tables from a tables-only file, rather than
-hard-wiring them into your application.  The jpeg_read_header() call is
-sufficient to read a tables-only file.  You must pass a second parameter of
-FALSE to indicate that you do not require an image to be present.  Thus, the
-typical scenario is
-
-	create JPEG decompression object
-	set source to tables-only file
-	jpeg_read_header(&cinfo, FALSE);
-	set source to abbreviated image file
-	jpeg_read_header(&cinfo, TRUE);
-	set decompression parameters
-	jpeg_start_decompress(&cinfo);
-	read data...
-	jpeg_finish_decompress(&cinfo);
-
-In some cases, you may want to read a file without knowing whether it contains
-an image or just tables.  In that case, pass FALSE and check the return value
-from jpeg_read_header(): it will be JPEG_HEADER_OK if an image was found,
-JPEG_HEADER_TABLES_ONLY if only tables were found.  (A third return value,
-JPEG_SUSPENDED, is possible when using a suspending data source manager.)
-Note that jpeg_read_header() will not complain if you read an abbreviated
-image for which you haven't loaded the missing tables; the missing-table check
-occurs later, in jpeg_start_decompress().
-
-
-It is possible to read a series of images from a single source file by
-repeating the jpeg_read_header() ... jpeg_finish_decompress() sequence,
-without releasing/recreating the JPEG object or the data source module.
-(If you did reinitialize, any partial bufferload left in the data source
-buffer at the end of one image would be discarded, causing you to lose the
-start of the next image.)  When you use this method, stored tables are
-automatically carried forward, so some of the images can be abbreviated images
-that depend on tables from earlier images.
-
-If you intend to write a series of images into a single destination file,
-you might want to make a specialized data destination module that doesn't
-flush the output buffer at term_destination() time.  This would speed things
-up by some trifling amount.  Of course, you'd need to remember to flush the
-buffer after the last image.  You can make the later images be abbreviated
-ones by passing FALSE to jpeg_start_compress().
-
-
-Special markers
----------------
-
-Some applications may need to insert or extract special data in the JPEG
-datastream.  The JPEG standard provides marker types "COM" (comment) and
-"APP0" through "APP15" (application) to hold application-specific data.
-Unfortunately, the use of these markers is not specified by the standard.
-COM markers are fairly widely used to hold user-supplied text.  The JFIF file
-format spec uses APP0 markers with specified initial strings to hold certain
-data.  Adobe applications use APP14 markers beginning with the string "Adobe"
-for miscellaneous data.  Other APPn markers are rarely seen, but might
-contain almost anything.
-
-If you wish to store user-supplied text, we recommend you use COM markers
-and place readable 7-bit ASCII text in them.  Newline conventions are not
-standardized --- expect to find LF (Unix style), CR/LF (DOS style), or CR
-(Mac style).  A robust COM reader should be able to cope with random binary
-garbage, including nulls, since some applications generate COM markers
-containing non-ASCII junk.  (But yours should not be one of them.)
-
-For program-supplied data, use an APPn marker, and be sure to begin it with an
-identifying string so that you can tell whether the marker is actually yours.
-It's probably best to avoid using APP0 or APP14 for any private markers.
-(NOTE: the upcoming SPIFF standard will use APP8 markers; we recommend you
-not use APP8 markers for any private purposes, either.)
-
-Keep in mind that at most 65533 bytes can be put into one marker, but you
-can have as many markers as you like.
-
-By default, the IJG compression library will write a JFIF APP0 marker if the
-selected JPEG colorspace is grayscale or YCbCr, or an Adobe APP14 marker if
-the selected colorspace is RGB, CMYK, or YCCK.  You can disable this, but
-we don't recommend it.  The decompression library will recognize JFIF and
-Adobe markers and will set the JPEG colorspace properly when one is found.
-
-
-You can write special markers immediately following the datastream header by
-calling jpeg_write_marker() after jpeg_start_compress() and before the first
-call to jpeg_write_scanlines().  When you do this, the markers appear after
-the SOI and the JFIF APP0 and Adobe APP14 markers (if written), but before
-all else.  Specify the marker type parameter as "JPEG_COM" for COM or
-"JPEG_APP0 + n" for APPn.  (Actually, jpeg_write_marker will let you write
-any marker type, but we don't recommend writing any other kinds of marker.)
-For example, to write a user comment string pointed to by comment_text:
-	jpeg_write_marker(cinfo, JPEG_COM, comment_text, strlen(comment_text));
-
-If it's not convenient to store all the marker data in memory at once,
-you can instead call jpeg_write_m_header() followed by multiple calls to
-jpeg_write_m_byte().  If you do it this way, it's your responsibility to
-call jpeg_write_m_byte() exactly the number of times given in the length
-parameter to jpeg_write_m_header().  (This method lets you empty the
-output buffer partway through a marker, which might be important when
-using a suspending data destination module.  In any case, if you are using
-a suspending destination, you should flush its buffer after inserting
-any special markers.  See "I/O suspension".)
-
-Or, if you prefer to synthesize the marker byte sequence yourself,
-you can just cram it straight into the data destination module.
-
-If you are writing JFIF 1.02 extension markers (thumbnail images), don't
-forget to set cinfo.JFIF_minor_version = 2 so that the encoder will write the
-correct JFIF version number in the JFIF header marker.  The library's default
-is to write version 1.01, but that's wrong if you insert any 1.02 extension
-markers.  (We could probably get away with just defaulting to 1.02, but there
-used to be broken decoders that would complain about unknown minor version
-numbers.  To reduce compatibility risks it's safest not to write 1.02 unless
-you are actually using 1.02 extensions.)
-
-
-When reading, two methods of handling special markers are available:
-1. You can ask the library to save the contents of COM and/or APPn markers
-into memory, and then examine them at your leisure afterwards.
-2. You can supply your own routine to process COM and/or APPn markers
-on-the-fly as they are read.
-The first method is simpler to use, especially if you are using a suspending
-data source; writing a marker processor that copes with input suspension is
-not easy (consider what happens if the marker is longer than your available
-input buffer).  However, the second method conserves memory since the marker
-data need not be kept around after it's been processed.
-
-For either method, you'd normally set up marker handling after creating a
-decompression object and before calling jpeg_read_header(), because the
-markers of interest will typically be near the head of the file and so will
-be scanned by jpeg_read_header.  Once you've established a marker handling
-method, it will be used for the life of that decompression object
-(potentially many datastreams), unless you change it.  Marker handling is
-determined separately for COM markers and for each APPn marker code.
-
-
-To save the contents of special markers in memory, call
-	jpeg_save_markers(cinfo, marker_code, length_limit)
-where marker_code is the marker type to save, JPEG_COM or JPEG_APP0+n.
-(To arrange to save all the special marker types, you need to call this
-routine 17 times, for COM and APP0-APP15.)  If the incoming marker is longer
-than length_limit data bytes, only length_limit bytes will be saved; this
-parameter allows you to avoid chewing up memory when you only need to see the
-first few bytes of a potentially large marker.  If you want to save all the
-data, set length_limit to 0xFFFF; that is enough since marker lengths are only
-16 bits.  As a special case, setting length_limit to 0 prevents that marker
-type from being saved at all.  (That is the default behavior, in fact.)
-
-After jpeg_read_header() completes, you can examine the special markers by
-following the cinfo->marker_list pointer chain.  All the special markers in
-the file appear in this list, in order of their occurrence in the file (but
-omitting any markers of types you didn't ask for).  Both the original data
-length and the saved data length are recorded for each list entry; the latter
-will not exceed length_limit for the particular marker type.  Note that these
-lengths exclude the marker length word, whereas the stored representation
-within the JPEG file includes it.  (Hence the maximum data length is really
-only 65533.)
-
-It is possible that additional special markers appear in the file beyond the
-SOS marker at which jpeg_read_header stops; if so, the marker list will be
-extended during reading of the rest of the file.  This is not expected to be
-common, however.  If you are short on memory you may want to reset the length
-limit to zero for all marker types after finishing jpeg_read_header, to
-ensure that the max_memory_to_use setting cannot be exceeded due to addition
-of later markers.
-
-The marker list remains stored until you call jpeg_finish_decompress or
-jpeg_abort, at which point the memory is freed and the list is set to empty.
-(jpeg_destroy also releases the storage, of course.)
-
-Note that the library is internally interested in APP0 and APP14 markers;
-if you try to set a small nonzero length limit on these types, the library
-will silently force the length up to the minimum it wants.  (But you can set
-a zero length limit to prevent them from being saved at all.)  Also, in a
-16-bit environment, the maximum length limit may be constrained to less than
-65533 by malloc() limitations.  It is therefore best not to assume that the
-effective length limit is exactly what you set it to be.
-
-
-If you want to supply your own marker-reading routine, you do it by calling
-jpeg_set_marker_processor().  A marker processor routine must have the
-signature
-	boolean jpeg_marker_parser_method (j_decompress_ptr cinfo)
-Although the marker code is not explicitly passed, the routine can find it
-in cinfo->unread_marker.  At the time of call, the marker proper has been
-read from the data source module.  The processor routine is responsible for
-reading the marker length word and the remaining parameter bytes, if any.
-Return TRUE to indicate success.  (FALSE should be returned only if you are
-using a suspending data source and it tells you to suspend.  See the standard
-marker processors in jdmarker.c for appropriate coding methods if you need to
-use a suspending data source.)
-
-If you override the default APP0 or APP14 processors, it is up to you to
-recognize JFIF and Adobe markers if you want colorspace recognition to occur
-properly.  We recommend copying and extending the default processors if you
-want to do that.  (A better idea is to save these marker types for later
-examination by calling jpeg_save_markers(); that method doesn't interfere
-with the library's own processing of these markers.)
-
-jpeg_set_marker_processor() and jpeg_save_markers() are mutually exclusive
---- if you call one it overrides any previous call to the other, for the
-particular marker type specified.
-
-A simple example of an external COM processor can be found in djpeg.c.
-Also, see jpegtran.c for an example of using jpeg_save_markers.
-
-
-Raw (downsampled) image data
-----------------------------
-
-Some applications need to supply already-downsampled image data to the JPEG
-compressor, or to receive raw downsampled data from the decompressor.  The
-library supports this requirement by allowing the application to write or
-read raw data, bypassing the normal preprocessing or postprocessing steps.
-The interface is different from the standard one and is somewhat harder to
-use.  If your interest is merely in bypassing color conversion, we recommend
-that you use the standard interface and simply set jpeg_color_space =
-in_color_space (or jpeg_color_space = out_color_space for decompression).
-The mechanism described in this section is necessary only to supply or
-receive downsampled image data, in which not all components have the same
-dimensions.
-
-
-To compress raw data, you must supply the data in the colorspace to be used
-in the JPEG file (please read the earlier section on Special color spaces)
-and downsampled to the sampling factors specified in the JPEG parameters.
-You must supply the data in the format used internally by the JPEG library,
-namely a JSAMPIMAGE array.  This is an array of pointers to two-dimensional
-arrays, each of type JSAMPARRAY.  Each 2-D array holds the values for one
-color component.  This structure is necessary since the components are of
-different sizes.  If the image dimensions are not a multiple of the MCU size,
-you must also pad the data correctly (usually, this is done by replicating
-the last column and/or row).  The data must be padded to a multiple of a DCT
-block in each component: that is, each downsampled row must contain a
-multiple of 8 valid samples, and there must be a multiple of 8 sample rows
-for each component.  (For applications such as conversion of digital TV
-images, the standard image size is usually a multiple of the DCT block size,
-so that no padding need actually be done.)
-
-The procedure for compression of raw data is basically the same as normal
-compression, except that you call jpeg_write_raw_data() in place of
-jpeg_write_scanlines().  Before calling jpeg_start_compress(), you must do
-the following:
-  * Set cinfo->raw_data_in to TRUE.  (It is set FALSE by jpeg_set_defaults().)
-    This notifies the library that you will be supplying raw data.
-  * Ensure jpeg_color_space is correct --- an explicit jpeg_set_colorspace()
-    call is a good idea.  Note that since color conversion is bypassed,
-    in_color_space is ignored, except that jpeg_set_defaults() uses it to
-    choose the default jpeg_color_space setting.
-  * Ensure the sampling factors, cinfo->comp_info[i].h_samp_factor and
-    cinfo->comp_info[i].v_samp_factor, are correct.  Since these indicate the
-    dimensions of the data you are supplying, it's wise to set them
-    explicitly, rather than assuming the library's defaults are what you want.
-
-To pass raw data to the library, call jpeg_write_raw_data() in place of
-jpeg_write_scanlines().  The two routines work similarly except that
-jpeg_write_raw_data takes a JSAMPIMAGE data array rather than JSAMPARRAY.
-The scanlines count passed to and returned from jpeg_write_raw_data is
-measured in terms of the component with the largest v_samp_factor.
-
-jpeg_write_raw_data() processes one MCU row per call, which is to say
-v_samp_factor*DCTSIZE sample rows of each component.  The passed num_lines
-value must be at least max_v_samp_factor*DCTSIZE, and the return value will
-be exactly that amount (or possibly some multiple of that amount, in future
-library versions).  This is true even on the last call at the bottom of the
-image; don't forget to pad your data as necessary.
-
-The required dimensions of the supplied data can be computed for each
-component as
-	cinfo->comp_info[i].width_in_blocks*DCTSIZE  samples per row
-	cinfo->comp_info[i].height_in_blocks*DCTSIZE rows in image
-after jpeg_start_compress() has initialized those fields.  If the valid data
-is smaller than this, it must be padded appropriately.  For some sampling
-factors and image sizes, additional dummy DCT blocks are inserted to make
-the image a multiple of the MCU dimensions.  The library creates such dummy
-blocks itself; it does not read them from your supplied data.  Therefore you
-need never pad by more than DCTSIZE samples.  An example may help here.
-Assume 2h2v downsampling of YCbCr data, that is
-	cinfo->comp_info[0].h_samp_factor = 2		for Y
-	cinfo->comp_info[0].v_samp_factor = 2
-	cinfo->comp_info[1].h_samp_factor = 1		for Cb
-	cinfo->comp_info[1].v_samp_factor = 1
-	cinfo->comp_info[2].h_samp_factor = 1		for Cr
-	cinfo->comp_info[2].v_samp_factor = 1
-and suppose that the nominal image dimensions (cinfo->image_width and
-cinfo->image_height) are 101x101 pixels.  Then jpeg_start_compress() will
-compute downsampled_width = 101 and width_in_blocks = 13 for Y,
-downsampled_width = 51 and width_in_blocks = 7 for Cb and Cr (and the same
-for the height fields).  You must pad the Y data to at least 13*8 = 104
-columns and rows, the Cb/Cr data to at least 7*8 = 56 columns and rows.  The
-MCU height is max_v_samp_factor = 2 DCT rows so you must pass at least 16
-scanlines on each call to jpeg_write_raw_data(), which is to say 16 actual
-sample rows of Y and 8 each of Cb and Cr.  A total of 7 MCU rows are needed,
-so you must pass a total of 7*16 = 112 "scanlines".  The last DCT block row
-of Y data is dummy, so it doesn't matter what you pass for it in the data
-arrays, but the scanlines count must total up to 112 so that all of the Cb
-and Cr data gets passed.
-
-Output suspension is supported with raw-data compression: if the data
-destination module suspends, jpeg_write_raw_data() will return 0.
-In this case the same data rows must be passed again on the next call.
-
-
-Decompression with raw data output implies bypassing all postprocessing:
-you cannot ask for rescaling or color quantization, for instance.  More
-seriously, you must deal with the color space and sampling factors present in
-the incoming file.  If your application only handles, say, 2h1v YCbCr data,
-you must check for and fail on other color spaces or other sampling factors.
-The library will not convert to a different color space for you.
-
-To obtain raw data output, set cinfo->raw_data_out = TRUE before
-jpeg_start_decompress() (it is set FALSE by jpeg_read_header()).  Be sure to
-verify that the color space and sampling factors are ones you can handle.
-Then call jpeg_read_raw_data() in place of jpeg_read_scanlines().  The
-decompression process is otherwise the same as usual.
-
-jpeg_read_raw_data() returns one MCU row per call, and thus you must pass a
-buffer of at least max_v_samp_factor*DCTSIZE scanlines (scanline counting is
-the same as for raw-data compression).  The buffer you pass must be large
-enough to hold the actual data plus padding to DCT-block boundaries.  As with
-compression, any entirely dummy DCT blocks are not processed so you need not
-allocate space for them, but the total scanline count includes them.  The
-above example of computing buffer dimensions for raw-data compression is
-equally valid for decompression.
-
-Input suspension is supported with raw-data decompression: if the data source
-module suspends, jpeg_read_raw_data() will return 0.  You can also use
-buffered-image mode to read raw data in multiple passes.
-
-
-Really raw data: DCT coefficients
----------------------------------
-
-It is possible to read or write the contents of a JPEG file as raw DCT
-coefficients.  This facility is mainly intended for use in lossless
-transcoding between different JPEG file formats.  Other possible applications
-include lossless cropping of a JPEG image, lossless reassembly of a
-multi-strip or multi-tile TIFF/JPEG file into a single JPEG datastream, etc.
-
-To read the contents of a JPEG file as DCT coefficients, open the file and do
-jpeg_read_header() as usual.  But instead of calling jpeg_start_decompress()
-and jpeg_read_scanlines(), call jpeg_read_coefficients().  This will read the
-entire image into a set of virtual coefficient-block arrays, one array per
-component.  The return value is a pointer to an array of virtual-array
-descriptors.  Each virtual array can be accessed directly using the JPEG
-memory manager's access_virt_barray method (see Memory management, below,
-and also read structure.doc's discussion of virtual array handling).  Or,
-for simple transcoding to a different JPEG file format, the array list can
-just be handed directly to jpeg_write_coefficients().
-
-Each block in the block arrays contains quantized coefficient values in
-normal array order (not JPEG zigzag order).  The block arrays contain only
-DCT blocks containing real data; any entirely-dummy blocks added to fill out
-interleaved MCUs at the right or bottom edges of the image are discarded
-during reading and are not stored in the block arrays.  (The size of each
-block array can be determined from the width_in_blocks and height_in_blocks
-fields of the component's comp_info entry.)  This is also the data format
-expected by jpeg_write_coefficients().
-
-When you are done using the virtual arrays, call jpeg_finish_decompress()
-to release the array storage and return the decompression object to an idle
-state; or just call jpeg_destroy() if you don't need to reuse the object.
-
-If you use a suspending data source, jpeg_read_coefficients() will return
-NULL if it is forced to suspend; a non-NULL return value indicates successful
-completion.  You need not test for a NULL return value when using a
-non-suspending data source.
-
-It is also possible to call jpeg_read_coefficients() to obtain access to the
-decoder's coefficient arrays during a normal decode cycle in buffered-image
-mode.  This frammish might be useful for progressively displaying an incoming
-image and then re-encoding it without loss.  To do this, decode in buffered-
-image mode as discussed previously, then call jpeg_read_coefficients() after
-the last jpeg_finish_output() call.  The arrays will be available for your use
-until you call jpeg_finish_decompress().
-
-
-To write the contents of a JPEG file as DCT coefficients, you must provide
-the DCT coefficients stored in virtual block arrays.  You can either pass
-block arrays read from an input JPEG file by jpeg_read_coefficients(), or
-allocate virtual arrays from the JPEG compression object and fill them
-yourself.  In either case, jpeg_write_coefficients() is substituted for
-jpeg_start_compress() and jpeg_write_scanlines().  Thus the sequence is
-  * Create compression object
-  * Set all compression parameters as necessary
-  * Request virtual arrays if needed
-  * jpeg_write_coefficients()
-  * jpeg_finish_compress()
-  * Destroy or re-use compression object
-jpeg_write_coefficients() is passed a pointer to an array of virtual block
-array descriptors; the number of arrays is equal to cinfo.num_components.
-
-The virtual arrays need only have been requested, not realized, before
-jpeg_write_coefficients() is called.  A side-effect of
-jpeg_write_coefficients() is to realize any virtual arrays that have been
-requested from the compression object's memory manager.  Thus, when obtaining
-the virtual arrays from the compression object, you should fill the arrays
-after calling jpeg_write_coefficients().  The data is actually written out
-when you call jpeg_finish_compress(); jpeg_write_coefficients() only writes
-the file header.
-
-When writing raw DCT coefficients, it is crucial that the JPEG quantization
-tables and sampling factors match the way the data was encoded, or the
-resulting file will be invalid.  For transcoding from an existing JPEG file,
-we recommend using jpeg_copy_critical_parameters().  This routine initializes
-all the compression parameters to default values (like jpeg_set_defaults()),
-then copies the critical information from a source decompression object.
-The decompression object should have just been used to read the entire
-JPEG input file --- that is, it should be awaiting jpeg_finish_decompress().
-
-jpeg_write_coefficients() marks all tables stored in the compression object
-as needing to be written to the output file (thus, it acts like
-jpeg_start_compress(cinfo, TRUE)).  This is for safety's sake, to avoid
-emitting abbreviated JPEG files by accident.  If you really want to emit an
-abbreviated JPEG file, call jpeg_suppress_tables(), or set the tables'
-individual sent_table flags, between calling jpeg_write_coefficients() and
-jpeg_finish_compress().
-
-
-Progress monitoring
--------------------
-
-Some applications may need to regain control from the JPEG library every so
-often.  The typical use of this feature is to produce a percent-done bar or
-other progress display.  (For a simple example, see cjpeg.c or djpeg.c.)
-Although you do get control back frequently during the data-transferring pass
-(the jpeg_read_scanlines or jpeg_write_scanlines loop), any additional passes
-will occur inside jpeg_finish_compress or jpeg_start_decompress; those
-routines may take a long time to execute, and you don't get control back
-until they are done.
-
-You can define a progress-monitor routine which will be called periodically
-by the library.  No guarantees are made about how often this call will occur,
-so we don't recommend you use it for mouse tracking or anything like that.
-At present, a call will occur once per MCU row, scanline, or sample row
-group, whichever unit is convenient for the current processing mode; so the
-wider the image, the longer the time between calls.  During the data
-transferring pass, only one call occurs per call of jpeg_read_scanlines or
-jpeg_write_scanlines, so don't pass a large number of scanlines at once if
-you want fine resolution in the progress count.  (If you really need to use
-the callback mechanism for time-critical tasks like mouse tracking, you could
-insert additional calls inside some of the library's inner loops.)
-
-To establish a progress-monitor callback, create a struct jpeg_progress_mgr,
-fill in its progress_monitor field with a pointer to your callback routine,
-and set cinfo->progress to point to the struct.  The callback will be called
-whenever cinfo->progress is non-NULL.  (This pointer is set to NULL by
-jpeg_create_compress or jpeg_create_decompress; the library will not change
-it thereafter.  So if you allocate dynamic storage for the progress struct,
-make sure it will live as long as the JPEG object does.  Allocating from the
-JPEG memory manager with lifetime JPOOL_PERMANENT will work nicely.)  You
-can use the same callback routine for both compression and decompression.
-
-The jpeg_progress_mgr struct contains four fields which are set by the library:
-	long pass_counter;	/* work units completed in this pass */
-	long pass_limit;	/* total number of work units in this pass */
-	int completed_passes;	/* passes completed so far */
-	int total_passes;	/* total number of passes expected */
-During any one pass, pass_counter increases from 0 up to (not including)
-pass_limit; the step size is usually but not necessarily 1.  The pass_limit
-value may change from one pass to another.  The expected total number of
-passes is in total_passes, and the number of passes already completed is in
-completed_passes.  Thus the fraction of work completed may be estimated as
-		completed_passes + (pass_counter/pass_limit)
-		--------------------------------------------
-				total_passes
-ignoring the fact that the passes may not be equal amounts of work.
-
-When decompressing, pass_limit can even change within a pass, because it
-depends on the number of scans in the JPEG file, which isn't always known in
-advance.  The computed fraction-of-work-done may jump suddenly (if the library
-discovers it has overestimated the number of scans) or even decrease (in the
-opposite case).  It is not wise to put great faith in the work estimate.
-
-When using the decompressor's buffered-image mode, the progress monitor work
-estimate is likely to be completely unhelpful, because the library has no way
-to know how many output passes will be demanded of it.  Currently, the library
-sets total_passes based on the assumption that there will be one more output
-pass if the input file end hasn't yet been read (jpeg_input_complete() isn't
-TRUE), but no more output passes if the file end has been reached when the
-output pass is started.  This means that total_passes will rise as additional
-output passes are requested.  If you have a way of determining the input file
-size, estimating progress based on the fraction of the file that's been read
-will probably be more useful than using the library's value.
-
-
-Memory management
------------------
-
-This section covers some key facts about the JPEG library's built-in memory
-manager.  For more info, please read structure.doc's section about the memory
-manager, and consult the source code if necessary.
-
-All memory and temporary file allocation within the library is done via the
-memory manager.  If necessary, you can replace the "back end" of the memory
-manager to control allocation yourself (for example, if you don't want the
-library to use malloc() and free() for some reason).
-
-Some data is allocated "permanently" and will not be freed until the JPEG
-object is destroyed.  Most data is allocated "per image" and is freed by
-jpeg_finish_compress, jpeg_finish_decompress, or jpeg_abort.  You can call the
-memory manager yourself to allocate structures that will automatically be
-freed at these times.  Typical code for this is
-  ptr = (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, size);
-Use JPOOL_PERMANENT to get storage that lasts as long as the JPEG object.
-Use alloc_large instead of alloc_small for anything bigger than a few Kbytes.
-There are also alloc_sarray and alloc_barray routines that automatically
-build 2-D sample or block arrays.
-
-The library's minimum space requirements to process an image depend on the
-image's width, but not on its height, because the library ordinarily works
-with "strip" buffers that are as wide as the image but just a few rows high.
-Some operating modes (eg, two-pass color quantization) require full-image
-buffers.  Such buffers are treated as "virtual arrays": only the current strip
-need be in memory, and the rest can be swapped out to a temporary file.
-
-If you use the simplest memory manager back end (jmemnobs.c), then no
-temporary files are used; virtual arrays are simply malloc()'d.  Images bigger
-than memory can be processed only if your system supports virtual memory.
-The other memory manager back ends support temporary files of various flavors
-and thus work in machines without virtual memory.  They may also be useful on
-Unix machines if you need to process images that exceed available swap space.
-
-When using temporary files, the library will make the in-memory buffers for
-its virtual arrays just big enough to stay within a "maximum memory" setting.
-Your application can set this limit by setting cinfo->mem->max_memory_to_use
-after creating the JPEG object.  (Of course, there is still a minimum size for
-the buffers, so the max-memory setting is effective only if it is bigger than
-the minimum space needed.)  If you allocate any large structures yourself, you
-must allocate them before jpeg_start_compress() or jpeg_start_decompress() in
-order to have them counted against the max memory limit.  Also keep in mind
-that space allocated with alloc_small() is ignored, on the assumption that
-it's too small to be worth worrying about; so a reasonable safety margin
-should be left when setting max_memory_to_use.
-
-If you use the jmemname.c or jmemdos.c memory manager back end, it is
-important to clean up the JPEG object properly to ensure that the temporary
-files get deleted.  (This is especially crucial with jmemdos.c, where the
-"temporary files" may be extended-memory segments; if they are not freed,
-DOS will require a reboot to recover the memory.)  Thus, with these memory
-managers, it's a good idea to provide a signal handler that will trap any
-early exit from your program.  The handler should call either jpeg_abort()
-or jpeg_destroy() for any active JPEG objects.  A handler is not needed with
-jmemnobs.c, and shouldn't be necessary with jmemansi.c or jmemmac.c either,
-since the C library is supposed to take care of deleting files made with
-tmpfile().
-
-
-Memory usage
-------------
-
-Working memory requirements while performing compression or decompression
-depend on image dimensions, image characteristics (such as colorspace and
-JPEG process), and operating mode (application-selected options).
-
-As of v6b, the decompressor requires:
- 1. About 24K in more-or-less-fixed-size data.  This varies a bit depending
-    on operating mode and image characteristics (particularly color vs.
-    grayscale), but it doesn't depend on image dimensions.
- 2. Strip buffers (of size proportional to the image width) for IDCT and
-    upsampling results.  The worst case for commonly used sampling factors
-    is about 34 bytes * width in pixels for a color image.  A grayscale image
-    only needs about 8 bytes per pixel column.
- 3. A full-image DCT coefficient buffer is needed to decode a multi-scan JPEG
-    file (including progressive JPEGs), or whenever you select buffered-image
-    mode.  This takes 2 bytes/coefficient.  At typical 2x2 sampling, that's
-    3 bytes per pixel for a color image.  Worst case (1x1 sampling) requires
-    6 bytes/pixel.  For grayscale, figure 2 bytes/pixel.
- 4. To perform 2-pass color quantization, the decompressor also needs a
-    128K color lookup table and a full-image pixel buffer (3 bytes/pixel).
-This does not count any memory allocated by the application, such as a
-buffer to hold the final output image.
-
-The above figures are valid for 8-bit JPEG data precision and a machine with
-32-bit ints.  For 12-bit JPEG data, double the size of the strip buffers and
-quantization pixel buffer.  The "fixed-size" data will be somewhat smaller
-with 16-bit ints, larger with 64-bit ints.  Also, CMYK or other unusual
-color spaces will require different amounts of space.
-
-The full-image coefficient and pixel buffers, if needed at all, do not
-have to be fully RAM resident; you can have the library use temporary
-files instead when the total memory usage would exceed a limit you set.
-(But if your OS supports virtual memory, it's probably better to just use
-jmemnobs and let the OS do the swapping.)
-
-The compressor's memory requirements are similar, except that it has no need
-for color quantization.  Also, it needs a full-image DCT coefficient buffer
-if Huffman-table optimization is asked for, even if progressive mode is not
-requested.
-
-If you need more detailed information about memory usage in a particular
-situation, you can enable the MEM_STATS code in jmemmgr.c.
-
-
-Library compile-time options
-----------------------------
-
-A number of compile-time options are available by modifying jmorecfg.h.
-
-The JPEG standard provides for both the baseline 8-bit DCT process and
-a 12-bit DCT process.  The IJG code supports 12-bit lossy JPEG if you define
-BITS_IN_JSAMPLE as 12 rather than 8.  Note that this causes JSAMPLE to be
-larger than a char, so it affects the surrounding application's image data.
-The sample applications cjpeg and djpeg can support 12-bit mode only for PPM
-and GIF file formats; you must disable the other file formats to compile a
-12-bit cjpeg or djpeg.  (install.doc has more information about that.)
-At present, a 12-bit library can handle *only* 12-bit images, not both
-precisions.  (If you need to include both 8- and 12-bit libraries in a single
-application, you could probably do it by defining NEED_SHORT_EXTERNAL_NAMES
-for just one of the copies.  You'd have to access the 8-bit and 12-bit copies
-from separate application source files.  This is untested ... if you try it,
-we'd like to hear whether it works!)
-
-Note that a 12-bit library always compresses in Huffman optimization mode,
-in order to generate valid Huffman tables.  This is necessary because our
-default Huffman tables only cover 8-bit data.  If you need to output 12-bit
-files in one pass, you'll have to supply suitable default Huffman tables.
-You may also want to supply your own DCT quantization tables; the existing
-quality-scaling code has been developed for 8-bit use, and probably doesn't
-generate especially good tables for 12-bit.
-
-The maximum number of components (color channels) in the image is determined
-by MAX_COMPONENTS.  The JPEG standard allows up to 255 components, but we
-expect that few applications will need more than four or so.
-
-On machines with unusual data type sizes, you may be able to improve
-performance or reduce memory space by tweaking the various typedefs in
-jmorecfg.h.  In particular, on some RISC CPUs, access to arrays of "short"s
-is quite slow; consider trading memory for speed by making JCOEF, INT16, and
-UINT16 be "int" or "unsigned int".  UINT8 is also a candidate to become int.
-You probably don't want to make JSAMPLE be int unless you have lots of memory
-to burn.
-
-You can reduce the size of the library by compiling out various optional
-functions.  To do this, undefine xxx_SUPPORTED symbols as necessary.
-
-You can also save a few K by not having text error messages in the library;
-the standard error message table occupies about 5Kb.  This is particularly
-reasonable for embedded applications where there's no good way to display 
-a message anyway.  To do this, remove the creation of the message table
-(jpeg_std_message_table[]) from jerror.c, and alter format_message to do
-something reasonable without it.  You could output the numeric value of the
-message code number, for example.  If you do this, you can also save a couple
-more K by modifying the TRACEMSn() macros in jerror.h to expand to nothing;
-you don't need trace capability anyway, right?
-
-
-Portability considerations
---------------------------
-
-The JPEG library has been written to be extremely portable; the sample
-applications cjpeg and djpeg are slightly less so.  This section summarizes
-the design goals in this area.  (If you encounter any bugs that cause the
-library to be less portable than is claimed here, we'd appreciate hearing
-about them.)
-
-The code works fine on ANSI C, C++, and pre-ANSI C compilers, using any of
-the popular system include file setups, and some not-so-popular ones too.
-See install.doc for configuration procedures.
-
-The code is not dependent on the exact sizes of the C data types.  As
-distributed, we make the assumptions that
-	char	is at least 8 bits wide
-	short	is at least 16 bits wide
-	int	is at least 16 bits wide
-	long	is at least 32 bits wide
-(These are the minimum requirements of the ANSI C standard.)  Wider types will
-work fine, although memory may be used inefficiently if char is much larger
-than 8 bits or short is much bigger than 16 bits.  The code should work
-equally well with 16- or 32-bit ints.
-
-In a system where these assumptions are not met, you may be able to make the
-code work by modifying the typedefs in jmorecfg.h.  However, you will probably
-have difficulty if int is less than 16 bits wide, since references to plain
-int abound in the code.
-
-char can be either signed or unsigned, although the code runs faster if an
-unsigned char type is available.  If char is wider than 8 bits, you will need
-to redefine JOCTET and/or provide custom data source/destination managers so
-that JOCTET represents exactly 8 bits of data on external storage.
-
-The JPEG library proper does not assume ASCII representation of characters.
-But some of the image file I/O modules in cjpeg/djpeg do have ASCII
-dependencies in file-header manipulation; so does cjpeg's select_file_type()
-routine.
-
-The JPEG library does not rely heavily on the C library.  In particular, C
-stdio is used only by the data source/destination modules and the error
-handler, all of which are application-replaceable.  (cjpeg/djpeg are more
-heavily dependent on stdio.)  malloc and free are called only from the memory
-manager "back end" module, so you can use a different memory allocator by
-replacing that one file.
-
-The code generally assumes that C names must be unique in the first 15
-characters.  However, global function names can be made unique in the
-first 6 characters by defining NEED_SHORT_EXTERNAL_NAMES.
-
-More info about porting the code may be gleaned by reading jconfig.doc,
-jmorecfg.h, and jinclude.h.
-
-
-Notes for MS-DOS implementors
------------------------------
-
-The IJG code is designed to work efficiently in 80x86 "small" or "medium"
-memory models (i.e., data pointers are 16 bits unless explicitly declared
-"far"; code pointers can be either size).  You may be able to use small
-model to compile cjpeg or djpeg by itself, but you will probably have to use
-medium model for any larger application.  This won't make much difference in
-performance.  You *will* take a noticeable performance hit if you use a
-large-data memory model (perhaps 10%-25%), and you should avoid "huge" model
-if at all possible.
-
-The JPEG library typically needs 2Kb-3Kb of stack space.  It will also
-malloc about 20K-30K of near heap space while executing (and lots of far
-heap, but that doesn't count in this calculation).  This figure will vary
-depending on selected operating mode, and to a lesser extent on image size.
-There is also about 5Kb-6Kb of constant data which will be allocated in the
-near data segment (about 4Kb of this is the error message table).
-Thus you have perhaps 20K available for other modules' static data and near
-heap space before you need to go to a larger memory model.  The C library's
-static data will account for several K of this, but that still leaves a good
-deal for your needs.  (If you are tight on space, you could reduce the sizes
-of the I/O buffers allocated by jdatasrc.c and jdatadst.c, say from 4K to
-1K.  Another possibility is to move the error message table to far memory;
-this should be doable with only localized hacking on jerror.c.)
-
-About 2K of the near heap space is "permanent" memory that will not be
-released until you destroy the JPEG object.  This is only an issue if you
-save a JPEG object between compression or decompression operations.
-
-Far data space may also be a tight resource when you are dealing with large
-images.  The most memory-intensive case is decompression with two-pass color
-quantization, or single-pass quantization to an externally supplied color
-map.  This requires a 128Kb color lookup table plus strip buffers amounting
-to about 40 bytes per column for typical sampling ratios (eg, about 25600
-bytes for a 640-pixel-wide image).  You may not be able to process wide
-images if you have large data structures of your own.
-
-Of course, all of these concerns vanish if you use a 32-bit flat-memory-model
-compiler, such as DJGPP or Watcom C.  We highly recommend flat model if you
-can use it; the JPEG library is significantly faster in flat model.
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/rdbmp.c ./Shared/jpeg-6b/rdbmp.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/rdbmp.c	Mon Dec  1 12:30:40 2003
+++ ./Shared/jpeg-6b/rdbmp.c	Wed Dec 31 19:00:00 1969
@@ -1,439 +0,0 @@
-/*
- * rdbmp.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to read input images in Microsoft "BMP"
- * format (MS Windows 3.x, OS/2 1.x, and OS/2 2.x flavors).
- * Currently, only 8-bit and 24-bit images are supported, not 1-bit or
- * 4-bit (feeding such low-depth images into JPEG would be silly anyway).
- * Also, we don't support RLE-compressed files.
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume input from
- * an ordinary stdio stream.  They further assume that reading begins
- * at the start of the file; start_input may need work if the
- * user interface has already read some data (e.g., to determine that
- * the file is indeed BMP format).
- *
- * This code contributed by James Arthur Boucher.
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef BMP_SUPPORTED
-
-
-/* Macros to deal with unsigned chars as efficiently as compiler allows */
-
-#ifdef HAVE_UNSIGNED_CHAR
-typedef unsigned char U_CHAR;
-#define UCH(x)	((int) (x))
-#else /* !HAVE_UNSIGNED_CHAR */
-#ifdef CHAR_IS_UNSIGNED
-typedef char U_CHAR;
-#define UCH(x)	((int) (x))
-#else
-typedef char U_CHAR;
-#define UCH(x)	((int) (x) & 0xFF)
-#endif
-#endif /* HAVE_UNSIGNED_CHAR */
-
-
-#define	ReadOK(file,buffer,len)	(JFREAD(file,buffer,len) == ((size_t) (len)))
-
-
-/* Private version of data source object */
-
-typedef struct _bmp_source_struct * bmp_source_ptr;
-
-typedef struct _bmp_source_struct {
-  struct cjpeg_source_struct pub; /* public fields */
-
-  j_compress_ptr cinfo;		/* back link saves passing separate parm */
-
-  JSAMPARRAY colormap;		/* BMP colormap (converted to my format) */
-
-  jvirt_sarray_ptr whole_image;	/* Needed to reverse row order */
-  JDIMENSION source_row;	/* Current source row number */
-  JDIMENSION row_width;		/* Physical width of scanlines in file */
-
-  int bits_per_pixel;		/* remembers 8- or 24-bit format */
-} bmp_source_struct;
-
-
-LOCAL(int)
-read_byte (bmp_source_ptr sinfo)
-/* Read next byte from BMP file */
-{
-  register FILE *infile = sinfo->pub.input_file;
-  register int c;
-
-  if ((c = getc(infile)) == EOF)
-    ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
-  return c;
-}
-
-
-LOCAL(void)
-read_colormap (bmp_source_ptr sinfo, int cmaplen, int mapentrysize)
-/* Read the colormap from a BMP file */
-{
-  int i;
-
-  switch (mapentrysize) {
-  case 3:
-    /* BGR format (occurs in OS/2 files) */
-    for (i = 0; i < cmaplen; i++) {
-      sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
-      sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
-      sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
-    }
-    break;
-  case 4:
-    /* BGR0 format (occurs in MS Windows files) */
-    for (i = 0; i < cmaplen; i++) {
-      sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
-      sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
-      sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
-      (void) read_byte(sinfo);
-    }
-    break;
-  default:
-    ERREXIT(sinfo->cinfo, JERR_BMP_BADCMAP);
-    break;
-  }
-}
-
-
-/*
- * Read one row of pixels.
- * The image has been read into the whole_image array, but is otherwise
- * unprocessed.  We must read it out in top-to-bottom row order, and if
- * it is an 8-bit image, we must expand colormapped pixels to 24bit format.
- */
-
-METHODDEF(JDIMENSION)
-get_8bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading 8-bit colormap indexes */
-{
-  bmp_source_ptr source = (bmp_source_ptr) sinfo;
-  register JSAMPARRAY colormap = source->colormap;
-  JSAMPARRAY image_ptr;
-  register int t;
-  register JSAMPROW inptr, outptr;
-  register JDIMENSION col;
-
-  /* Fetch next row from virtual array */
-  source->source_row--;
-  image_ptr = (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, source->whole_image,
-     source->source_row, (JDIMENSION) 1, FALSE);
-
-  /* Expand the colormap indexes to real data */
-  inptr = image_ptr[0];
-  outptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    t = GETJSAMPLE(*inptr++);
-    *outptr++ = colormap[0][t];	/* can omit GETJSAMPLE() safely */
-    *outptr++ = colormap[1][t];
-    *outptr++ = colormap[2][t];
-  }
-
-  return 1;
-}
-
-
-METHODDEF(JDIMENSION)
-get_24bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading 24-bit pixels */
-{
-  bmp_source_ptr source = (bmp_source_ptr) sinfo;
-  JSAMPARRAY image_ptr;
-  register JSAMPROW inptr, outptr;
-  register JDIMENSION col;
-
-  /* Fetch next row from virtual array */
-  source->source_row--;
-  image_ptr = (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, source->whole_image,
-     source->source_row, (JDIMENSION) 1, FALSE);
-
-  /* Transfer data.  Note source values are in BGR order
-   * (even though Microsoft's own documents say the opposite).
-   */
-  inptr = image_ptr[0];
-  outptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    outptr[2] = *inptr++;	/* can omit GETJSAMPLE() safely */
-    outptr[1] = *inptr++;
-    outptr[0] = *inptr++;
-    outptr += 3;
-  }
-
-  return 1;
-}
-
-
-/*
- * This method loads the image into whole_image during the first call on
- * get_pixel_rows.  The get_pixel_rows pointer is then adjusted to call
- * get_8bit_row or get_24bit_row on subsequent calls.
- */
-
-METHODDEF(JDIMENSION)
-preload_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  bmp_source_ptr source = (bmp_source_ptr) sinfo;
-  register FILE *infile = source->pub.input_file;
-  register int c;
-  register JSAMPROW out_ptr;
-  JSAMPARRAY image_ptr;
-  JDIMENSION row, col;
-  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-
-  /* Read the data into a virtual array in input-file row order. */
-  for (row = 0; row < cinfo->image_height; row++) {
-    if (progress != NULL) {
-      progress->pub.pass_counter = (long) row;
-      progress->pub.pass_limit = (long) cinfo->image_height;
-      (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-    }
-    image_ptr = (*cinfo->mem->access_virt_sarray)
-      ((j_common_ptr) cinfo, source->whole_image,
-       row, (JDIMENSION) 1, TRUE);
-    out_ptr = image_ptr[0];
-    for (col = source->row_width; col > 0; col--) {
-      /* inline copy of read_byte() for speed */
-      if ((c = getc(infile)) == EOF)
-	ERREXIT(cinfo, JERR_INPUT_EOF);
-      *out_ptr++ = (JSAMPLE) c;
-    }
-  }
-  if (progress != NULL)
-    progress->completed_extra_passes++;
-
-  /* Set up to read from the virtual array in top-to-bottom order */
-  switch (source->bits_per_pixel) {
-  case 8:
-    source->pub.get_pixel_rows = get_8bit_row;
-    break;
-  case 24:
-    source->pub.get_pixel_rows = get_24bit_row;
-    break;
-  default:
-    ERREXIT(cinfo, JERR_BMP_BADDEPTH);
-  }
-  source->source_row = cinfo->image_height;
-
-  /* And read the first row */
-  return (*source->pub.get_pixel_rows) (cinfo, sinfo);
-}
-
-
-/*
- * Read the file header; return image size and component count.
- */
-
-METHODDEF(void)
-start_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  bmp_source_ptr source = (bmp_source_ptr) sinfo;
-  U_CHAR bmpfileheader[14];
-  U_CHAR bmpinfoheader[64];
-#define GET_2B(array,offset)  ((unsigned int) UCH(array[offset]) + \
-			       (((unsigned int) UCH(array[offset+1])) << 8))
-#define GET_4B(array,offset)  ((INT32) UCH(array[offset]) + \
-			       (((INT32) UCH(array[offset+1])) << 8) + \
-			       (((INT32) UCH(array[offset+2])) << 16) + \
-			       (((INT32) UCH(array[offset+3])) << 24))
-  INT32 bfOffBits;
-  INT32 headerSize;
-  INT32 biWidth = 0;		/* initialize to avoid compiler warning */
-  INT32 biHeight = 0;
-  unsigned int biPlanes;
-  INT32 biCompression;
-  INT32 biXPelsPerMeter,biYPelsPerMeter;
-  INT32 biClrUsed = 0;
-  int mapentrysize = 0;		/* 0 indicates no colormap */
-  INT32 bPad;
-  JDIMENSION row_width;
-
-  /* Read and verify the bitmap file header */
-  if (! ReadOK(source->pub.input_file, bmpfileheader, 14))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-  if (GET_2B(bmpfileheader,0) != 0x4D42) /* 'BM' */
-    ERREXIT(cinfo, JERR_BMP_NOT);
-  bfOffBits = (INT32) GET_4B(bmpfileheader,10);
-  /* We ignore the remaining fileheader fields */
-
-  /* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows),
-   * or 64 bytes (OS/2 2.x).  Check the first 4 bytes to find out which.
-   */
-  if (! ReadOK(source->pub.input_file, bmpinfoheader, 4))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-  headerSize = (INT32) GET_4B(bmpinfoheader,0);
-  if (headerSize < 12 || headerSize > 64)
-    ERREXIT(cinfo, JERR_BMP_BADHEADER);
-  if (! ReadOK(source->pub.input_file, bmpinfoheader+4, headerSize-4))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-
-  switch ((int) headerSize) {
-  case 12:
-    /* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */
-    biWidth = (INT32) GET_2B(bmpinfoheader,4);
-    biHeight = (INT32) GET_2B(bmpinfoheader,6);
-    biPlanes = GET_2B(bmpinfoheader,8);
-    source->bits_per_pixel = (int) GET_2B(bmpinfoheader,10);
-
-    switch (source->bits_per_pixel) {
-    case 8:			/* colormapped image */
-      mapentrysize = 3;		/* OS/2 uses RGBTRIPLE colormap */
-      TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, (int) biWidth, (int) biHeight);
-      break;
-    case 24:			/* RGB image */
-      TRACEMS2(cinfo, 1, JTRC_BMP_OS2, (int) biWidth, (int) biHeight);
-      break;
-    default:
-      ERREXIT(cinfo, JERR_BMP_BADDEPTH);
-      break;
-    }
-    if (biPlanes != 1)
-      ERREXIT(cinfo, JERR_BMP_BADPLANES);
-    break;
-  case 40:
-  case 64:
-    /* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */
-    /* or OS/2 2.x header, which has additional fields that we ignore */
-    biWidth = GET_4B(bmpinfoheader,4);
-    biHeight = GET_4B(bmpinfoheader,8);
-    biPlanes = GET_2B(bmpinfoheader,12);
-    source->bits_per_pixel = (int) GET_2B(bmpinfoheader,14);
-    biCompression = GET_4B(bmpinfoheader,16);
-    biXPelsPerMeter = GET_4B(bmpinfoheader,24);
-    biYPelsPerMeter = GET_4B(bmpinfoheader,28);
-    biClrUsed = GET_4B(bmpinfoheader,32);
-    /* biSizeImage, biClrImportant fields are ignored */
-
-    switch (source->bits_per_pixel) {
-    case 8:			/* colormapped image */
-      mapentrysize = 4;		/* Windows uses RGBQUAD colormap */
-      TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, (int) biWidth, (int) biHeight);
-      break;
-    case 24:			/* RGB image */
-      TRACEMS2(cinfo, 1, JTRC_BMP, (int) biWidth, (int) biHeight);
-      break;
-    default:
-      ERREXIT(cinfo, JERR_BMP_BADDEPTH);
-      break;
-    }
-    if (biPlanes != 1)
-      ERREXIT(cinfo, JERR_BMP_BADPLANES);
-    if (biCompression != 0)
-      ERREXIT(cinfo, JERR_BMP_COMPRESSED);
-
-    if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) {
-      /* Set JFIF density parameters from the BMP data */
-      cinfo->X_density = (UINT16) (biXPelsPerMeter/100); /* 100 cm per meter */
-      cinfo->Y_density = (UINT16) (biYPelsPerMeter/100);
-      cinfo->density_unit = 2;	/* dots/cm */
-    }
-    break;
-  default:
-    ERREXIT(cinfo, JERR_BMP_BADHEADER);
-    break;
-  }
-
-  /* Compute distance to bitmap data --- will adjust for colormap below */
-  bPad = bfOffBits - (headerSize + 14);
-
-  /* Read the colormap, if any */
-  if (mapentrysize > 0) {
-    if (biClrUsed <= 0)
-      biClrUsed = 256;		/* assume it's 256 */
-    else if (biClrUsed > 256)
-      ERREXIT(cinfo, JERR_BMP_BADCMAP);
-    /* Allocate space to store the colormap */
-    source->colormap = (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       (JDIMENSION) biClrUsed, (JDIMENSION) 3);
-    /* and read it from the file */
-    read_colormap(source, (int) biClrUsed, mapentrysize);
-    /* account for size of colormap */
-    bPad -= biClrUsed * mapentrysize;
-  }
-
-  /* Skip any remaining pad bytes */
-  if (bPad < 0)			/* incorrect bfOffBits value? */
-    ERREXIT(cinfo, JERR_BMP_BADHEADER);
-  while (--bPad >= 0) {
-    (void) read_byte(source);
-  }
-
-  /* Compute row width in file, including padding to 4-byte boundary */
-  if (source->bits_per_pixel == 24)
-    row_width = (JDIMENSION) (biWidth * 3);
-  else
-    row_width = (JDIMENSION) biWidth;
-  while ((row_width & 3) != 0) row_width++;
-  source->row_width = row_width;
-
-  /* Allocate space for inversion array, prepare for preload pass */
-  source->whole_image = (*cinfo->mem->request_virt_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-     row_width, (JDIMENSION) biHeight, (JDIMENSION) 1);
-  source->pub.get_pixel_rows = preload_image;
-  if (cinfo->progress != NULL) {
-    cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-    progress->total_extra_passes++; /* count file input as separate pass */
-  }
-
-  /* Allocate one-row buffer for returned data */
-  source->pub.buffer = (*cinfo->mem->alloc_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE,
-     (JDIMENSION) (biWidth * 3), (JDIMENSION) 1);
-  source->pub.buffer_height = 1;
-
-  cinfo->in_color_space = JCS_RGB;
-  cinfo->input_components = 3;
-  cinfo->data_precision = 8;
-  cinfo->image_width = (JDIMENSION) biWidth;
-  cinfo->image_height = (JDIMENSION) biHeight;
-}
-
-
-/*
- * Finish up at the end of the file.
- */
-
-METHODDEF(void)
-finish_input_bmp (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  /* no work */
-}
-
-
-/*
- * The module selection routine for BMP format input.
- */
-
-GLOBAL(cjpeg_source_ptr)
-jinit_read_bmp (j_compress_ptr cinfo)
-{
-  bmp_source_ptr source;
-
-  /* Create module interface object */
-  source = (bmp_source_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(bmp_source_struct));
-  source->cinfo = cinfo;	/* make back link for subroutines */
-  /* Fill in method ptrs, except get_pixel_rows which start_input sets */
-  source->pub.start_input = start_input_bmp;
-  source->pub.finish_input = finish_input_bmp;
-
-  return (cjpeg_source_ptr) source;
-}
-
-#endif /* BMP_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/rdgif.c ./Shared/jpeg-6b/rdgif.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/rdgif.c	Mon Dec  1 12:30:40 2003
+++ ./Shared/jpeg-6b/rdgif.c	Wed Dec 31 19:00:00 1969
@@ -1,38 +0,0 @@
-/*
- * rdgif.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to read input images in GIF format.
- *
- *****************************************************************************
- * NOTE: to avoid entanglements with Unisys' patent on LZW compression,      *
- * the ability to read GIF files has been removed from the IJG distribution. *
- * Sorry about that.                                                         *
- *****************************************************************************
- *
- * We are required to state that
- *    "The Graphics Interchange Format(c) is the Copyright property of
- *    CompuServe Incorporated. GIF(sm) is a Service Mark property of
- *    CompuServe Incorporated."
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef GIF_SUPPORTED
-
-/*
- * The module selection routine for GIF format input.
- */
-
-GLOBAL(cjpeg_source_ptr)
-jinit_read_gif (j_compress_ptr cinfo)
-{
-  fprintf(stderr, "GIF input is unsupported for legal reasons.  Sorry.\n");
-  exit(EXIT_FAILURE);
-  return NULL;			/* keep compiler happy */
-}
-
-#endif /* GIF_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/rdppm.c ./Shared/jpeg-6b/rdppm.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/rdppm.c	Mon Dec  1 12:30:40 2003
+++ ./Shared/jpeg-6b/rdppm.c	Wed Dec 31 19:00:00 1969
@@ -1,458 +0,0 @@
-/*
- * rdppm.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to read input images in PPM/PGM format.
- * The extended 2-byte-per-sample raw PPM/PGM formats are supported.
- * The PBMPLUS library is NOT required to compile this software
- * (but it is highly useful as a set of PPM image manipulation programs).
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume input from
- * an ordinary stdio stream.  They further assume that reading begins
- * at the start of the file; start_input may need work if the
- * user interface has already read some data (e.g., to determine that
- * the file is indeed PPM format).
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef PPM_SUPPORTED
-
-
-/* Portions of this code are based on the PBMPLUS library, which is:
-**
-** Copyright (C) 1988 by Jef Poskanzer.
-**
-** Permission to use, copy, modify, and distribute this software and its
-** documentation for any purpose and without fee is hereby granted, provided
-** that the above copyright notice appear in all copies and that both that
-** copyright notice and this permission notice appear in supporting
-** documentation.  This software is provided "as is" without express or
-** implied warranty.
-*/
-
-
-/* Macros to deal with unsigned chars as efficiently as compiler allows */
-
-#ifdef HAVE_UNSIGNED_CHAR
-typedef unsigned char U_CHAR;
-#define UCH(x)	((int) (x))
-#else /* !HAVE_UNSIGNED_CHAR */
-#ifdef CHAR_IS_UNSIGNED
-typedef char U_CHAR;
-#define UCH(x)	((int) (x))
-#else
-typedef char U_CHAR;
-#define UCH(x)	((int) (x) & 0xFF)
-#endif
-#endif /* HAVE_UNSIGNED_CHAR */
-
-
-#define	ReadOK(file,buffer,len)	(JFREAD(file,buffer,len) == ((size_t) (len)))
-
-
-/*
- * On most systems, reading individual bytes with getc() is drastically less
- * efficient than buffering a row at a time with fread().  On PCs, we must
- * allocate the buffer in near data space, because we are assuming small-data
- * memory model, wherein fread() can't reach far memory.  If you need to
- * process very wide images on a PC, you might have to compile in large-memory
- * model, or else replace fread() with a getc() loop --- which will be much
- * slower.
- */
-
-
-/* Private version of data source object */
-
-typedef struct {
-  struct cjpeg_source_struct pub; /* public fields */
-
-  U_CHAR *iobuffer;		/* non-FAR pointer to I/O buffer */
-  JSAMPROW pixrow;		/* FAR pointer to same */
-  size_t buffer_width;		/* width of I/O buffer */
-  JSAMPLE *rescale;		/* => maxval-remapping array, or NULL */
-} ppm_source_struct;
-
-typedef ppm_source_struct * ppm_source_ptr;
-
-
-LOCAL(int)
-pbm_getc (FILE * infile)
-/* Read next char, skipping over any comments */
-/* A comment/newline sequence is returned as a newline */
-{
-  register int ch;
-
-  ch = getc(infile);
-  if (ch == '#') {
-    do {
-      ch = getc(infile);
-    } while (ch != '\n' && ch != EOF);
-  }
-  return ch;
-}
-
-
-LOCAL(unsigned int)
-read_pbm_integer (j_compress_ptr cinfo, FILE * infile)
-/* Read an unsigned decimal integer from the PPM file */
-/* Swallows one trailing character after the integer */
-/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
-/* This should not be a problem in practice. */
-{
-  register int ch;
-  register unsigned int val;
-
-  /* Skip any leading whitespace */
-  do {
-    ch = pbm_getc(infile);
-    if (ch == EOF)
-      ERREXIT(cinfo, JERR_INPUT_EOF);
-  } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
-
-  if (ch < '0' || ch > '9')
-    ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
-
-  val = ch - '0';
-  while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
-    val *= 10;
-    val += ch - '0';
-  }
-  return val;
-}
-
-
-/*
- * Read one row of pixels.
- *
- * We provide several different versions depending on input file format.
- * In all cases, input is scaled to the size of JSAMPLE.
- *
- * A really fast path is provided for reading byte/sample raw files with
- * maxval = MAXJSAMPLE, which is the normal case for 8-bit data.
- */
-
-
-METHODDEF(JDIMENSION)
-get_text_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading text-format PGM files with any maxval */
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-  FILE * infile = source->pub.input_file;
-  register JSAMPROW ptr;
-  register JSAMPLE *rescale = source->rescale;
-  JDIMENSION col;
-
-  ptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
-  }
-  return 1;
-}
-
-
-METHODDEF(JDIMENSION)
-get_text_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading text-format PPM files with any maxval */
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-  FILE * infile = source->pub.input_file;
-  register JSAMPROW ptr;
-  register JSAMPLE *rescale = source->rescale;
-  JDIMENSION col;
-
-  ptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
-    *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
-    *ptr++ = rescale[read_pbm_integer(cinfo, infile)];
-  }
-  return 1;
-}
-
-
-METHODDEF(JDIMENSION)
-get_scaled_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading raw-byte-format PGM files with any maxval */
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-  register JSAMPROW ptr;
-  register U_CHAR * bufferptr;
-  register JSAMPLE *rescale = source->rescale;
-  JDIMENSION col;
-
-  if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-  ptr = source->pub.buffer[0];
-  bufferptr = source->iobuffer;
-  for (col = cinfo->image_width; col > 0; col--) {
-    *ptr++ = rescale[UCH(*bufferptr++)];
-  }
-  return 1;
-}
-
-
-METHODDEF(JDIMENSION)
-get_scaled_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading raw-byte-format PPM files with any maxval */
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-  register JSAMPROW ptr;
-  register U_CHAR * bufferptr;
-  register JSAMPLE *rescale = source->rescale;
-  JDIMENSION col;
-
-  if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-  ptr = source->pub.buffer[0];
-  bufferptr = source->iobuffer;
-  for (col = cinfo->image_width; col > 0; col--) {
-    *ptr++ = rescale[UCH(*bufferptr++)];
-    *ptr++ = rescale[UCH(*bufferptr++)];
-    *ptr++ = rescale[UCH(*bufferptr++)];
-  }
-  return 1;
-}
-
-
-METHODDEF(JDIMENSION)
-get_raw_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading raw-byte-format files with maxval = MAXJSAMPLE.
- * In this case we just read right into the JSAMPLE buffer!
- * Note that same code works for PPM and PGM files.
- */
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-
-  if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-  return 1;
-}
-
-
-METHODDEF(JDIMENSION)
-get_word_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading raw-word-format PGM files with any maxval */
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-  register JSAMPROW ptr;
-  register U_CHAR * bufferptr;
-  register JSAMPLE *rescale = source->rescale;
-  JDIMENSION col;
-
-  if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-  ptr = source->pub.buffer[0];
-  bufferptr = source->iobuffer;
-  for (col = cinfo->image_width; col > 0; col--) {
-    register int temp;
-    temp  = UCH(*bufferptr++);
-    temp |= UCH(*bufferptr++) << 8;
-    *ptr++ = rescale[temp];
-  }
-  return 1;
-}
-
-
-METHODDEF(JDIMENSION)
-get_word_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading raw-word-format PPM files with any maxval */
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-  register JSAMPROW ptr;
-  register U_CHAR * bufferptr;
-  register JSAMPLE *rescale = source->rescale;
-  JDIMENSION col;
-
-  if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-  ptr = source->pub.buffer[0];
-  bufferptr = source->iobuffer;
-  for (col = cinfo->image_width; col > 0; col--) {
-    register int temp;
-    temp  = UCH(*bufferptr++);
-    temp |= UCH(*bufferptr++) << 8;
-    *ptr++ = rescale[temp];
-    temp  = UCH(*bufferptr++);
-    temp |= UCH(*bufferptr++) << 8;
-    *ptr++ = rescale[temp];
-    temp  = UCH(*bufferptr++);
-    temp |= UCH(*bufferptr++) << 8;
-    *ptr++ = rescale[temp];
-  }
-  return 1;
-}
-
-
-/*
- * Read the file header; return image size and component count.
- */
-
-METHODDEF(void)
-start_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  ppm_source_ptr source = (ppm_source_ptr) sinfo;
-  int c;
-  unsigned int w, h, maxval;
-  boolean need_iobuffer, use_raw_buffer, need_rescale;
-
-  if (getc(source->pub.input_file) != 'P')
-    ERREXIT(cinfo, JERR_PPM_NOT);
-
-  c = getc(source->pub.input_file); /* subformat discriminator character */
-
-  /* detect unsupported variants (ie, PBM) before trying to read header */
-  switch (c) {
-  case '2':			/* it's a text-format PGM file */
-  case '3':			/* it's a text-format PPM file */
-  case '5':			/* it's a raw-format PGM file */
-  case '6':			/* it's a raw-format PPM file */
-    break;
-  default:
-    ERREXIT(cinfo, JERR_PPM_NOT);
-    break;
-  }
-
-  /* fetch the remaining header info */
-  w = read_pbm_integer(cinfo, source->pub.input_file);
-  h = read_pbm_integer(cinfo, source->pub.input_file);
-  maxval = read_pbm_integer(cinfo, source->pub.input_file);
-
-  if (w <= 0 || h <= 0 || maxval <= 0) /* error check */
-    ERREXIT(cinfo, JERR_PPM_NOT);
-
-  cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
-  cinfo->image_width = (JDIMENSION) w;
-  cinfo->image_height = (JDIMENSION) h;
-
-  /* initialize flags to most common settings */
-  need_iobuffer = TRUE;		/* do we need an I/O buffer? */
-  use_raw_buffer = FALSE;	/* do we map input buffer onto I/O buffer? */
-  need_rescale = TRUE;		/* do we need a rescale array? */
-
-  switch (c) {
-  case '2':			/* it's a text-format PGM file */
-    cinfo->input_components = 1;
-    cinfo->in_color_space = JCS_GRAYSCALE;
-    TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h);
-    source->pub.get_pixel_rows = get_text_gray_row;
-    need_iobuffer = FALSE;
-    break;
-
-  case '3':			/* it's a text-format PPM file */
-    cinfo->input_components = 3;
-    cinfo->in_color_space = JCS_RGB;
-    TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h);
-    source->pub.get_pixel_rows = get_text_rgb_row;
-    need_iobuffer = FALSE;
-    break;
-
-  case '5':			/* it's a raw-format PGM file */
-    cinfo->input_components = 1;
-    cinfo->in_color_space = JCS_GRAYSCALE;
-    TRACEMS2(cinfo, 1, JTRC_PGM, w, h);
-    if (maxval > 255) {
-      source->pub.get_pixel_rows = get_word_gray_row;
-    } else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) {
-      source->pub.get_pixel_rows = get_raw_row;
-      use_raw_buffer = TRUE;
-      need_rescale = FALSE;
-    } else {
-      source->pub.get_pixel_rows = get_scaled_gray_row;
-    }
-    break;
-
-  case '6':			/* it's a raw-format PPM file */
-    cinfo->input_components = 3;
-    cinfo->in_color_space = JCS_RGB;
-    TRACEMS2(cinfo, 1, JTRC_PPM, w, h);
-    if (maxval > 255) {
-      source->pub.get_pixel_rows = get_word_rgb_row;
-    } else if (maxval == MAXJSAMPLE && SIZEOF(JSAMPLE) == SIZEOF(U_CHAR)) {
-      source->pub.get_pixel_rows = get_raw_row;
-      use_raw_buffer = TRUE;
-      need_rescale = FALSE;
-    } else {
-      source->pub.get_pixel_rows = get_scaled_rgb_row;
-    }
-    break;
-  }
-
-  /* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */
-  if (need_iobuffer) {
-    source->buffer_width = (size_t) w * cinfo->input_components *
-      ((maxval<=255) ? SIZEOF(U_CHAR) : (2*SIZEOF(U_CHAR)));
-    source->iobuffer = (U_CHAR *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  source->buffer_width);
-  }
-
-  /* Create compressor input buffer. */
-  if (use_raw_buffer) {
-    /* For unscaled raw-input case, we can just map it onto the I/O buffer. */
-    /* Synthesize a JSAMPARRAY pointer structure */
-    /* Cast here implies near->far pointer conversion on PCs */
-    source->pixrow = (JSAMPROW) source->iobuffer;
-    source->pub.buffer = & source->pixrow;
-    source->pub.buffer_height = 1;
-  } else {
-    /* Need to translate anyway, so make a separate sample buffer. */
-    source->pub.buffer = (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       (JDIMENSION) w * cinfo->input_components, (JDIMENSION) 1);
-    source->pub.buffer_height = 1;
-  }
-
-  /* Compute the rescaling array if required. */
-  if (need_rescale) {
-    INT32 val, half_maxval;
-
-    /* On 16-bit-int machines we have to be careful of maxval = 65535 */
-    source->rescale = (JSAMPLE *)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  (size_t) (((long) maxval + 1L) * SIZEOF(JSAMPLE)));
-    half_maxval = maxval / 2;
-    for (val = 0; val <= (INT32) maxval; val++) {
-      /* The multiplication here must be done in 32 bits to avoid overflow */
-      source->rescale[val] = (JSAMPLE) ((val*MAXJSAMPLE + half_maxval)/maxval);
-    }
-  }
-}
-
-
-/*
- * Finish up at the end of the file.
- */
-
-METHODDEF(void)
-finish_input_ppm (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  /* no work */
-}
-
-
-/*
- * The module selection routine for PPM format input.
- */
-
-GLOBAL(cjpeg_source_ptr)
-jinit_read_ppm (j_compress_ptr cinfo)
-{
-  ppm_source_ptr source;
-
-  /* Create module interface object */
-  source = (ppm_source_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(ppm_source_struct));
-  /* Fill in method ptrs, except get_pixel_rows which start_input sets */
-  source->pub.start_input = start_input_ppm;
-  source->pub.finish_input = finish_input_ppm;
-
-  return (cjpeg_source_ptr) source;
-}
-
-#endif /* PPM_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/rdrle.c ./Shared/jpeg-6b/rdrle.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/rdrle.c	Mon Dec  1 12:30:40 2003
+++ ./Shared/jpeg-6b/rdrle.c	Wed Dec 31 19:00:00 1969
@@ -1,387 +0,0 @@
-/*
- * rdrle.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to read input images in Utah RLE format.
- * The Utah Raster Toolkit library is required (version 3.1 or later).
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume input from
- * an ordinary stdio stream.  They further assume that reading begins
- * at the start of the file; start_input may need work if the
- * user interface has already read some data (e.g., to determine that
- * the file is indeed RLE format).
- *
- * Based on code contributed by Mike Lijewski,
- * with updates from Robert Hutchinson.
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef RLE_SUPPORTED
-
-/* rle.h is provided by the Utah Raster Toolkit. */
-
-#include <rle.h>
-
-/*
- * We assume that JSAMPLE has the same representation as rle_pixel,
- * to wit, "unsigned char".  Hence we can't cope with 12- or 16-bit samples.
- */
-
-#if BITS_IN_JSAMPLE != 8
-  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
-#endif
-
-/*
- * We support the following types of RLE files:
- *   
- *   GRAYSCALE   - 8 bits, no colormap
- *   MAPPEDGRAY  - 8 bits, 1 channel colomap
- *   PSEUDOCOLOR - 8 bits, 3 channel colormap
- *   TRUECOLOR   - 24 bits, 3 channel colormap
- *   DIRECTCOLOR - 24 bits, no colormap
- *
- * For now, we ignore any alpha channel in the image.
- */
-
-typedef enum
-  { GRAYSCALE, MAPPEDGRAY, PSEUDOCOLOR, TRUECOLOR, DIRECTCOLOR } rle_kind;
-
-
-/*
- * Since RLE stores scanlines bottom-to-top, we have to invert the image
- * to conform to JPEG's top-to-bottom order.  To do this, we read the
- * incoming image into a virtual array on the first get_pixel_rows call,
- * then fetch the required row from the virtual array on subsequent calls.
- */
-
-typedef struct _rle_source_struct * rle_source_ptr;
-
-typedef struct _rle_source_struct {
-  struct cjpeg_source_struct pub; /* public fields */
-
-  rle_kind visual;              /* actual type of input file */
-  jvirt_sarray_ptr image;       /* virtual array to hold the image */
-  JDIMENSION row;		/* current row # in the virtual array */
-  rle_hdr header;               /* Input file information */
-  rle_pixel** rle_row;          /* holds a row returned by rle_getrow() */
-
-} rle_source_struct;
-
-
-/*
- * Read the file header; return image size and component count.
- */
-
-METHODDEF(void)
-start_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  rle_source_ptr source = (rle_source_ptr) sinfo;
-  JDIMENSION width, height;
-#ifdef PROGRESS_REPORT
-  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-#endif
-
-  /* Use RLE library routine to get the header info */
-  source->header = *rle_hdr_init(NULL);
-  source->header.rle_file = source->pub.input_file;
-  switch (rle_get_setup(&(source->header))) {
-  case RLE_SUCCESS:
-    /* A-OK */
-    break;
-  case RLE_NOT_RLE:
-    ERREXIT(cinfo, JERR_RLE_NOT);
-    break;
-  case RLE_NO_SPACE:
-    ERREXIT(cinfo, JERR_RLE_MEM);
-    break;
-  case RLE_EMPTY:
-    ERREXIT(cinfo, JERR_RLE_EMPTY);
-    break;
-  case RLE_EOF:
-    ERREXIT(cinfo, JERR_RLE_EOF);
-    break;
-  default:
-    ERREXIT(cinfo, JERR_RLE_BADERROR);
-    break;
-  }
-
-  /* Figure out what we have, set private vars and return values accordingly */
-  
-  width  = source->header.xmax - source->header.xmin + 1;
-  height = source->header.ymax - source->header.ymin + 1;
-  source->header.xmin = 0;		/* realign horizontally */
-  source->header.xmax = width-1;
-
-  cinfo->image_width      = width;
-  cinfo->image_height     = height;
-  cinfo->data_precision   = 8;  /* we can only handle 8 bit data */
-
-  if (source->header.ncolors == 1 && source->header.ncmap == 0) {
-    source->visual     = GRAYSCALE;
-    TRACEMS2(cinfo, 1, JTRC_RLE_GRAY, width, height);
-  } else if (source->header.ncolors == 1 && source->header.ncmap == 1) {
-    source->visual     = MAPPEDGRAY;
-    TRACEMS3(cinfo, 1, JTRC_RLE_MAPGRAY, width, height,
-             1 << source->header.cmaplen);
-  } else if (source->header.ncolors == 1 && source->header.ncmap == 3) {
-    source->visual     = PSEUDOCOLOR;
-    TRACEMS3(cinfo, 1, JTRC_RLE_MAPPED, width, height,
-	     1 << source->header.cmaplen);
-  } else if (source->header.ncolors == 3 && source->header.ncmap == 3) {
-    source->visual     = TRUECOLOR;
-    TRACEMS3(cinfo, 1, JTRC_RLE_FULLMAP, width, height,
-	     1 << source->header.cmaplen);
-  } else if (source->header.ncolors == 3 && source->header.ncmap == 0) {
-    source->visual     = DIRECTCOLOR;
-    TRACEMS2(cinfo, 1, JTRC_RLE, width, height);
-  } else
-    ERREXIT(cinfo, JERR_RLE_UNSUPPORTED);
-  
-  if (source->visual == GRAYSCALE || source->visual == MAPPEDGRAY) {
-    cinfo->in_color_space   = JCS_GRAYSCALE;
-    cinfo->input_components = 1;
-  } else {
-    cinfo->in_color_space   = JCS_RGB;
-    cinfo->input_components = 3;
-  }
-
-  /*
-   * A place to hold each scanline while it's converted.
-   * (GRAYSCALE scanlines don't need converting)
-   */
-  if (source->visual != GRAYSCALE) {
-    source->rle_row = (rle_pixel**) (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       (JDIMENSION) width, (JDIMENSION) cinfo->input_components);
-  }
-
-  /* request a virtual array to hold the image */
-  source->image = (*cinfo->mem->request_virt_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-     (JDIMENSION) (width * source->header.ncolors),
-     (JDIMENSION) height, (JDIMENSION) 1);
-
-#ifdef PROGRESS_REPORT
-  if (progress != NULL) {
-    /* count file input as separate pass */
-    progress->total_extra_passes++;
-  }
-#endif
-
-  source->pub.buffer_height = 1;
-}
-
-
-/*
- * Read one row of pixels.
- * Called only after load_image has read the image into the virtual array.
- * Used for GRAYSCALE, MAPPEDGRAY, TRUECOLOR, and DIRECTCOLOR images.
- */
-
-METHODDEF(JDIMENSION)
-get_rle_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  rle_source_ptr source = (rle_source_ptr) sinfo;
-
-  source->row--;
-  source->pub.buffer = (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE);
-
-  return 1;
-}
-
-/*
- * Read one row of pixels.
- * Called only after load_image has read the image into the virtual array.
- * Used for PSEUDOCOLOR images.
- */
-
-METHODDEF(JDIMENSION)
-get_pseudocolor_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  rle_source_ptr source = (rle_source_ptr) sinfo;
-  JSAMPROW src_row, dest_row;
-  JDIMENSION col;
-  rle_map *colormap;
-  int val;
-
-  colormap = source->header.cmap;
-  dest_row = source->pub.buffer[0];
-  source->row--;
-  src_row = * (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, source->image, source->row, (JDIMENSION) 1, FALSE);
-
-  for (col = cinfo->image_width; col > 0; col--) {
-    val = GETJSAMPLE(*src_row++);
-    *dest_row++ = (JSAMPLE) (colormap[val      ] >> 8);
-    *dest_row++ = (JSAMPLE) (colormap[val + 256] >> 8);
-    *dest_row++ = (JSAMPLE) (colormap[val + 512] >> 8);
-  }
-
-  return 1;
-}
-
-
-/*
- * Load the image into a virtual array.  We have to do this because RLE
- * files start at the lower left while the JPEG standard has them starting
- * in the upper left.  This is called the first time we want to get a row
- * of input.  What we do is load the RLE data into the array and then call
- * the appropriate routine to read one row from the array.  Before returning,
- * we set source->pub.get_pixel_rows so that subsequent calls go straight to
- * the appropriate row-reading routine.
- */
-
-METHODDEF(JDIMENSION)
-load_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  rle_source_ptr source = (rle_source_ptr) sinfo;
-  JDIMENSION row, col;
-  JSAMPROW  scanline, red_ptr, green_ptr, blue_ptr;
-  rle_pixel **rle_row;
-  rle_map *colormap;
-  char channel;
-#ifdef PROGRESS_REPORT
-  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-#endif
-
-  colormap = source->header.cmap;
-  rle_row = source->rle_row;
-
-  /* Read the RLE data into our virtual array.
-   * We assume here that (a) rle_pixel is represented the same as JSAMPLE,
-   * and (b) we are not on a machine where FAR pointers differ from regular.
-   */
-  RLE_CLR_BIT(source->header, RLE_ALPHA); /* don't read the alpha channel */
-
-#ifdef PROGRESS_REPORT
-  if (progress != NULL) {
-    progress->pub.pass_limit = cinfo->image_height;
-    progress->pub.pass_counter = 0;
-    (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-  }
-#endif
-
-  switch (source->visual) {
-
-  case GRAYSCALE:
-  case PSEUDOCOLOR:
-    for (row = 0; row < cinfo->image_height; row++) {
-      rle_row = (rle_pixel **) (*cinfo->mem->access_virt_sarray)
-         ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
-      rle_getrow(&source->header, rle_row);
-#ifdef PROGRESS_REPORT
-      if (progress != NULL) {
-        progress->pub.pass_counter++;
-        (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-      }
-#endif
-    }
-    break;
-
-  case MAPPEDGRAY:
-  case TRUECOLOR:
-    for (row = 0; row < cinfo->image_height; row++) {
-      scanline = * (*cinfo->mem->access_virt_sarray)
-        ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
-      rle_row = source->rle_row;
-      rle_getrow(&source->header, rle_row);
-
-      for (col = 0; col < cinfo->image_width; col++) {
-        for (channel = 0; channel < source->header.ncolors; channel++) {
-          *scanline++ = (JSAMPLE)
-            (colormap[GETJSAMPLE(rle_row[channel][col]) + 256 * channel] >> 8);
-        }
-      }
-
-#ifdef PROGRESS_REPORT
-      if (progress != NULL) {
-        progress->pub.pass_counter++;
-        (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-      }
-#endif
-    }
-    break;
-
-  case DIRECTCOLOR:
-    for (row = 0; row < cinfo->image_height; row++) {
-      scanline = * (*cinfo->mem->access_virt_sarray)
-        ((j_common_ptr) cinfo, source->image, row, (JDIMENSION) 1, TRUE);
-      rle_getrow(&source->header, rle_row);
-
-      red_ptr   = rle_row[0];
-      green_ptr = rle_row[1];
-      blue_ptr  = rle_row[2];
-
-      for (col = cinfo->image_width; col > 0; col--) {
-        *scanline++ = *red_ptr++;
-        *scanline++ = *green_ptr++;
-        *scanline++ = *blue_ptr++;
-      }
-
-#ifdef PROGRESS_REPORT
-      if (progress != NULL) {
-        progress->pub.pass_counter++;
-        (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-      }
-#endif
-    }
-  }
-
-#ifdef PROGRESS_REPORT
-  if (progress != NULL)
-    progress->completed_extra_passes++;
-#endif
-
-  /* Set up to call proper row-extraction routine in future */
-  if (source->visual == PSEUDOCOLOR) {
-    source->pub.buffer = source->rle_row;
-    source->pub.get_pixel_rows = get_pseudocolor_row;
-  } else {
-    source->pub.get_pixel_rows = get_rle_row;
-  }
-  source->row = cinfo->image_height;
-
-  /* And fetch the topmost (bottommost) row */
-  return (*source->pub.get_pixel_rows) (cinfo, sinfo);   
-}
-
-
-/*
- * Finish up at the end of the file.
- */
-
-METHODDEF(void)
-finish_input_rle (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  /* no work */
-}
-
-
-/*
- * The module selection routine for RLE format input.
- */
-
-GLOBAL(cjpeg_source_ptr)
-jinit_read_rle (j_compress_ptr cinfo)
-{
-  rle_source_ptr source;
-
-  /* Create module interface object */
-  source = (rle_source_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-                                  SIZEOF(rle_source_struct));
-  /* Fill in method ptrs */
-  source->pub.start_input = start_input_rle;
-  source->pub.finish_input = finish_input_rle;
-  source->pub.get_pixel_rows = load_image;
-
-  return (cjpeg_source_ptr) source;
-}
-
-#endif /* RLE_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/rdtarga.c ./Shared/jpeg-6b/rdtarga.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/rdtarga.c	Mon Dec  1 12:30:40 2003
+++ ./Shared/jpeg-6b/rdtarga.c	Wed Dec 31 19:00:00 1969
@@ -1,500 +0,0 @@
-/*
- * rdtarga.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to read input images in Targa format.
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume input from
- * an ordinary stdio stream.  They further assume that reading begins
- * at the start of the file; start_input may need work if the
- * user interface has already read some data (e.g., to determine that
- * the file is indeed Targa format).
- *
- * Based on code contributed by Lee Daniel Crocker.
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef TARGA_SUPPORTED
-
-
-/* Macros to deal with unsigned chars as efficiently as compiler allows */
-
-#ifdef HAVE_UNSIGNED_CHAR
-typedef unsigned char U_CHAR;
-#define UCH(x)	((int) (x))
-#else /* !HAVE_UNSIGNED_CHAR */
-#ifdef CHAR_IS_UNSIGNED
-typedef char U_CHAR;
-#define UCH(x)	((int) (x))
-#else
-typedef char U_CHAR;
-#define UCH(x)	((int) (x) & 0xFF)
-#endif
-#endif /* HAVE_UNSIGNED_CHAR */
-
-
-#define	ReadOK(file,buffer,len)	(JFREAD(file,buffer,len) == ((size_t) (len)))
-
-
-/* Private version of data source object */
-
-typedef struct _tga_source_struct * tga_source_ptr;
-
-typedef struct _tga_source_struct {
-  struct cjpeg_source_struct pub; /* public fields */
-
-  j_compress_ptr cinfo;		/* back link saves passing separate parm */
-
-  JSAMPARRAY colormap;		/* Targa colormap (converted to my format) */
-
-  jvirt_sarray_ptr whole_image;	/* Needed if funny input row order */
-  JDIMENSION current_row;	/* Current logical row number to read */
-
-  /* Pointer to routine to extract next Targa pixel from input file */
-  JMETHOD(void, read_pixel, (tga_source_ptr sinfo));
-
-  /* Result of read_pixel is delivered here: */
-  U_CHAR tga_pixel[4];
-
-  int pixel_size;		/* Bytes per Targa pixel (1 to 4) */
-
-  /* State info for reading RLE-coded pixels; both counts must be init to 0 */
-  int block_count;		/* # of pixels remaining in RLE block */
-  int dup_pixel_count;		/* # of times to duplicate previous pixel */
-
-  /* This saves the correct pixel-row-expansion method for preload_image */
-  JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo,
-				       cjpeg_source_ptr sinfo));
-} tga_source_struct;
-
-
-/* For expanding 5-bit pixel values to 8-bit with best rounding */
-
-static const UINT8 c5to8bits[32] = {
-    0,   8,  16,  25,  33,  41,  49,  58,
-   66,  74,  82,  90,  99, 107, 115, 123,
-  132, 140, 148, 156, 165, 173, 181, 189,
-  197, 206, 214, 222, 230, 239, 247, 255
-};
-
-
-
-LOCAL(int)
-read_byte (tga_source_ptr sinfo)
-/* Read next byte from Targa file */
-{
-  register FILE *infile = sinfo->pub.input_file;
-  register int c;
-
-  if ((c = getc(infile)) == EOF)
-    ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
-  return c;
-}
-
-
-LOCAL(void)
-read_colormap (tga_source_ptr sinfo, int cmaplen, int mapentrysize)
-/* Read the colormap from a Targa file */
-{
-  int i;
-
-  /* Presently only handles 24-bit BGR format */
-  if (mapentrysize != 24)
-    ERREXIT(sinfo->cinfo, JERR_TGA_BADCMAP);
-
-  for (i = 0; i < cmaplen; i++) {
-    sinfo->colormap[2][i] = (JSAMPLE) read_byte(sinfo);
-    sinfo->colormap[1][i] = (JSAMPLE) read_byte(sinfo);
-    sinfo->colormap[0][i] = (JSAMPLE) read_byte(sinfo);
-  }
-}
-
-
-/*
- * read_pixel methods: get a single pixel from Targa file into tga_pixel[]
- */
-
-METHODDEF(void)
-read_non_rle_pixel (tga_source_ptr sinfo)
-/* Read one Targa pixel from the input file; no RLE expansion */
-{
-  register FILE *infile = sinfo->pub.input_file;
-  register int i;
-
-  for (i = 0; i < sinfo->pixel_size; i++) {
-    sinfo->tga_pixel[i] = (U_CHAR) getc(infile);
-  }
-}
-
-
-METHODDEF(void)
-read_rle_pixel (tga_source_ptr sinfo)
-/* Read one Targa pixel from the input file, expanding RLE data as needed */
-{
-  register FILE *infile = sinfo->pub.input_file;
-  register int i;
-
-  /* Duplicate previously read pixel? */
-  if (sinfo->dup_pixel_count > 0) {
-    sinfo->dup_pixel_count--;
-    return;
-  }
-
-  /* Time to read RLE block header? */
-  if (--sinfo->block_count < 0) { /* decrement pixels remaining in block */
-    i = read_byte(sinfo);
-    if (i & 0x80) {		/* Start of duplicate-pixel block? */
-      sinfo->dup_pixel_count = i & 0x7F; /* number of dups after this one */
-      sinfo->block_count = 0;	/* then read new block header */
-    } else {
-      sinfo->block_count = i & 0x7F; /* number of pixels after this one */
-    }
-  }
-
-  /* Read next pixel */
-  for (i = 0; i < sinfo->pixel_size; i++) {
-    sinfo->tga_pixel[i] = (U_CHAR) getc(infile);
-  }
-}
-
-
-/*
- * Read one row of pixels.
- *
- * We provide several different versions depending on input file format.
- */
-
-
-METHODDEF(JDIMENSION)
-get_8bit_gray_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading 8-bit grayscale pixels */
-{
-  tga_source_ptr source = (tga_source_ptr) sinfo;
-  register JSAMPROW ptr;
-  register JDIMENSION col;
-  
-  ptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
-    *ptr++ = (JSAMPLE) UCH(source->tga_pixel[0]);
-  }
-  return 1;
-}
-
-METHODDEF(JDIMENSION)
-get_8bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading 8-bit colormap indexes */
-{
-  tga_source_ptr source = (tga_source_ptr) sinfo;
-  register int t;
-  register JSAMPROW ptr;
-  register JDIMENSION col;
-  register JSAMPARRAY colormap = source->colormap;
-
-  ptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
-    t = UCH(source->tga_pixel[0]);
-    *ptr++ = colormap[0][t];
-    *ptr++ = colormap[1][t];
-    *ptr++ = colormap[2][t];
-  }
-  return 1;
-}
-
-METHODDEF(JDIMENSION)
-get_16bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading 16-bit pixels */
-{
-  tga_source_ptr source = (tga_source_ptr) sinfo;
-  register int t;
-  register JSAMPROW ptr;
-  register JDIMENSION col;
-  
-  ptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
-    t = UCH(source->tga_pixel[0]);
-    t += UCH(source->tga_pixel[1]) << 8;
-    /* We expand 5 bit data to 8 bit sample width.
-     * The format of the 16-bit (LSB first) input word is
-     *     xRRRRRGGGGGBBBBB
-     */
-    ptr[2] = (JSAMPLE) c5to8bits[t & 0x1F];
-    t >>= 5;
-    ptr[1] = (JSAMPLE) c5to8bits[t & 0x1F];
-    t >>= 5;
-    ptr[0] = (JSAMPLE) c5to8bits[t & 0x1F];
-    ptr += 3;
-  }
-  return 1;
-}
-
-METHODDEF(JDIMENSION)
-get_24bit_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-/* This version is for reading 24-bit pixels */
-{
-  tga_source_ptr source = (tga_source_ptr) sinfo;
-  register JSAMPROW ptr;
-  register JDIMENSION col;
-  
-  ptr = source->pub.buffer[0];
-  for (col = cinfo->image_width; col > 0; col--) {
-    (*source->read_pixel) (source); /* Load next pixel into tga_pixel */
-    *ptr++ = (JSAMPLE) UCH(source->tga_pixel[2]); /* change BGR to RGB order */
-    *ptr++ = (JSAMPLE) UCH(source->tga_pixel[1]);
-    *ptr++ = (JSAMPLE) UCH(source->tga_pixel[0]);
-  }
-  return 1;
-}
-
-/*
- * Targa also defines a 32-bit pixel format with order B,G,R,A.
- * We presently ignore the attribute byte, so the code for reading
- * these pixels is identical to the 24-bit routine above.
- * This works because the actual pixel length is only known to read_pixel.
- */
-
-#define get_32bit_row  get_24bit_row
-
-
-/*
- * This method is for re-reading the input data in standard top-down
- * row order.  The entire image has already been read into whole_image
- * with proper conversion of pixel format, but it's in a funny row order.
- */
-
-METHODDEF(JDIMENSION)
-get_memory_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  tga_source_ptr source = (tga_source_ptr) sinfo;
-  JDIMENSION source_row;
-
-  /* Compute row of source that maps to current_row of normal order */
-  /* For now, assume image is bottom-up and not interlaced. */
-  /* NEEDS WORK to support interlaced images! */
-  source_row = cinfo->image_height - source->current_row - 1;
-
-  /* Fetch that row from virtual array */
-  source->pub.buffer = (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, source->whole_image,
-     source_row, (JDIMENSION) 1, FALSE);
-
-  source->current_row++;
-  return 1;
-}
-
-
-/*
- * This method loads the image into whole_image during the first call on
- * get_pixel_rows.  The get_pixel_rows pointer is then adjusted to call
- * get_memory_row on subsequent calls.
- */
-
-METHODDEF(JDIMENSION)
-preload_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  tga_source_ptr source = (tga_source_ptr) sinfo;
-  JDIMENSION row;
-  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-
-  /* Read the data into a virtual array in input-file row order. */
-  for (row = 0; row < cinfo->image_height; row++) {
-    if (progress != NULL) {
-      progress->pub.pass_counter = (long) row;
-      progress->pub.pass_limit = (long) cinfo->image_height;
-      (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-    }
-    source->pub.buffer = (*cinfo->mem->access_virt_sarray)
-      ((j_common_ptr) cinfo, source->whole_image, row, (JDIMENSION) 1, TRUE);
-    (*source->get_pixel_rows) (cinfo, sinfo);
-  }
-  if (progress != NULL)
-    progress->completed_extra_passes++;
-
-  /* Set up to read from the virtual array in unscrambled order */
-  source->pub.get_pixel_rows = get_memory_row;
-  source->current_row = 0;
-  /* And read the first row */
-  return get_memory_row(cinfo, sinfo);
-}
-
-
-/*
- * Read the file header; return image size and component count.
- */
-
-METHODDEF(void)
-start_input_tga (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  tga_source_ptr source = (tga_source_ptr) sinfo;
-  U_CHAR targaheader[18];
-  int idlen, cmaptype, subtype, flags, interlace_type, components;
-  unsigned int width, height, maplen;
-  boolean is_bottom_up;
-
-#define GET_2B(offset)	((unsigned int) UCH(targaheader[offset]) + \
-			 (((unsigned int) UCH(targaheader[offset+1])) << 8))
-
-  if (! ReadOK(source->pub.input_file, targaheader, 18))
-    ERREXIT(cinfo, JERR_INPUT_EOF);
-
-  /* Pretend "15-bit" pixels are 16-bit --- we ignore attribute bit anyway */
-  if (targaheader[16] == 15)
-    targaheader[16] = 16;
-
-  idlen = UCH(targaheader[0]);
-  cmaptype = UCH(targaheader[1]);
-  subtype = UCH(targaheader[2]);
-  maplen = GET_2B(5);
-  width = GET_2B(12);
-  height = GET_2B(14);
-  source->pixel_size = UCH(targaheader[16]) >> 3;
-  flags = UCH(targaheader[17]);	/* Image Descriptor byte */
-
-  is_bottom_up = ((flags & 0x20) == 0);	/* bit 5 set => top-down */
-  interlace_type = flags >> 6;	/* bits 6/7 are interlace code */
-
-  if (cmaptype > 1 ||		/* cmaptype must be 0 or 1 */
-      source->pixel_size < 1 || source->pixel_size > 4 ||
-      (UCH(targaheader[16]) & 7) != 0 || /* bits/pixel must be multiple of 8 */
-      interlace_type != 0)	/* currently don't allow interlaced image */
-    ERREXIT(cinfo, JERR_TGA_BADPARMS);
-  
-  if (subtype > 8) {
-    /* It's an RLE-coded file */
-    source->read_pixel = read_rle_pixel;
-    source->block_count = source->dup_pixel_count = 0;
-    subtype -= 8;
-  } else {
-    /* Non-RLE file */
-    source->read_pixel = read_non_rle_pixel;
-  }
-
-  /* Now should have subtype 1, 2, or 3 */
-  components = 3;		/* until proven different */
-  cinfo->in_color_space = JCS_RGB;
-
-  switch (subtype) {
-  case 1:			/* Colormapped image */
-    if (source->pixel_size == 1 && cmaptype == 1)
-      source->get_pixel_rows = get_8bit_row;
-    else
-      ERREXIT(cinfo, JERR_TGA_BADPARMS);
-    TRACEMS2(cinfo, 1, JTRC_TGA_MAPPED, width, height);
-    break;
-  case 2:			/* RGB image */
-    switch (source->pixel_size) {
-    case 2:
-      source->get_pixel_rows = get_16bit_row;
-      break;
-    case 3:
-      source->get_pixel_rows = get_24bit_row;
-      break;
-    case 4:
-      source->get_pixel_rows = get_32bit_row;
-      break;
-    default:
-      ERREXIT(cinfo, JERR_TGA_BADPARMS);
-      break;
-    }
-    TRACEMS2(cinfo, 1, JTRC_TGA, width, height);
-    break;
-  case 3:			/* Grayscale image */
-    components = 1;
-    cinfo->in_color_space = JCS_GRAYSCALE;
-    if (source->pixel_size == 1)
-      source->get_pixel_rows = get_8bit_gray_row;
-    else
-      ERREXIT(cinfo, JERR_TGA_BADPARMS);
-    TRACEMS2(cinfo, 1, JTRC_TGA_GRAY, width, height);
-    break;
-  default:
-    ERREXIT(cinfo, JERR_TGA_BADPARMS);
-    break;
-  }
-
-  if (is_bottom_up) {
-    /* Create a virtual array to buffer the upside-down image. */
-    source->whole_image = (*cinfo->mem->request_virt_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-       (JDIMENSION) width * components, (JDIMENSION) height, (JDIMENSION) 1);
-    if (cinfo->progress != NULL) {
-      cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-      progress->total_extra_passes++; /* count file input as separate pass */
-    }
-    /* source->pub.buffer will point to the virtual array. */
-    source->pub.buffer_height = 1; /* in case anyone looks at it */
-    source->pub.get_pixel_rows = preload_image;
-  } else {
-    /* Don't need a virtual array, but do need a one-row input buffer. */
-    source->whole_image = NULL;
-    source->pub.buffer = (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       (JDIMENSION) width * components, (JDIMENSION) 1);
-    source->pub.buffer_height = 1;
-    source->pub.get_pixel_rows = source->get_pixel_rows;
-  }
-  
-  while (idlen--)		/* Throw away ID field */
-    (void) read_byte(source);
-
-  if (maplen > 0) {
-    if (maplen > 256 || GET_2B(3) != 0)
-      ERREXIT(cinfo, JERR_TGA_BADCMAP);
-    /* Allocate space to store the colormap */
-    source->colormap = (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) maplen, (JDIMENSION) 3);
-    /* and read it from the file */
-    read_colormap(source, (int) maplen, UCH(targaheader[7]));
-  } else {
-    if (cmaptype)		/* but you promised a cmap! */
-      ERREXIT(cinfo, JERR_TGA_BADPARMS);
-    source->colormap = NULL;
-  }
-
-  cinfo->input_components = components;
-  cinfo->data_precision = 8;
-  cinfo->image_width = width;
-  cinfo->image_height = height;
-}
-
-
-/*
- * Finish up at the end of the file.
- */
-
-METHODDEF(void)
-finish_input_tga (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
-{
-  /* no work */
-}
-
-
-/*
- * The module selection routine for Targa format input.
- */
-
-GLOBAL(cjpeg_source_ptr)
-jinit_read_targa (j_compress_ptr cinfo)
-{
-  tga_source_ptr source;
-
-  /* Create module interface object */
-  source = (tga_source_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(tga_source_struct));
-  source->cinfo = cinfo;	/* make back link for subroutines */
-  /* Fill in method ptrs, except get_pixel_rows which start_input sets */
-  source->pub.start_input = start_input_tga;
-  source->pub.finish_input = finish_input_tga;
-
-  return (cjpeg_source_ptr) source;
-}
-
-#endif /* TARGA_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/structure.doc ./Shared/jpeg-6b/structure.doc
--- ../Tekkotsu_2.3/Shared/jpeg-6b/structure.doc	Mon Dec  1 12:30:41 2003
+++ ./Shared/jpeg-6b/structure.doc	Wed Dec 31 19:00:00 1969
@@ -1,948 +0,0 @@
-IJG JPEG LIBRARY:  SYSTEM ARCHITECTURE
-
-Copyright (C) 1991-1995, Thomas G. Lane.
-This file is part of the Independent JPEG Group's software.
-For conditions of distribution and use, see the accompanying README file.
-
-
-This file provides an overview of the architecture of the IJG JPEG software;
-that is, the functions of the various modules in the system and the interfaces
-between modules.  For more precise details about any data structure or calling
-convention, see the include files and comments in the source code.
-
-We assume that the reader is already somewhat familiar with the JPEG standard.
-The README file includes references for learning about JPEG.  The file
-libjpeg.doc describes the library from the viewpoint of an application
-programmer using the library; it's best to read that file before this one.
-Also, the file coderules.doc describes the coding style conventions we use.
-
-In this document, JPEG-specific terminology follows the JPEG standard:
-  A "component" means a color channel, e.g., Red or Luminance.
-  A "sample" is a single component value (i.e., one number in the image data).
-  A "coefficient" is a frequency coefficient (a DCT transform output number).
-  A "block" is an 8x8 group of samples or coefficients.
-  An "MCU" (minimum coded unit) is an interleaved set of blocks of size
-	determined by the sampling factors, or a single block in a
-	noninterleaved scan.
-We do not use the terms "pixel" and "sample" interchangeably.  When we say
-pixel, we mean an element of the full-size image, while a sample is an element
-of the downsampled image.  Thus the number of samples may vary across
-components while the number of pixels does not.  (This terminology is not used
-rigorously throughout the code, but it is used in places where confusion would
-otherwise result.)
-
-
-*** System features ***
-
-The IJG distribution contains two parts:
-  * A subroutine library for JPEG compression and decompression.
-  * cjpeg/djpeg, two sample applications that use the library to transform
-    JFIF JPEG files to and from several other image formats.
-cjpeg/djpeg are of no great intellectual complexity: they merely add a simple
-command-line user interface and I/O routines for several uncompressed image
-formats.  This document concentrates on the library itself.
-
-We desire the library to be capable of supporting all JPEG baseline, extended
-sequential, and progressive DCT processes.  Hierarchical processes are not
-supported.
-
-The library does not support the lossless (spatial) JPEG process.  Lossless
-JPEG shares little or no code with lossy JPEG, and would normally be used
-without the extensive pre- and post-processing provided by this library.
-We feel that lossless JPEG is better handled by a separate library.
-
-Within these limits, any set of compression parameters allowed by the JPEG
-spec should be readable for decompression.  (We can be more restrictive about
-what formats we can generate.)  Although the system design allows for all
-parameter values, some uncommon settings are not yet implemented and may
-never be; nonintegral sampling ratios are the prime example.  Furthermore,
-we treat 8-bit vs. 12-bit data precision as a compile-time switch, not a
-run-time option, because most machines can store 8-bit pixels much more
-compactly than 12-bit.
-
-For legal reasons, JPEG arithmetic coding is not currently supported, but
-extending the library to include it would be straightforward.
-
-By itself, the library handles only interchange JPEG datastreams --- in
-particular the widely used JFIF file format.  The library can be used by
-surrounding code to process interchange or abbreviated JPEG datastreams that
-are embedded in more complex file formats.  (For example, libtiff uses this
-library to implement JPEG compression within the TIFF file format.)
-
-The library includes a substantial amount of code that is not covered by the
-JPEG standard but is necessary for typical applications of JPEG.  These
-functions preprocess the image before JPEG compression or postprocess it after
-decompression.  They include colorspace conversion, downsampling/upsampling,
-and color quantization.  This code can be omitted if not needed.
-
-A wide range of quality vs. speed tradeoffs are possible in JPEG processing,
-and even more so in decompression postprocessing.  The decompression library
-provides multiple implementations that cover most of the useful tradeoffs,
-ranging from very-high-quality down to fast-preview operation.  On the
-compression side we have generally not provided low-quality choices, since
-compression is normally less time-critical.  It should be understood that the
-low-quality modes may not meet the JPEG standard's accuracy requirements;
-nonetheless, they are useful for viewers.
-
-
-*** Portability issues ***
-
-Portability is an essential requirement for the library.  The key portability
-issues that show up at the level of system architecture are:
-
-1.  Memory usage.  We want the code to be able to run on PC-class machines
-with limited memory.  Images should therefore be processed sequentially (in
-strips), to avoid holding the whole image in memory at once.  Where a
-full-image buffer is necessary, we should be able to use either virtual memory
-or temporary files.
-
-2.  Near/far pointer distinction.  To run efficiently on 80x86 machines, the
-code should distinguish "small" objects (kept in near data space) from
-"large" ones (kept in far data space).  This is an annoying restriction, but
-fortunately it does not impact code quality for less brain-damaged machines,
-and the source code clutter turns out to be minimal with sufficient use of
-pointer typedefs.
-
-3. Data precision.  We assume that "char" is at least 8 bits, "short" and
-"int" at least 16, "long" at least 32.  The code will work fine with larger
-data sizes, although memory may be used inefficiently in some cases.  However,
-the JPEG compressed datastream must ultimately appear on external storage as a
-sequence of 8-bit bytes if it is to conform to the standard.  This may pose a
-problem on machines where char is wider than 8 bits.  The library represents
-compressed data as an array of values of typedef JOCTET.  If no data type
-exactly 8 bits wide is available, custom data source and data destination
-modules must be written to unpack and pack the chosen JOCTET datatype into
-8-bit external representation.
-
-
-*** System overview ***
-
-The compressor and decompressor are each divided into two main sections:
-the JPEG compressor or decompressor proper, and the preprocessing or
-postprocessing functions.  The interface between these two sections is the
-image data that the official JPEG spec regards as its input or output: this
-data is in the colorspace to be used for compression, and it is downsampled
-to the sampling factors to be used.  The preprocessing and postprocessing
-steps are responsible for converting a normal image representation to or from
-this form.  (Those few applications that want to deal with YCbCr downsampled
-data can skip the preprocessing or postprocessing step.)
-
-Looking more closely, the compressor library contains the following main
-elements:
-
-  Preprocessing:
-    * Color space conversion (e.g., RGB to YCbCr).
-    * Edge expansion and downsampling.  Optionally, this step can do simple
-      smoothing --- this is often helpful for low-quality source data.
-  JPEG proper:
-    * MCU assembly, DCT, quantization.
-    * Entropy coding (sequential or progressive, Huffman or arithmetic).
-
-In addition to these modules we need overall control, marker generation,
-and support code (memory management & error handling).  There is also a
-module responsible for physically writing the output data --- typically
-this is just an interface to fwrite(), but some applications may need to
-do something else with the data.
-
-The decompressor library contains the following main elements:
-
-  JPEG proper:
-    * Entropy decoding (sequential or progressive, Huffman or arithmetic).
-    * Dequantization, inverse DCT, MCU disassembly.
-  Postprocessing:
-    * Upsampling.  Optionally, this step may be able to do more general
-      rescaling of the image.
-    * Color space conversion (e.g., YCbCr to RGB).  This step may also
-      provide gamma adjustment [ currently it does not ].
-    * Optional color quantization (e.g., reduction to 256 colors).
-    * Optional color precision reduction (e.g., 24-bit to 15-bit color).
-      [This feature is not currently implemented.]
-
-We also need overall control, marker parsing, and a data source module.
-The support code (memory management & error handling) can be shared with
-the compression half of the library.
-
-There may be several implementations of each of these elements, particularly
-in the decompressor, where a wide range of speed/quality tradeoffs is very
-useful.  It must be understood that some of the best speedups involve
-merging adjacent steps in the pipeline.  For example, upsampling, color space
-conversion, and color quantization might all be done at once when using a
-low-quality ordered-dither technique.  The system architecture is designed to
-allow such merging where appropriate.
-
-
-Note: it is convenient to regard edge expansion (padding to block boundaries)
-as a preprocessing/postprocessing function, even though the JPEG spec includes
-it in compression/decompression.  We do this because downsampling/upsampling
-can be simplified a little if they work on padded data: it's not necessary to
-have special cases at the right and bottom edges.  Therefore the interface
-buffer is always an integral number of blocks wide and high, and we expect
-compression preprocessing to pad the source data properly.  Padding will occur
-only to the next block (8-sample) boundary.  In an interleaved-scan situation,
-additional dummy blocks may be used to fill out MCUs, but the MCU assembly and
-disassembly logic will create or discard these blocks internally.  (This is
-advantageous for speed reasons, since we avoid DCTing the dummy blocks.
-It also permits a small reduction in file size, because the compressor can
-choose dummy block contents so as to minimize their size in compressed form.
-Finally, it makes the interface buffer specification independent of whether
-the file is actually interleaved or not.)  Applications that wish to deal
-directly with the downsampled data must provide similar buffering and padding
-for odd-sized images.
-
-
-*** Poor man's object-oriented programming ***
-
-It should be clear by now that we have a lot of quasi-independent processing
-steps, many of which have several possible behaviors.  To avoid cluttering the
-code with lots of switch statements, we use a simple form of object-style
-programming to separate out the different possibilities.
-
-For example, two different color quantization algorithms could be implemented
-as two separate modules that present the same external interface; at runtime,
-the calling code will access the proper module indirectly through an "object".
-
-We can get the limited features we need while staying within portable C.
-The basic tool is a function pointer.  An "object" is just a struct
-containing one or more function pointer fields, each of which corresponds to
-a method name in real object-oriented languages.  During initialization we
-fill in the function pointers with references to whichever module we have
-determined we need to use in this run.  Then invocation of the module is done
-by indirecting through a function pointer; on most machines this is no more
-expensive than a switch statement, which would be the only other way of
-making the required run-time choice.  The really significant benefit, of
-course, is keeping the source code clean and well structured.
-
-We can also arrange to have private storage that varies between different
-implementations of the same kind of object.  We do this by making all the
-module-specific object structs be separately allocated entities, which will
-be accessed via pointers in the master compression or decompression struct.
-The "public" fields or methods for a given kind of object are specified by
-a commonly known struct.  But a module's initialization code can allocate
-a larger struct that contains the common struct as its first member, plus
-additional private fields.  With appropriate pointer casting, the module's
-internal functions can access these private fields.  (For a simple example,
-see jdatadst.c, which implements the external interface specified by struct
-jpeg_destination_mgr, but adds extra fields.)
-
-(Of course this would all be a lot easier if we were using C++, but we are
-not yet prepared to assume that everyone has a C++ compiler.)
-
-An important benefit of this scheme is that it is easy to provide multiple
-versions of any method, each tuned to a particular case.  While a lot of
-precalculation might be done to select an optimal implementation of a method,
-the cost per invocation is constant.  For example, the upsampling step might
-have a "generic" method, plus one or more "hardwired" methods for the most
-popular sampling factors; the hardwired methods would be faster because they'd
-use straight-line code instead of for-loops.  The cost to determine which
-method to use is paid only once, at startup, and the selection criteria are
-hidden from the callers of the method.
-
-This plan differs a little bit from usual object-oriented structures, in that
-only one instance of each object class will exist during execution.  The
-reason for having the class structure is that on different runs we may create
-different instances (choose to execute different modules).  You can think of
-the term "method" as denoting the common interface presented by a particular
-set of interchangeable functions, and "object" as denoting a group of related
-methods, or the total shared interface behavior of a group of modules.
-
-
-*** Overall control structure ***
-
-We previously mentioned the need for overall control logic in the compression
-and decompression libraries.  In IJG implementations prior to v5, overall
-control was mostly provided by "pipeline control" modules, which proved to be
-large, unwieldy, and hard to understand.  To improve the situation, the
-control logic has been subdivided into multiple modules.  The control modules
-consist of:
-
-1. Master control for module selection and initialization.  This has two
-responsibilities:
-
-   1A.  Startup initialization at the beginning of image processing.
-        The individual processing modules to be used in this run are selected
-        and given initialization calls.
-
-   1B.  Per-pass control.  This determines how many passes will be performed
-        and calls each active processing module to configure itself
-        appropriately at the beginning of each pass.  End-of-pass processing,
-	where necessary, is also invoked from the master control module.
-
-   Method selection is partially distributed, in that a particular processing
-   module may contain several possible implementations of a particular method,
-   which it will select among when given its initialization call.  The master
-   control code need only be concerned with decisions that affect more than
-   one module.
- 
-2. Data buffering control.  A separate control module exists for each
-   inter-processing-step data buffer.  This module is responsible for
-   invoking the processing steps that write or read that data buffer.
-
-Each buffer controller sees the world as follows:
-
-input data => processing step A => buffer => processing step B => output data
-                      |              |               |
-              ------------------ controller ------------------
-
-The controller knows the dataflow requirements of steps A and B: how much data
-they want to accept in one chunk and how much they output in one chunk.  Its
-function is to manage its buffer and call A and B at the proper times.
-
-A data buffer control module may itself be viewed as a processing step by a
-higher-level control module; thus the control modules form a binary tree with
-elementary processing steps at the leaves of the tree.
-
-The control modules are objects.  A considerable amount of flexibility can
-be had by replacing implementations of a control module.  For example:
-* Merging of adjacent steps in the pipeline is done by replacing a control
-  module and its pair of processing-step modules with a single processing-
-  step module.  (Hence the possible merges are determined by the tree of
-  control modules.)
-* In some processing modes, a given interstep buffer need only be a "strip"
-  buffer large enough to accommodate the desired data chunk sizes.  In other
-  modes, a full-image buffer is needed and several passes are required.
-  The control module determines which kind of buffer is used and manipulates
-  virtual array buffers as needed.  One or both processing steps may be
-  unaware of the multi-pass behavior.
-
-In theory, we might be able to make all of the data buffer controllers
-interchangeable and provide just one set of implementations for all.  In
-practice, each one contains considerable special-case processing for its
-particular job.  The buffer controller concept should be regarded as an
-overall system structuring principle, not as a complete description of the
-task performed by any one controller.
-
-
-*** Compression object structure ***
-
-Here is a sketch of the logical structure of the JPEG compression library:
-
-                                                 |-- Colorspace conversion
-                  |-- Preprocessing controller --|
-                  |                              |-- Downsampling
-Main controller --|
-                  |                            |-- Forward DCT, quantize
-                  |-- Coefficient controller --|
-                                               |-- Entropy encoding
-
-This sketch also describes the flow of control (subroutine calls) during
-typical image data processing.  Each of the components shown in the diagram is
-an "object" which may have several different implementations available.  One
-or more source code files contain the actual implementation(s) of each object.
-
-The objects shown above are:
-
-* Main controller: buffer controller for the subsampled-data buffer, which
-  holds the preprocessed input data.  This controller invokes preprocessing to
-  fill the subsampled-data buffer, and JPEG compression to empty it.  There is
-  usually no need for a full-image buffer here; a strip buffer is adequate.
-
-* Preprocessing controller: buffer controller for the downsampling input data
-  buffer, which lies between colorspace conversion and downsampling.  Note
-  that a unified conversion/downsampling module would probably replace this
-  controller entirely.
-
-* Colorspace conversion: converts application image data into the desired
-  JPEG color space; also changes the data from pixel-interleaved layout to
-  separate component planes.  Processes one pixel row at a time.
-
-* Downsampling: performs reduction of chroma components as required.
-  Optionally may perform pixel-level smoothing as well.  Processes a "row
-  group" at a time, where a row group is defined as Vmax pixel rows of each
-  component before downsampling, and Vk sample rows afterwards (remember Vk
-  differs across components).  Some downsampling or smoothing algorithms may
-  require context rows above and below the current row group; the
-  preprocessing controller is responsible for supplying these rows via proper
-  buffering.  The downsampler is responsible for edge expansion at the right
-  edge (i.e., extending each sample row to a multiple of 8 samples); but the
-  preprocessing controller is responsible for vertical edge expansion (i.e.,
-  duplicating the bottom sample row as needed to make a multiple of 8 rows).
-
-* Coefficient controller: buffer controller for the DCT-coefficient data.
-  This controller handles MCU assembly, including insertion of dummy DCT
-  blocks when needed at the right or bottom edge.  When performing
-  Huffman-code optimization or emitting a multiscan JPEG file, this
-  controller is responsible for buffering the full image.  The equivalent of
-  one fully interleaved MCU row of subsampled data is processed per call,
-  even when the JPEG file is noninterleaved.
-
-* Forward DCT and quantization: Perform DCT, quantize, and emit coefficients.
-  Works on one or more DCT blocks at a time.  (Note: the coefficients are now
-  emitted in normal array order, which the entropy encoder is expected to
-  convert to zigzag order as necessary.  Prior versions of the IJG code did
-  the conversion to zigzag order within the quantization step.)
-
-* Entropy encoding: Perform Huffman or arithmetic entropy coding and emit the
-  coded data to the data destination module.  Works on one MCU per call.
-  For progressive JPEG, the same DCT blocks are fed to the entropy coder
-  during each pass, and the coder must emit the appropriate subset of
-  coefficients.
-
-In addition to the above objects, the compression library includes these
-objects:
-
-* Master control: determines the number of passes required, controls overall
-  and per-pass initialization of the other modules.
-
-* Marker writing: generates JPEG markers (except for RSTn, which is emitted
-  by the entropy encoder when needed).
-
-* Data destination manager: writes the output JPEG datastream to its final
-  destination (e.g., a file).  The destination manager supplied with the
-  library knows how to write to a stdio stream; for other behaviors, the
-  surrounding application may provide its own destination manager.
-
-* Memory manager: allocates and releases memory, controls virtual arrays
-  (with backing store management, where required).
-
-* Error handler: performs formatting and output of error and trace messages;
-  determines handling of nonfatal errors.  The surrounding application may
-  override some or all of this object's methods to change error handling.
-
-* Progress monitor: supports output of "percent-done" progress reports.
-  This object represents an optional callback to the surrounding application:
-  if wanted, it must be supplied by the application.
-
-The error handler, destination manager, and progress monitor objects are
-defined as separate objects in order to simplify application-specific
-customization of the JPEG library.  A surrounding application may override
-individual methods or supply its own all-new implementation of one of these
-objects.  The object interfaces for these objects are therefore treated as
-part of the application interface of the library, whereas the other objects
-are internal to the library.
-
-The error handler and memory manager are shared by JPEG compression and
-decompression; the progress monitor, if used, may be shared as well.
-
-
-*** Decompression object structure ***
-
-Here is a sketch of the logical structure of the JPEG decompression library:
-
-                                               |-- Entropy decoding
-                  |-- Coefficient controller --|
-                  |                            |-- Dequantize, Inverse DCT
-Main controller --|
-                  |                               |-- Upsampling
-                  |-- Postprocessing controller --|   |-- Colorspace conversion
-                                                  |-- Color quantization
-                                                  |-- Color precision reduction
-
-As before, this diagram also represents typical control flow.  The objects
-shown are:
-
-* Main controller: buffer controller for the subsampled-data buffer, which
-  holds the output of JPEG decompression proper.  This controller's primary
-  task is to feed the postprocessing procedure.  Some upsampling algorithms
-  may require context rows above and below the current row group; when this
-  is true, the main controller is responsible for managing its buffer so as
-  to make context rows available.  In the current design, the main buffer is
-  always a strip buffer; a full-image buffer is never required.
-
-* Coefficient controller: buffer controller for the DCT-coefficient data.
-  This controller handles MCU disassembly, including deletion of any dummy
-  DCT blocks at the right or bottom edge.  When reading a multiscan JPEG
-  file, this controller is responsible for buffering the full image.
-  (Buffering DCT coefficients, rather than samples, is necessary to support
-  progressive JPEG.)  The equivalent of one fully interleaved MCU row of
-  subsampled data is processed per call, even when the source JPEG file is
-  noninterleaved.
-
-* Entropy decoding: Read coded data from the data source module and perform
-  Huffman or arithmetic entropy decoding.  Works on one MCU per call.
-  For progressive JPEG decoding, the coefficient controller supplies the prior
-  coefficients of each MCU (initially all zeroes), which the entropy decoder
-  modifies in each scan.
-
-* Dequantization and inverse DCT: like it says.  Note that the coefficients
-  buffered by the coefficient controller have NOT been dequantized; we
-  merge dequantization and inverse DCT into a single step for speed reasons.
-  When scaled-down output is asked for, simplified DCT algorithms may be used
-  that emit only 1x1, 2x2, or 4x4 samples per DCT block, not the full 8x8.
-  Works on one DCT block at a time.
-
-* Postprocessing controller: buffer controller for the color quantization
-  input buffer, when quantization is in use.  (Without quantization, this
-  controller just calls the upsampler.)  For two-pass quantization, this
-  controller is responsible for buffering the full-image data.
-
-* Upsampling: restores chroma components to full size.  (May support more
-  general output rescaling, too.  Note that if undersized DCT outputs have
-  been emitted by the DCT module, this module must adjust so that properly
-  sized outputs are created.)  Works on one row group at a time.  This module
-  also calls the color conversion module, so its top level is effectively a
-  buffer controller for the upsampling->color conversion buffer.  However, in
-  all but the highest-quality operating modes, upsampling and color
-  conversion are likely to be merged into a single step.
-
-* Colorspace conversion: convert from JPEG color space to output color space,
-  and change data layout from separate component planes to pixel-interleaved.
-  Works on one pixel row at a time.
-
-* Color quantization: reduce the data to colormapped form, using either an
-  externally specified colormap or an internally generated one.  This module
-  is not used for full-color output.  Works on one pixel row at a time; may
-  require two passes to generate a color map.  Note that the output will
-  always be a single component representing colormap indexes.  In the current
-  design, the output values are JSAMPLEs, so an 8-bit compilation cannot
-  quantize to more than 256 colors.  This is unlikely to be a problem in
-  practice.
-
-* Color reduction: this module handles color precision reduction, e.g.,
-  generating 15-bit color (5 bits/primary) from JPEG's 24-bit output.
-  Not quite clear yet how this should be handled... should we merge it with
-  colorspace conversion???
-
-Note that some high-speed operating modes might condense the entire
-postprocessing sequence to a single module (upsample, color convert, and
-quantize in one step).
-
-In addition to the above objects, the decompression library includes these
-objects:
-
-* Master control: determines the number of passes required, controls overall
-  and per-pass initialization of the other modules.  This is subdivided into
-  input and output control: jdinput.c controls only input-side processing,
-  while jdmaster.c handles overall initialization and output-side control.
-
-* Marker reading: decodes JPEG markers (except for RSTn).
-
-* Data source manager: supplies the input JPEG datastream.  The source
-  manager supplied with the library knows how to read from a stdio stream;
-  for other behaviors, the surrounding application may provide its own source
-  manager.
-
-* Memory manager: same as for compression library.
-
-* Error handler: same as for compression library.
-
-* Progress monitor: same as for compression library.
-
-As with compression, the data source manager, error handler, and progress
-monitor are candidates for replacement by a surrounding application.
-
-
-*** Decompression input and output separation ***
-
-To support efficient incremental display of progressive JPEG files, the
-decompressor is divided into two sections that can run independently:
-
-1. Data input includes marker parsing, entropy decoding, and input into the
-   coefficient controller's DCT coefficient buffer.  Note that this
-   processing is relatively cheap and fast.
-
-2. Data output reads from the DCT coefficient buffer and performs the IDCT
-   and all postprocessing steps.
-
-For a progressive JPEG file, the data input processing is allowed to get
-arbitrarily far ahead of the data output processing.  (This occurs only
-if the application calls jpeg_consume_input(); otherwise input and output
-run in lockstep, since the input section is called only when the output
-section needs more data.)  In this way the application can avoid making
-extra display passes when data is arriving faster than the display pass
-can run.  Furthermore, it is possible to abort an output pass without
-losing anything, since the coefficient buffer is read-only as far as the
-output section is concerned.  See libjpeg.doc for more detail.
-
-A full-image coefficient array is only created if the JPEG file has multiple
-scans (or if the application specifies buffered-image mode anyway).  When
-reading a single-scan file, the coefficient controller normally creates only
-a one-MCU buffer, so input and output processing must run in lockstep in this
-case.  jpeg_consume_input() is effectively a no-op in this situation.
-
-The main impact of dividing the decompressor in this fashion is that we must
-be very careful with shared variables in the cinfo data structure.  Each
-variable that can change during the course of decompression must be
-classified as belonging to data input or data output, and each section must
-look only at its own variables.  For example, the data output section may not
-depend on any of the variables that describe the current scan in the JPEG
-file, because these may change as the data input section advances into a new
-scan.
-
-The progress monitor is (somewhat arbitrarily) defined to treat input of the
-file as one pass when buffered-image mode is not used, and to ignore data
-input work completely when buffered-image mode is used.  Note that the
-library has no reliable way to predict the number of passes when dealing
-with a progressive JPEG file, nor can it predict the number of output passes
-in buffered-image mode.  So the work estimate is inherently bogus anyway.
-
-No comparable division is currently made in the compression library, because
-there isn't any real need for it.
-
-
-*** Data formats ***
-
-Arrays of pixel sample values use the following data structure:
-
-    typedef something JSAMPLE;		a pixel component value, 0..MAXJSAMPLE
-    typedef JSAMPLE *JSAMPROW;		ptr to a row of samples
-    typedef JSAMPROW *JSAMPARRAY;	ptr to a list of rows
-    typedef JSAMPARRAY *JSAMPIMAGE;	ptr to a list of color-component arrays
-
-The basic element type JSAMPLE will typically be one of unsigned char,
-(signed) char, or short.  Short will be used if samples wider than 8 bits are
-to be supported (this is a compile-time option).  Otherwise, unsigned char is
-used if possible.  If the compiler only supports signed chars, then it is
-necessary to mask off the value when reading.  Thus, all reads of JSAMPLE
-values must be coded as "GETJSAMPLE(value)", where the macro will be defined
-as "((value) & 0xFF)" on signed-char machines and "((int) (value))" elsewhere.
-
-With these conventions, JSAMPLE values can be assumed to be >= 0.  This helps
-simplify correct rounding during downsampling, etc.  The JPEG standard's
-specification that sample values run from -128..127 is accommodated by
-subtracting 128 just as the sample value is copied into the source array for
-the DCT step (this will be an array of signed ints).  Similarly, during
-decompression the output of the IDCT step will be immediately shifted back to
-0..255.  (NB: different values are required when 12-bit samples are in use.
-The code is written in terms of MAXJSAMPLE and CENTERJSAMPLE, which will be
-defined as 255 and 128 respectively in an 8-bit implementation, and as 4095
-and 2048 in a 12-bit implementation.)
-
-We use a pointer per row, rather than a two-dimensional JSAMPLE array.  This
-choice costs only a small amount of memory and has several benefits:
-* Code using the data structure doesn't need to know the allocated width of
-  the rows.  This simplifies edge expansion/compression, since we can work
-  in an array that's wider than the logical picture width.
-* Indexing doesn't require multiplication; this is a performance win on many
-  machines.
-* Arrays with more than 64K total elements can be supported even on machines
-  where malloc() cannot allocate chunks larger than 64K.
-* The rows forming a component array may be allocated at different times
-  without extra copying.  This trick allows some speedups in smoothing steps
-  that need access to the previous and next rows.
-
-Note that each color component is stored in a separate array; we don't use the
-traditional layout in which the components of a pixel are stored together.
-This simplifies coding of modules that work on each component independently,
-because they don't need to know how many components there are.  Furthermore,
-we can read or write each component to a temporary file independently, which
-is helpful when dealing with noninterleaved JPEG files.
-
-In general, a specific sample value is accessed by code such as
-	GETJSAMPLE(image[colorcomponent][row][col])
-where col is measured from the image left edge, but row is measured from the
-first sample row currently in memory.  Either of the first two indexings can
-be precomputed by copying the relevant pointer.
-
-
-Since most image-processing applications prefer to work on images in which
-the components of a pixel are stored together, the data passed to or from the
-surrounding application uses the traditional convention: a single pixel is
-represented by N consecutive JSAMPLE values, and an image row is an array of
-(# of color components)*(image width) JSAMPLEs.  One or more rows of data can
-be represented by a pointer of type JSAMPARRAY in this scheme.  This scheme is
-converted to component-wise storage inside the JPEG library.  (Applications
-that want to skip JPEG preprocessing or postprocessing will have to contend
-with component-wise storage.)
-
-
-Arrays of DCT-coefficient values use the following data structure:
-
-    typedef short JCOEF;		a 16-bit signed integer
-    typedef JCOEF JBLOCK[DCTSIZE2];	an 8x8 block of coefficients
-    typedef JBLOCK *JBLOCKROW;		ptr to one horizontal row of 8x8 blocks
-    typedef JBLOCKROW *JBLOCKARRAY;	ptr to a list of such rows
-    typedef JBLOCKARRAY *JBLOCKIMAGE;	ptr to a list of color component arrays
-
-The underlying type is at least a 16-bit signed integer; while "short" is big
-enough on all machines of interest, on some machines it is preferable to use
-"int" for speed reasons, despite the storage cost.  Coefficients are grouped
-into 8x8 blocks (but we always use #defines DCTSIZE and DCTSIZE2 rather than
-"8" and "64").
-
-The contents of a coefficient block may be in either "natural" or zigzagged
-order, and may be true values or divided by the quantization coefficients,
-depending on where the block is in the processing pipeline.  In the current
-library, coefficient blocks are kept in natural order everywhere; the entropy
-codecs zigzag or dezigzag the data as it is written or read.  The blocks
-contain quantized coefficients everywhere outside the DCT/IDCT subsystems.
-(This latter decision may need to be revisited to support variable
-quantization a la JPEG Part 3.)
-
-Notice that the allocation unit is now a row of 8x8 blocks, corresponding to
-eight rows of samples.  Otherwise the structure is much the same as for
-samples, and for the same reasons.
-
-On machines where malloc() can't handle a request bigger than 64Kb, this data
-structure limits us to rows of less than 512 JBLOCKs, or a picture width of
-4000+ pixels.  This seems an acceptable restriction.
-
-
-On 80x86 machines, the bottom-level pointer types (JSAMPROW and JBLOCKROW)
-must be declared as "far" pointers, but the upper levels can be "near"
-(implying that the pointer lists are allocated in the DS segment).
-We use a #define symbol FAR, which expands to the "far" keyword when
-compiling on 80x86 machines and to nothing elsewhere.
-
-
-*** Suspendable processing ***
-
-In some applications it is desirable to use the JPEG library as an
-incremental, memory-to-memory filter.  In this situation the data source or
-destination may be a limited-size buffer, and we can't rely on being able to
-empty or refill the buffer at arbitrary times.  Instead the application would
-like to have control return from the library at buffer overflow/underrun, and
-then resume compression or decompression at a later time.
-
-This scenario is supported for simple cases.  (For anything more complex, we
-recommend that the application "bite the bullet" and develop real multitasking
-capability.)  The libjpeg.doc file goes into more detail about the usage and
-limitations of this capability; here we address the implications for library
-structure.
-
-The essence of the problem is that the entropy codec (coder or decoder) must
-be prepared to stop at arbitrary times.  In turn, the controllers that call
-the entropy codec must be able to stop before having produced or consumed all
-the data that they normally would handle in one call.  That part is reasonably
-straightforward: we make the controller call interfaces include "progress
-counters" which indicate the number of data chunks successfully processed, and
-we require callers to test the counter rather than just assume all of the data
-was processed.
-
-Rather than trying to restart at an arbitrary point, the current Huffman
-codecs are designed to restart at the beginning of the current MCU after a
-suspension due to buffer overflow/underrun.  At the start of each call, the
-codec's internal state is loaded from permanent storage (in the JPEG object
-structures) into local variables.  On successful completion of the MCU, the
-permanent state is updated.  (This copying is not very expensive, and may even
-lead to *improved* performance if the local variables can be registerized.)
-If a suspension occurs, the codec simply returns without updating the state,
-thus effectively reverting to the start of the MCU.  Note that this implies
-leaving some data unprocessed in the source/destination buffer (ie, the
-compressed partial MCU).  The data source/destination module interfaces are
-specified so as to make this possible.  This also implies that the data buffer
-must be large enough to hold a worst-case compressed MCU; a couple thousand
-bytes should be enough.
-
-In a successive-approximation AC refinement scan, the progressive Huffman
-decoder has to be able to undo assignments of newly nonzero coefficients if it
-suspends before the MCU is complete, since decoding requires distinguishing
-previously-zero and previously-nonzero coefficients.  This is a bit tedious
-but probably won't have much effect on performance.  Other variants of Huffman
-decoding need not worry about this, since they will just store the same values
-again if forced to repeat the MCU.
-
-This approach would probably not work for an arithmetic codec, since its
-modifiable state is quite large and couldn't be copied cheaply.  Instead it
-would have to suspend and resume exactly at the point of the buffer end.
-
-The JPEG marker reader is designed to cope with suspension at an arbitrary
-point.  It does so by backing up to the start of the marker parameter segment,
-so the data buffer must be big enough to hold the largest marker of interest.
-Again, a couple KB should be adequate.  (A special "skip" convention is used
-to bypass COM and APPn markers, so these can be larger than the buffer size
-without causing problems; otherwise a 64K buffer would be needed in the worst
-case.)
-
-The JPEG marker writer currently does *not* cope with suspension.  I feel that
-this is not necessary; it is much easier simply to require the application to
-ensure there is enough buffer space before starting.  (An empty 2K buffer is
-more than sufficient for the header markers; and ensuring there are a dozen or
-two bytes available before calling jpeg_finish_compress() will suffice for the
-trailer.)  This would not work for writing multi-scan JPEG files, but
-we simply do not intend to support that capability with suspension.
-
-
-*** Memory manager services ***
-
-The JPEG library's memory manager controls allocation and deallocation of
-memory, and it manages large "virtual" data arrays on machines where the
-operating system does not provide virtual memory.  Note that the same
-memory manager serves both compression and decompression operations.
-
-In all cases, allocated objects are tied to a particular compression or
-decompression master record, and they will be released when that master
-record is destroyed.
-
-The memory manager does not provide explicit deallocation of objects.
-Instead, objects are created in "pools" of free storage, and a whole pool
-can be freed at once.  This approach helps prevent storage-leak bugs, and
-it speeds up operations whenever malloc/free are slow (as they often are).
-The pools can be regarded as lifetime identifiers for objects.  Two
-pools/lifetimes are defined:
-  * JPOOL_PERMANENT	lasts until master record is destroyed
-  * JPOOL_IMAGE		lasts until done with image (JPEG datastream)
-Permanent lifetime is used for parameters and tables that should be carried
-across from one datastream to another; this includes all application-visible
-parameters.  Image lifetime is used for everything else.  (A third lifetime,
-JPOOL_PASS = one processing pass, was originally planned.  However it was
-dropped as not being worthwhile.  The actual usage patterns are such that the
-peak memory usage would be about the same anyway; and having per-pass storage
-substantially complicates the virtual memory allocation rules --- see below.)
-
-The memory manager deals with three kinds of object:
-1. "Small" objects.  Typically these require no more than 10K-20K total.
-2. "Large" objects.  These may require tens to hundreds of K depending on
-   image size.  Semantically they behave the same as small objects, but we
-   distinguish them for two reasons:
-     * On MS-DOS machines, large objects are referenced by FAR pointers,
-       small objects by NEAR pointers.
-     * Pool allocation heuristics may differ for large and small objects.
-   Note that individual "large" objects cannot exceed the size allowed by
-   type size_t, which may be 64K or less on some machines.
-3. "Virtual" objects.  These are large 2-D arrays of JSAMPLEs or JBLOCKs
-   (typically large enough for the entire image being processed).  The
-   memory manager provides stripwise access to these arrays.  On machines
-   without virtual memory, the rest of the array may be swapped out to a
-   temporary file.
-
-(Note: JSAMPARRAY and JBLOCKARRAY data structures are a combination of large
-objects for the data proper and small objects for the row pointers.  For
-convenience and speed, the memory manager provides single routines to create
-these structures.  Similarly, virtual arrays include a small control block
-and a JSAMPARRAY or JBLOCKARRAY working buffer, all created with one call.)
-
-In the present implementation, virtual arrays are only permitted to have image
-lifespan.  (Permanent lifespan would not be reasonable, and pass lifespan is
-not very useful since a virtual array's raison d'etre is to store data for
-multiple passes through the image.)  We also expect that only "small" objects
-will be given permanent lifespan, though this restriction is not required by
-the memory manager.
-
-In a non-virtual-memory machine, some performance benefit can be gained by
-making the in-memory buffers for virtual arrays be as large as possible.
-(For small images, the buffers might fit entirely in memory, so blind
-swapping would be very wasteful.)  The memory manager will adjust the height
-of the buffers to fit within a prespecified maximum memory usage.  In order
-to do this in a reasonably optimal fashion, the manager needs to allocate all
-of the virtual arrays at once.  Therefore, there isn't a one-step allocation
-routine for virtual arrays; instead, there is a "request" routine that simply
-allocates the control block, and a "realize" routine (called just once) that
-determines space allocation and creates all of the actual buffers.  The
-realize routine must allow for space occupied by non-virtual large objects.
-(We don't bother to factor in the space needed for small objects, on the
-grounds that it isn't worth the trouble.)
-
-To support all this, we establish the following protocol for doing business
-with the memory manager:
-  1. Modules must request virtual arrays (which may have only image lifespan)
-     during the initial setup phase, i.e., in their jinit_xxx routines.
-  2. All "large" objects (including JSAMPARRAYs and JBLOCKARRAYs) must also be
-     allocated during initial setup.
-  3. realize_virt_arrays will be called at the completion of initial setup.
-     The above conventions ensure that sufficient information is available
-     for it to choose a good size for virtual array buffers.
-Small objects of any lifespan may be allocated at any time.  We expect that
-the total space used for small objects will be small enough to be negligible
-in the realize_virt_arrays computation.
-
-In a virtual-memory machine, we simply pretend that the available space is
-infinite, thus causing realize_virt_arrays to decide that it can allocate all
-the virtual arrays as full-size in-memory buffers.  The overhead of the
-virtual-array access protocol is very small when no swapping occurs.
-
-A virtual array can be specified to be "pre-zeroed"; when this flag is set,
-never-yet-written sections of the array are set to zero before being made
-available to the caller.  If this flag is not set, never-written sections
-of the array contain garbage.  (This feature exists primarily because the
-equivalent logic would otherwise be needed in jdcoefct.c for progressive
-JPEG mode; we may as well make it available for possible other uses.)
-
-The first write pass on a virtual array is required to occur in top-to-bottom
-order; read passes, as well as any write passes after the first one, may
-access the array in any order.  This restriction exists partly to simplify
-the virtual array control logic, and partly because some file systems may not
-support seeking beyond the current end-of-file in a temporary file.  The main
-implication of this restriction is that rearrangement of rows (such as
-converting top-to-bottom data order to bottom-to-top) must be handled while
-reading data out of the virtual array, not while putting it in.
-
-
-*** Memory manager internal structure ***
-
-To isolate system dependencies as much as possible, we have broken the
-memory manager into two parts.  There is a reasonably system-independent
-"front end" (jmemmgr.c) and a "back end" that contains only the code
-likely to change across systems.  All of the memory management methods
-outlined above are implemented by the front end.  The back end provides
-the following routines for use by the front end (none of these routines
-are known to the rest of the JPEG code):
-
-jpeg_mem_init, jpeg_mem_term	system-dependent initialization/shutdown
-
-jpeg_get_small, jpeg_free_small	interface to malloc and free library routines
-				(or their equivalents)
-
-jpeg_get_large, jpeg_free_large	interface to FAR malloc/free in MSDOS machines;
-				else usually the same as
-				jpeg_get_small/jpeg_free_small
-
-jpeg_mem_available		estimate available memory
-
-jpeg_open_backing_store		create a backing-store object
-
-read_backing_store,		manipulate a backing-store object
-write_backing_store,
-close_backing_store
-
-On some systems there will be more than one type of backing-store object
-(specifically, in MS-DOS a backing store file might be an area of extended
-memory as well as a disk file).  jpeg_open_backing_store is responsible for
-choosing how to implement a given object.  The read/write/close routines
-are method pointers in the structure that describes a given object; this
-lets them be different for different object types.
-
-It may be necessary to ensure that backing store objects are explicitly
-released upon abnormal program termination.  For example, MS-DOS won't free
-extended memory by itself.  To support this, we will expect the main program
-or surrounding application to arrange to call self_destruct (typically via
-jpeg_destroy) upon abnormal termination.  This may require a SIGINT signal
-handler or equivalent.  We don't want to have the back end module install its
-own signal handler, because that would pre-empt the surrounding application's
-ability to control signal handling.
-
-The IJG distribution includes several memory manager back end implementations.
-Usually the same back end should be suitable for all applications on a given
-system, but it is possible for an application to supply its own back end at
-need.
-
-
-*** Implications of DNL marker ***
-
-Some JPEG files may use a DNL marker to postpone definition of the image
-height (this would be useful for a fax-like scanner's output, for instance).
-In these files the SOF marker claims the image height is 0, and you only
-find out the true image height at the end of the first scan.
-
-We could read these files as follows:
-1. Upon seeing zero image height, replace it by 65535 (the maximum allowed).
-2. When the DNL is found, update the image height in the global image
-   descriptor.
-This implies that control modules must avoid making copies of the image
-height, and must re-test for termination after each MCU row.  This would
-be easy enough to do.
-
-In cases where image-size data structures are allocated, this approach will
-result in very inefficient use of virtual memory or much-larger-than-necessary
-temporary files.  This seems acceptable for something that probably won't be a
-mainstream usage.  People might have to forgo use of memory-hogging options
-(such as two-pass color quantization or noninterleaved JPEG files) if they
-want efficient conversion of such files.  (One could improve efficiency by
-demanding a user-supplied upper bound for the height, less than 65536; in most
-cases it could be much less.)
-
-The standard also permits the SOF marker to overestimate the image height,
-with a DNL to give the true, smaller height at the end of the first scan.
-This would solve the space problems if the overestimate wasn't too great.
-However, it implies that you don't even know whether DNL will be used.
-
-This leads to a couple of very serious objections:
-1. Testing for a DNL marker must occur in the inner loop of the decompressor's
-   Huffman decoder; this implies a speed penalty whether the feature is used
-   or not.
-2. There is no way to hide the last-minute change in image height from an
-   application using the decoder.  Thus *every* application using the IJG
-   library would suffer a complexity penalty whether it cared about DNL or
-   not.
-We currently do not support DNL because of these problems.
-
-A different approach is to insist that DNL-using files be preprocessed by a
-separate program that reads ahead to the DNL, then goes back and fixes the SOF
-marker.  This is a much simpler solution and is probably far more efficient.
-Even if one wants piped input, buffering the first scan of the JPEG file needs
-a lot smaller temp file than is implied by the maximum-height method.  For
-this approach we'd simply treat DNL as a no-op in the decompressor (at most,
-check that it matches the SOF image height).
-
-We will not worry about making the compressor capable of outputting DNL.
-Something similar to the first scheme above could be applied if anyone ever
-wants to make that work.
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/wrbmp.c ./Shared/jpeg-6b/wrbmp.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/wrbmp.c	Mon Dec  1 12:30:41 2003
+++ ./Shared/jpeg-6b/wrbmp.c	Wed Dec 31 19:00:00 1969
@@ -1,442 +0,0 @@
-/*
- * wrbmp.c
- *
- * Copyright (C) 1994-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to write output images in Microsoft "BMP"
- * format (MS Windows 3.x and OS/2 1.x flavors).
- * Either 8-bit colormapped or 24-bit full-color format can be written.
- * No compression is supported.
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume output to
- * an ordinary stdio stream.
- *
- * This code contributed by James Arthur Boucher.
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef BMP_SUPPORTED
-
-
-/*
- * To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
- * This is not yet implemented.
- */
-
-#if BITS_IN_JSAMPLE != 8
-  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
-#endif
-
-/*
- * Since BMP stores scanlines bottom-to-top, we have to invert the image
- * from JPEG's top-to-bottom order.  To do this, we save the outgoing data
- * in a virtual array during put_pixel_row calls, then actually emit the
- * BMP file during finish_output.  The virtual array contains one JSAMPLE per
- * pixel if the output is grayscale or colormapped, three if it is full color.
- */
-
-/* Private version of data destination object */
-
-typedef struct {
-  struct djpeg_dest_struct pub;	/* public fields */
-
-  boolean is_os2;		/* saves the OS2 format request flag */
-
-  jvirt_sarray_ptr whole_image;	/* needed to reverse row order */
-  JDIMENSION data_width;	/* JSAMPLEs per row */
-  JDIMENSION row_width;		/* physical width of one row in the BMP file */
-  int pad_bytes;		/* number of padding bytes needed per row */
-  JDIMENSION cur_output_row;	/* next row# to write to virtual array */
-} bmp_dest_struct;
-
-typedef bmp_dest_struct * bmp_dest_ptr;
-
-
-/* Forward declarations */
-LOCAL(void) write_colormap
-	JPP((j_decompress_ptr cinfo, bmp_dest_ptr dest,
-	     int map_colors, int map_entry_size));
-
-
-/*
- * Write some pixel data.
- * In this module rows_supplied will always be 1.
- */
-
-METHODDEF(void)
-put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		JDIMENSION rows_supplied)
-/* This version is for writing 24-bit pixels */
-{
-  bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
-  JSAMPARRAY image_ptr;
-  register JSAMPROW inptr, outptr;
-  register JDIMENSION col;
-  int pad;
-
-  /* Access next row in virtual array */
-  image_ptr = (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, dest->whole_image,
-     dest->cur_output_row, (JDIMENSION) 1, TRUE);
-  dest->cur_output_row++;
-
-  /* Transfer data.  Note destination values must be in BGR order
-   * (even though Microsoft's own documents say the opposite).
-   */
-  inptr = dest->pub.buffer[0];
-  outptr = image_ptr[0];
-  for (col = cinfo->output_width; col > 0; col--) {
-    outptr[2] = *inptr++;	/* can omit GETJSAMPLE() safely */
-    outptr[1] = *inptr++;
-    outptr[0] = *inptr++;
-    outptr += 3;
-  }
-
-  /* Zero out the pad bytes. */
-  pad = dest->pad_bytes;
-  while (--pad >= 0)
-    *outptr++ = 0;
-}
-
-METHODDEF(void)
-put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-	       JDIMENSION rows_supplied)
-/* This version is for grayscale OR quantized color output */
-{
-  bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
-  JSAMPARRAY image_ptr;
-  register JSAMPROW inptr, outptr;
-  register JDIMENSION col;
-  int pad;
-
-  /* Access next row in virtual array */
-  image_ptr = (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, dest->whole_image,
-     dest->cur_output_row, (JDIMENSION) 1, TRUE);
-  dest->cur_output_row++;
-
-  /* Transfer data. */
-  inptr = dest->pub.buffer[0];
-  outptr = image_ptr[0];
-  for (col = cinfo->output_width; col > 0; col--) {
-    *outptr++ = *inptr++;	/* can omit GETJSAMPLE() safely */
-  }
-
-  /* Zero out the pad bytes. */
-  pad = dest->pad_bytes;
-  while (--pad >= 0)
-    *outptr++ = 0;
-}
-
-
-/*
- * Startup: normally writes the file header.
- * In this module we may as well postpone everything until finish_output.
- */
-
-METHODDEF(void)
-start_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  /* no work here */
-}
-
-
-/*
- * Finish up at the end of the file.
- *
- * Here is where we really output the BMP file.
- *
- * First, routines to write the Windows and OS/2 variants of the file header.
- */
-
-LOCAL(void)
-write_bmp_header (j_decompress_ptr cinfo, bmp_dest_ptr dest)
-/* Write a Windows-style BMP file header, including colormap if needed */
-{
-  char bmpfileheader[14];
-  char bmpinfoheader[40];
-#define PUT_2B(array,offset,value)  \
-	(array[offset] = (char) ((value) & 0xFF), \
-	 array[offset+1] = (char) (((value) >> 8) & 0xFF))
-#define PUT_4B(array,offset,value)  \
-	(array[offset] = (char) ((value) & 0xFF), \
-	 array[offset+1] = (char) (((value) >> 8) & 0xFF), \
-	 array[offset+2] = (char) (((value) >> 16) & 0xFF), \
-	 array[offset+3] = (char) (((value) >> 24) & 0xFF))
-  INT32 headersize, bfSize;
-  int bits_per_pixel, cmap_entries;
-
-  /* Compute colormap size and total file size */
-  if (cinfo->out_color_space == JCS_RGB) {
-    if (cinfo->quantize_colors) {
-      /* Colormapped RGB */
-      bits_per_pixel = 8;
-      cmap_entries = 256;
-    } else {
-      /* Unquantized, full color RGB */
-      bits_per_pixel = 24;
-      cmap_entries = 0;
-    }
-  } else {
-    /* Grayscale output.  We need to fake a 256-entry colormap. */
-    bits_per_pixel = 8;
-    cmap_entries = 256;
-  }
-  /* File size */
-  headersize = 14 + 40 + cmap_entries * 4; /* Header and colormap */
-  bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height;
-  
-  /* Set unused fields of header to 0 */
-  MEMZERO(bmpfileheader, SIZEOF(bmpfileheader));
-  MEMZERO(bmpinfoheader, SIZEOF(bmpinfoheader));
-
-  /* Fill the file header */
-  bmpfileheader[0] = 0x42;	/* first 2 bytes are ASCII 'B', 'M' */
-  bmpfileheader[1] = 0x4D;
-  PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
-  /* we leave bfReserved1 & bfReserved2 = 0 */
-  PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
-
-  /* Fill the info header (Microsoft calls this a BITMAPINFOHEADER) */
-  PUT_2B(bmpinfoheader, 0, 40);	/* biSize */
-  PUT_4B(bmpinfoheader, 4, cinfo->output_width); /* biWidth */
-  PUT_4B(bmpinfoheader, 8, cinfo->output_height); /* biHeight */
-  PUT_2B(bmpinfoheader, 12, 1);	/* biPlanes - must be 1 */
-  PUT_2B(bmpinfoheader, 14, bits_per_pixel); /* biBitCount */
-  /* we leave biCompression = 0, for none */
-  /* we leave biSizeImage = 0; this is correct for uncompressed data */
-  if (cinfo->density_unit == 2) { /* if have density in dots/cm, then */
-    PUT_4B(bmpinfoheader, 24, (INT32) (cinfo->X_density*100)); /* XPels/M */
-    PUT_4B(bmpinfoheader, 28, (INT32) (cinfo->Y_density*100)); /* XPels/M */
-  }
-  PUT_2B(bmpinfoheader, 32, cmap_entries); /* biClrUsed */
-  /* we leave biClrImportant = 0 */
-
-  if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14)
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-  if (JFWRITE(dest->pub.output_file, bmpinfoheader, 40) != (size_t) 40)
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-
-  if (cmap_entries > 0)
-    write_colormap(cinfo, dest, cmap_entries, 4);
-}
-
-
-LOCAL(void)
-write_os2_header (j_decompress_ptr cinfo, bmp_dest_ptr dest)
-/* Write an OS2-style BMP file header, including colormap if needed */
-{
-  char bmpfileheader[14];
-  char bmpcoreheader[12];
-  INT32 headersize, bfSize;
-  int bits_per_pixel, cmap_entries;
-
-  /* Compute colormap size and total file size */
-  if (cinfo->out_color_space == JCS_RGB) {
-    if (cinfo->quantize_colors) {
-      /* Colormapped RGB */
-      bits_per_pixel = 8;
-      cmap_entries = 256;
-    } else {
-      /* Unquantized, full color RGB */
-      bits_per_pixel = 24;
-      cmap_entries = 0;
-    }
-  } else {
-    /* Grayscale output.  We need to fake a 256-entry colormap. */
-    bits_per_pixel = 8;
-    cmap_entries = 256;
-  }
-  /* File size */
-  headersize = 14 + 12 + cmap_entries * 3; /* Header and colormap */
-  bfSize = headersize + (INT32) dest->row_width * (INT32) cinfo->output_height;
-  
-  /* Set unused fields of header to 0 */
-  MEMZERO(bmpfileheader, SIZEOF(bmpfileheader));
-  MEMZERO(bmpcoreheader, SIZEOF(bmpcoreheader));
-
-  /* Fill the file header */
-  bmpfileheader[0] = 0x42;	/* first 2 bytes are ASCII 'B', 'M' */
-  bmpfileheader[1] = 0x4D;
-  PUT_4B(bmpfileheader, 2, bfSize); /* bfSize */
-  /* we leave bfReserved1 & bfReserved2 = 0 */
-  PUT_4B(bmpfileheader, 10, headersize); /* bfOffBits */
-
-  /* Fill the info header (Microsoft calls this a BITMAPCOREHEADER) */
-  PUT_2B(bmpcoreheader, 0, 12);	/* bcSize */
-  PUT_2B(bmpcoreheader, 4, cinfo->output_width); /* bcWidth */
-  PUT_2B(bmpcoreheader, 6, cinfo->output_height); /* bcHeight */
-  PUT_2B(bmpcoreheader, 8, 1);	/* bcPlanes - must be 1 */
-  PUT_2B(bmpcoreheader, 10, bits_per_pixel); /* bcBitCount */
-
-  if (JFWRITE(dest->pub.output_file, bmpfileheader, 14) != (size_t) 14)
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-  if (JFWRITE(dest->pub.output_file, bmpcoreheader, 12) != (size_t) 12)
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-
-  if (cmap_entries > 0)
-    write_colormap(cinfo, dest, cmap_entries, 3);
-}
-
-
-/*
- * Write the colormap.
- * Windows uses BGR0 map entries; OS/2 uses BGR entries.
- */
-
-LOCAL(void)
-write_colormap (j_decompress_ptr cinfo, bmp_dest_ptr dest,
-		int map_colors, int map_entry_size)
-{
-  JSAMPARRAY colormap = cinfo->colormap;
-  int num_colors = cinfo->actual_number_of_colors;
-  FILE * outfile = dest->pub.output_file;
-  int i;
-
-  if (colormap != NULL) {
-    if (cinfo->out_color_components == 3) {
-      /* Normal case with RGB colormap */
-      for (i = 0; i < num_colors; i++) {
-	putc(GETJSAMPLE(colormap[2][i]), outfile);
-	putc(GETJSAMPLE(colormap[1][i]), outfile);
-	putc(GETJSAMPLE(colormap[0][i]), outfile);
-	if (map_entry_size == 4)
-	  putc(0, outfile);
-      }
-    } else {
-      /* Grayscale colormap (only happens with grayscale quantization) */
-      for (i = 0; i < num_colors; i++) {
-	putc(GETJSAMPLE(colormap[0][i]), outfile);
-	putc(GETJSAMPLE(colormap[0][i]), outfile);
-	putc(GETJSAMPLE(colormap[0][i]), outfile);
-	if (map_entry_size == 4)
-	  putc(0, outfile);
-      }
-    }
-  } else {
-    /* If no colormap, must be grayscale data.  Generate a linear "map". */
-    for (i = 0; i < 256; i++) {
-      putc(i, outfile);
-      putc(i, outfile);
-      putc(i, outfile);
-      if (map_entry_size == 4)
-	putc(0, outfile);
-    }
-  }
-  /* Pad colormap with zeros to ensure specified number of colormap entries */ 
-  if (i > map_colors)
-    ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, i);
-  for (; i < map_colors; i++) {
-    putc(0, outfile);
-    putc(0, outfile);
-    putc(0, outfile);
-    if (map_entry_size == 4)
-      putc(0, outfile);
-  }
-}
-
-
-METHODDEF(void)
-finish_output_bmp (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  bmp_dest_ptr dest = (bmp_dest_ptr) dinfo;
-  register FILE * outfile = dest->pub.output_file;
-  JSAMPARRAY image_ptr;
-  register JSAMPROW data_ptr;
-  JDIMENSION row;
-  register JDIMENSION col;
-  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-
-  /* Write the header and colormap */
-  if (dest->is_os2)
-    write_os2_header(cinfo, dest);
-  else
-    write_bmp_header(cinfo, dest);
-
-  /* Write the file body from our virtual array */
-  for (row = cinfo->output_height; row > 0; row--) {
-    if (progress != NULL) {
-      progress->pub.pass_counter = (long) (cinfo->output_height - row);
-      progress->pub.pass_limit = (long) cinfo->output_height;
-      (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-    }
-    image_ptr = (*cinfo->mem->access_virt_sarray)
-      ((j_common_ptr) cinfo, dest->whole_image, row-1, (JDIMENSION) 1, FALSE);
-    data_ptr = image_ptr[0];
-    for (col = dest->row_width; col > 0; col--) {
-      putc(GETJSAMPLE(*data_ptr), outfile);
-      data_ptr++;
-    }
-  }
-  if (progress != NULL)
-    progress->completed_extra_passes++;
-
-  /* Make sure we wrote the output file OK */
-  fflush(outfile);
-  if (ferror(outfile))
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-}
-
-
-/*
- * The module selection routine for BMP format output.
- */
-
-GLOBAL(djpeg_dest_ptr)
-jinit_write_bmp (j_decompress_ptr cinfo, boolean is_os2)
-{
-  bmp_dest_ptr dest;
-  JDIMENSION row_width;
-
-  /* Create module interface object, fill in method pointers */
-  dest = (bmp_dest_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(bmp_dest_struct));
-  dest->pub.start_output = start_output_bmp;
-  dest->pub.finish_output = finish_output_bmp;
-  dest->is_os2 = is_os2;
-
-  if (cinfo->out_color_space == JCS_GRAYSCALE) {
-    dest->pub.put_pixel_rows = put_gray_rows;
-  } else if (cinfo->out_color_space == JCS_RGB) {
-    if (cinfo->quantize_colors)
-      dest->pub.put_pixel_rows = put_gray_rows;
-    else
-      dest->pub.put_pixel_rows = put_pixel_rows;
-  } else {
-    ERREXIT(cinfo, JERR_BMP_COLORSPACE);
-  }
-
-  /* Calculate output image dimensions so we can allocate space */
-  jpeg_calc_output_dimensions(cinfo);
-
-  /* Determine width of rows in the BMP file (padded to 4-byte boundary). */
-  row_width = cinfo->output_width * cinfo->output_components;
-  dest->data_width = row_width;
-  while ((row_width & 3) != 0) row_width++;
-  dest->row_width = row_width;
-  dest->pad_bytes = (int) (row_width - dest->data_width);
-
-  /* Allocate space for inversion array, prepare for write pass */
-  dest->whole_image = (*cinfo->mem->request_virt_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-     row_width, cinfo->output_height, (JDIMENSION) 1);
-  dest->cur_output_row = 0;
-  if (cinfo->progress != NULL) {
-    cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-    progress->total_extra_passes++; /* count file input as separate pass */
-  }
-
-  /* Create decompressor output buffer. */
-  dest->pub.buffer = (*cinfo->mem->alloc_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, row_width, (JDIMENSION) 1);
-  dest->pub.buffer_height = 1;
-
-  return (djpeg_dest_ptr) dest;
-}
-
-#endif /* BMP_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/wrgif.c ./Shared/jpeg-6b/wrgif.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/wrgif.c	Mon Dec  1 12:30:41 2003
+++ ./Shared/jpeg-6b/wrgif.c	Wed Dec 31 19:00:00 1969
@@ -1,399 +0,0 @@
-/*
- * wrgif.c
- *
- * Copyright (C) 1991-1997, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to write output images in GIF format.
- *
- **************************************************************************
- * NOTE: to avoid entanglements with Unisys' patent on LZW compression,   *
- * this code has been modified to output "uncompressed GIF" files.        *
- * There is no trace of the LZW algorithm in this file.                   *
- **************************************************************************
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume output to
- * an ordinary stdio stream.
- */
-
-/*
- * This code is loosely based on ppmtogif from the PBMPLUS distribution
- * of Feb. 1991.  That file contains the following copyright notice:
- *    Based on GIFENCODE by David Rowley <mgardi@watdscu.waterloo.edu>.
- *    Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al.
- *    Copyright (C) 1989 by Jef Poskanzer.
- *    Permission to use, copy, modify, and distribute this software and its
- *    documentation for any purpose and without fee is hereby granted, provided
- *    that the above copyright notice appear in all copies and that both that
- *    copyright notice and this permission notice appear in supporting
- *    documentation.  This software is provided "as is" without express or
- *    implied warranty.
- *
- * We are also required to state that
- *    "The Graphics Interchange Format(c) is the Copyright property of
- *    CompuServe Incorporated. GIF(sm) is a Service Mark property of
- *    CompuServe Incorporated."
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef GIF_SUPPORTED
-
-
-/* Private version of data destination object */
-
-typedef struct {
-  struct djpeg_dest_struct pub;	/* public fields */
-
-  j_decompress_ptr cinfo;	/* back link saves passing separate parm */
-
-  /* State for packing variable-width codes into a bitstream */
-  int n_bits;			/* current number of bits/code */
-  int maxcode;			/* maximum code, given n_bits */
-  INT32 cur_accum;		/* holds bits not yet output */
-  int cur_bits;			/* # of bits in cur_accum */
-
-  /* State for GIF code assignment */
-  int ClearCode;		/* clear code (doesn't change) */
-  int EOFCode;			/* EOF code (ditto) */
-  int code_counter;		/* counts output symbols */
-
-  /* GIF data packet construction buffer */
-  int bytesinpkt;		/* # of bytes in current packet */
-  char packetbuf[256];		/* workspace for accumulating packet */
-
-} gif_dest_struct;
-
-typedef gif_dest_struct * gif_dest_ptr;
-
-/* Largest value that will fit in N bits */
-#define MAXCODE(n_bits)	((1 << (n_bits)) - 1)
-
-
-/*
- * Routines to package finished data bytes into GIF data blocks.
- * A data block consists of a count byte (1..255) and that many data bytes.
- */
-
-LOCAL(void)
-flush_packet (gif_dest_ptr dinfo)
-/* flush any accumulated data */
-{
-  if (dinfo->bytesinpkt > 0) {	/* never write zero-length packet */
-    dinfo->packetbuf[0] = (char) dinfo->bytesinpkt++;
-    if (JFWRITE(dinfo->pub.output_file, dinfo->packetbuf, dinfo->bytesinpkt)
-	!= (size_t) dinfo->bytesinpkt)
-      ERREXIT(dinfo->cinfo, JERR_FILE_WRITE);
-    dinfo->bytesinpkt = 0;
-  }
-}
-
-
-/* Add a character to current packet; flush to disk if necessary */
-#define CHAR_OUT(dinfo,c)  \
-	{ (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c);  \
-	    if ((dinfo)->bytesinpkt >= 255)  \
-	      flush_packet(dinfo);  \
-	}
-
-
-/* Routine to convert variable-width codes into a byte stream */
-
-LOCAL(void)
-output (gif_dest_ptr dinfo, int code)
-/* Emit a code of n_bits bits */
-/* Uses cur_accum and cur_bits to reblock into 8-bit bytes */
-{
-  dinfo->cur_accum |= ((INT32) code) << dinfo->cur_bits;
-  dinfo->cur_bits += dinfo->n_bits;
-
-  while (dinfo->cur_bits >= 8) {
-    CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
-    dinfo->cur_accum >>= 8;
-    dinfo->cur_bits -= 8;
-  }
-}
-
-
-/* The pseudo-compression algorithm.
- *
- * In this module we simply output each pixel value as a separate symbol;
- * thus, no compression occurs.  In fact, there is expansion of one bit per
- * pixel, because we use a symbol width one bit wider than the pixel width.
- *
- * GIF ordinarily uses variable-width symbols, and the decoder will expect
- * to ratchet up the symbol width after a fixed number of symbols.
- * To simplify the logic and keep the expansion penalty down, we emit a
- * GIF Clear code to reset the decoder just before the width would ratchet up.
- * Thus, all the symbols in the output file will have the same bit width.
- * Note that emitting the Clear codes at the right times is a mere matter of
- * counting output symbols and is in no way dependent on the LZW patent.
- *
- * With a small basic pixel width (low color count), Clear codes will be
- * needed very frequently, causing the file to expand even more.  So this
- * simplistic approach wouldn't work too well on bilevel images, for example.
- * But for output of JPEG conversions the pixel width will usually be 8 bits
- * (129 to 256 colors), so the overhead added by Clear symbols is only about
- * one symbol in every 256.
- */
-
-LOCAL(void)
-compress_init (gif_dest_ptr dinfo, int i_bits)
-/* Initialize pseudo-compressor */
-{
-  /* init all the state variables */
-  dinfo->n_bits = i_bits;
-  dinfo->maxcode = MAXCODE(dinfo->n_bits);
-  dinfo->ClearCode = (1 << (i_bits - 1));
-  dinfo->EOFCode = dinfo->ClearCode + 1;
-  dinfo->code_counter = dinfo->ClearCode + 2;
-  /* init output buffering vars */
-  dinfo->bytesinpkt = 0;
-  dinfo->cur_accum = 0;
-  dinfo->cur_bits = 0;
-  /* GIF specifies an initial Clear code */
-  output(dinfo, dinfo->ClearCode);
-}
-
-
-LOCAL(void)
-compress_pixel (gif_dest_ptr dinfo, int c)
-/* Accept and "compress" one pixel value.
- * The given value must be less than n_bits wide.
- */
-{
-  /* Output the given pixel value as a symbol. */
-  output(dinfo, c);
-  /* Issue Clear codes often enough to keep the reader from ratcheting up
-   * its symbol size.
-   */
-  if (dinfo->code_counter < dinfo->maxcode) {
-    dinfo->code_counter++;
-  } else {
-    output(dinfo, dinfo->ClearCode);
-    dinfo->code_counter = dinfo->ClearCode + 2;	/* reset the counter */
-  }
-}
-
-
-LOCAL(void)
-compress_term (gif_dest_ptr dinfo)
-/* Clean up at end */
-{
-  /* Send an EOF code */
-  output(dinfo, dinfo->EOFCode);
-  /* Flush the bit-packing buffer */
-  if (dinfo->cur_bits > 0) {
-    CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
-  }
-  /* Flush the packet buffer */
-  flush_packet(dinfo);
-}
-
-
-/* GIF header construction */
-
-
-LOCAL(void)
-put_word (gif_dest_ptr dinfo, unsigned int w)
-/* Emit a 16-bit word, LSB first */
-{
-  putc(w & 0xFF, dinfo->pub.output_file);
-  putc((w >> 8) & 0xFF, dinfo->pub.output_file);
-}
-
-
-LOCAL(void)
-put_3bytes (gif_dest_ptr dinfo, int val)
-/* Emit 3 copies of same byte value --- handy subr for colormap construction */
-{
-  putc(val, dinfo->pub.output_file);
-  putc(val, dinfo->pub.output_file);
-  putc(val, dinfo->pub.output_file);
-}
-
-
-LOCAL(void)
-emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap)
-/* Output the GIF file header, including color map */
-/* If colormap==NULL, synthesize a gray-scale colormap */
-{
-  int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte;
-  int cshift = dinfo->cinfo->data_precision - 8;
-  int i;
-
-  if (num_colors > 256)
-    ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors);
-  /* Compute bits/pixel and related values */
-  BitsPerPixel = 1;
-  while (num_colors > (1 << BitsPerPixel))
-    BitsPerPixel++;
-  ColorMapSize = 1 << BitsPerPixel;
-  if (BitsPerPixel <= 1)
-    InitCodeSize = 2;
-  else
-    InitCodeSize = BitsPerPixel;
-  /*
-   * Write the GIF header.
-   * Note that we generate a plain GIF87 header for maximum compatibility.
-   */
-  putc('G', dinfo->pub.output_file);
-  putc('I', dinfo->pub.output_file);
-  putc('F', dinfo->pub.output_file);
-  putc('8', dinfo->pub.output_file);
-  putc('7', dinfo->pub.output_file);
-  putc('a', dinfo->pub.output_file);
-  /* Write the Logical Screen Descriptor */
-  put_word(dinfo, (unsigned int) dinfo->cinfo->output_width);
-  put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
-  FlagByte = 0x80;		/* Yes, there is a global color table */
-  FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */
-  FlagByte |= (BitsPerPixel-1);	/* size of global color table */
-  putc(FlagByte, dinfo->pub.output_file);
-  putc(0, dinfo->pub.output_file); /* Background color index */
-  putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */
-  /* Write the Global Color Map */
-  /* If the color map is more than 8 bits precision, */
-  /* we reduce it to 8 bits by shifting */
-  for (i=0; i < ColorMapSize; i++) {
-    if (i < num_colors) {
-      if (colormap != NULL) {
-	if (dinfo->cinfo->out_color_space == JCS_RGB) {
-	  /* Normal case: RGB color map */
-	  putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file);
-	  putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file);
-	  putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file);
-	} else {
-	  /* Grayscale "color map": possible if quantizing grayscale image */
-	  put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift);
-	}
-      } else {
-	/* Create a gray-scale map of num_colors values, range 0..255 */
-	put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1));
-      }
-    } else {
-      /* fill out the map to a power of 2 */
-      put_3bytes(dinfo, 0);
-    }
-  }
-  /* Write image separator and Image Descriptor */
-  putc(',', dinfo->pub.output_file); /* separator */
-  put_word(dinfo, 0);		/* left/top offset */
-  put_word(dinfo, 0);
-  put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */
-  put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
-  /* flag byte: not interlaced, no local color map */
-  putc(0x00, dinfo->pub.output_file);
-  /* Write Initial Code Size byte */
-  putc(InitCodeSize, dinfo->pub.output_file);
-
-  /* Initialize for "compression" of image data */
-  compress_init(dinfo, InitCodeSize+1);
-}
-
-
-/*
- * Startup: write the file header.
- */
-
-METHODDEF(void)
-start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  gif_dest_ptr dest = (gif_dest_ptr) dinfo;
-
-  if (cinfo->quantize_colors)
-    emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap);
-  else
-    emit_header(dest, 256, (JSAMPARRAY) NULL);
-}
-
-
-/*
- * Write some pixel data.
- * In this module rows_supplied will always be 1.
- */
-
-METHODDEF(void)
-put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		JDIMENSION rows_supplied)
-{
-  gif_dest_ptr dest = (gif_dest_ptr) dinfo;
-  register JSAMPROW ptr;
-  register JDIMENSION col;
-
-  ptr = dest->pub.buffer[0];
-  for (col = cinfo->output_width; col > 0; col--) {
-    compress_pixel(dest, GETJSAMPLE(*ptr++));
-  }
-}
-
-
-/*
- * Finish up at the end of the file.
- */
-
-METHODDEF(void)
-finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  gif_dest_ptr dest = (gif_dest_ptr) dinfo;
-
-  /* Flush "compression" mechanism */
-  compress_term(dest);
-  /* Write a zero-length data block to end the series */
-  putc(0, dest->pub.output_file);
-  /* Write the GIF terminator mark */
-  putc(';', dest->pub.output_file);
-  /* Make sure we wrote the output file OK */
-  fflush(dest->pub.output_file);
-  if (ferror(dest->pub.output_file))
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-}
-
-
-/*
- * The module selection routine for GIF format output.
- */
-
-GLOBAL(djpeg_dest_ptr)
-jinit_write_gif (j_decompress_ptr cinfo)
-{
-  gif_dest_ptr dest;
-
-  /* Create module interface object, fill in method pointers */
-  dest = (gif_dest_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(gif_dest_struct));
-  dest->cinfo = cinfo;		/* make back link for subroutines */
-  dest->pub.start_output = start_output_gif;
-  dest->pub.put_pixel_rows = put_pixel_rows;
-  dest->pub.finish_output = finish_output_gif;
-
-  if (cinfo->out_color_space != JCS_GRAYSCALE &&
-      cinfo->out_color_space != JCS_RGB)
-    ERREXIT(cinfo, JERR_GIF_COLORSPACE);
-
-  /* Force quantization if color or if > 8 bits input */
-  if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) {
-    /* Force quantization to at most 256 colors */
-    cinfo->quantize_colors = TRUE;
-    if (cinfo->desired_number_of_colors > 256)
-      cinfo->desired_number_of_colors = 256;
-  }
-
-  /* Calculate output image dimensions so we can allocate space */
-  jpeg_calc_output_dimensions(cinfo);
-
-  if (cinfo->output_components != 1) /* safety check: just one component? */
-    ERREXIT(cinfo, JERR_GIF_BUG);
-
-  /* Create decompressor output buffer. */
-  dest->pub.buffer = (*cinfo->mem->alloc_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1);
-  dest->pub.buffer_height = 1;
-
-  return (djpeg_dest_ptr) dest;
-}
-
-#endif /* GIF_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/write_jpeg.c ./Shared/jpeg-6b/write_jpeg.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/write_jpeg.c	Mon Dec  1 12:30:41 2003
+++ ./Shared/jpeg-6b/write_jpeg.c	Wed Dec 31 19:00:00 1969
@@ -1,106 +0,0 @@
-//
-// Copyright 2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "jpeglib.h"
-#include "write_jpeg.h"
-#include "jpeg_mem_dest.h"
-
-int
-write_jpeg_mem(unsigned char* YCbCr,
-               int w, int h, int quality,
-               unsigned char* dest, int destsize)
-{
-    JSAMPLE* image_buffer = (JSAMPLE*)YCbCr;
-    int      image_width  = w;
-    int      image_height = h;
-
-    struct jpeg_compress_struct cinfo;
-    struct jpeg_error_mgr jerr;
-
-    JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
-    int row_stride;		/* physical row width in image buffer */
-    int jpegsize;
-
-    cinfo.err = jpeg_std_error(&jerr);
-    jpeg_create_compress(&cinfo);
-
-    jpeg_mem_dest(&cinfo, dest, destsize);
-
-    cinfo.image_width = image_width;
-    cinfo.image_height = image_height;
-    cinfo.input_components = 3;		/* # of color components per pixel */
-    cinfo.in_color_space = JCS_YCbCr; /* colorspace of input image */
-
-    jpeg_set_defaults(&cinfo);
-
-    jpeg_set_quality(&cinfo,
-                     quality, TRUE /* limit to baseline-JPEG values */);
-
-    jpeg_start_compress(&cinfo, TRUE);
-
-    row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
-
-    while (cinfo.next_scanline < cinfo.image_height) {
-        row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
-        (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
-    }
-
-    jpeg_finish_compress(&cinfo);
-    jpegsize = jpeg_mem_size(&cinfo);
-
-    jpeg_destroy_compress(&cinfo);
-
-    return jpegsize;
-}
-
-void
-write_jpeg_file(unsigned char* YCbCr, int w, int h, int quality, FILE* outfile)
-{
-    JSAMPLE* image_buffer = (JSAMPLE*)YCbCr;
-    int      image_width  = w;
-    int      image_height = h;
-
-    struct jpeg_compress_struct cinfo;
-    struct jpeg_error_mgr jerr;
-
-    JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
-    int row_stride;		/* physical row width in image buffer */
-
-    cinfo.err = jpeg_std_error(&jerr);
-    jpeg_create_compress(&cinfo);
-
-    jpeg_stdio_dest(&cinfo, outfile);
-
-    cinfo.image_width = image_width;
-    cinfo.image_height = image_height;
-    cinfo.input_components = 3;		/* # of color components per pixel */
-    cinfo.in_color_space = JCS_YCbCr; /* colorspace of input image */
-
-    jpeg_set_defaults(&cinfo);
-
-    jpeg_set_quality(&cinfo,
-                     quality, TRUE /* limit to baseline-JPEG values */);
-    
-    jpeg_start_compress(&cinfo, TRUE);
-
-    row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
-
-    while (cinfo.next_scanline < cinfo.image_height) {
-        row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
-        (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
-    }
-
-    jpeg_finish_compress(&cinfo);
-
-    jpeg_destroy_compress(&cinfo);
-}
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/write_jpeg.cc ./Shared/jpeg-6b/write_jpeg.cc
--- ../Tekkotsu_2.3/Shared/jpeg-6b/write_jpeg.cc	Wed Dec 31 19:00:00 1969
+++ ./Shared/jpeg-6b/write_jpeg.cc	Wed Jun  1 01:47:53 2005
@@ -0,0 +1,114 @@
+//
+// Copyright 2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "write_jpeg.h"
+#include "jpeg_mem_dest.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include <jpeglib.h>
+
+int
+write_jpeg_mem(unsigned char* YCbCr,
+               int w, int h, int quality,
+               unsigned char* dest, int destsize)
+{
+    JSAMPLE* image_buffer = (JSAMPLE*)YCbCr;
+    int      image_width  = w;
+    int      image_height = h;
+
+    struct jpeg_compress_struct cinfo;
+    struct jpeg_error_mgr jerr;
+
+    JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
+    int row_stride;		/* physical row width in image buffer */
+    int jpegsize;
+
+    cinfo.err = jpeg_std_error(&jerr);
+    jpeg_create_compress(&cinfo);
+
+    jpeg_mem_dest(&cinfo, dest, destsize);
+
+    cinfo.image_width = image_width;
+    cinfo.image_height = image_height;
+    cinfo.input_components = 3;		/* # of color components per pixel */
+    cinfo.in_color_space = JCS_YCbCr; /* colorspace of input image */
+
+    jpeg_set_defaults(&cinfo);
+
+    jpeg_set_quality(&cinfo,
+                     quality, TRUE /* limit to baseline-JPEG values */);
+
+    jpeg_start_compress(&cinfo, TRUE);
+
+    row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
+
+    while (cinfo.next_scanline < cinfo.image_height) {
+        row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
+        (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
+    }
+
+    jpeg_finish_compress(&cinfo);
+    jpegsize = jpeg_mem_size(&cinfo);
+
+    jpeg_destroy_compress(&cinfo);
+
+    return jpegsize;
+}
+
+void
+write_jpeg_file(unsigned char* YCbCr, int w, int h, int quality, FILE* outfile)
+{
+    JSAMPLE* image_buffer = (JSAMPLE*)YCbCr;
+    int      image_width  = w;
+    int      image_height = h;
+
+    struct jpeg_compress_struct cinfo;
+    struct jpeg_error_mgr jerr;
+
+    JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
+    int row_stride;		/* physical row width in image buffer */
+
+    cinfo.err = jpeg_std_error(&jerr);
+    jpeg_create_compress(&cinfo);
+
+    jpeg_stdio_dest(&cinfo, outfile);
+
+    cinfo.image_width = image_width;
+    cinfo.image_height = image_height;
+    cinfo.input_components = 3;		/* # of color components per pixel */
+    cinfo.in_color_space = JCS_YCbCr; /* colorspace of input image */
+
+    jpeg_set_defaults(&cinfo);
+
+    jpeg_set_quality(&cinfo,
+                     quality, TRUE /* limit to baseline-JPEG values */);
+    
+    jpeg_start_compress(&cinfo, TRUE);
+
+    row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
+
+    while (cinfo.next_scanline < cinfo.image_height) {
+        row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
+        (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
+    }
+
+    jpeg_finish_compress(&cinfo);
+
+    jpeg_destroy_compress(&cinfo);
+}
+
+#ifdef __cplusplus
+}
+#endif
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/wrppm.c ./Shared/jpeg-6b/wrppm.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/wrppm.c	Mon Dec  1 12:30:41 2003
+++ ./Shared/jpeg-6b/wrppm.c	Wed Dec 31 19:00:00 1969
@@ -1,268 +0,0 @@
-/*
- * wrppm.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to write output images in PPM/PGM format.
- * The extended 2-byte-per-sample raw PPM/PGM formats are supported.
- * The PBMPLUS library is NOT required to compile this software
- * (but it is highly useful as a set of PPM image manipulation programs).
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume output to
- * an ordinary stdio stream.
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef PPM_SUPPORTED
-
-
-/*
- * For 12-bit JPEG data, we either downscale the values to 8 bits
- * (to write standard byte-per-sample PPM/PGM files), or output
- * nonstandard word-per-sample PPM/PGM files.  Downscaling is done
- * if PPM_NORAWWORD is defined (this can be done in the Makefile
- * or in jconfig.h).
- * (When the core library supports data precision reduction, a cleaner
- * implementation will be to ask for that instead.)
- */
-
-#if BITS_IN_JSAMPLE == 8
-#define PUTPPMSAMPLE(ptr,v)  *ptr++ = (char) (v)
-#define BYTESPERSAMPLE 1
-#define PPM_MAXVAL 255
-#else
-#ifdef PPM_NORAWWORD
-#define PUTPPMSAMPLE(ptr,v)  *ptr++ = (char) ((v) >> (BITS_IN_JSAMPLE-8))
-#define BYTESPERSAMPLE 1
-#define PPM_MAXVAL 255
-#else
-/* The word-per-sample format always puts the LSB first. */
-#define PUTPPMSAMPLE(ptr,v)			\
-	{ register int val_ = v;		\
-	  *ptr++ = (char) (val_ & 0xFF);	\
-	  *ptr++ = (char) ((val_ >> 8) & 0xFF);	\
-	}
-#define BYTESPERSAMPLE 2
-#define PPM_MAXVAL ((1<<BITS_IN_JSAMPLE)-1)
-#endif
-#endif
-
-
-/*
- * When JSAMPLE is the same size as char, we can just fwrite() the
- * decompressed data to the PPM or PGM file.  On PCs, in order to make this
- * work the output buffer must be allocated in near data space, because we are
- * assuming small-data memory model wherein fwrite() can't reach far memory.
- * If you need to process very wide images on a PC, you might have to compile
- * in large-memory model, or else replace fwrite() with a putc() loop ---
- * which will be much slower.
- */
-
-
-/* Private version of data destination object */
-
-typedef struct {
-  struct djpeg_dest_struct pub;	/* public fields */
-
-  /* Usually these two pointers point to the same place: */
-  char *iobuffer;		/* fwrite's I/O buffer */
-  JSAMPROW pixrow;		/* decompressor output buffer */
-  size_t buffer_width;		/* width of I/O buffer */
-  JDIMENSION samples_per_row;	/* JSAMPLEs per output row */
-} ppm_dest_struct;
-
-typedef ppm_dest_struct * ppm_dest_ptr;
-
-
-/*
- * Write some pixel data.
- * In this module rows_supplied will always be 1.
- *
- * put_pixel_rows handles the "normal" 8-bit case where the decompressor
- * output buffer is physically the same as the fwrite buffer.
- */
-
-METHODDEF(void)
-put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		JDIMENSION rows_supplied)
-{
-  ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
-
-  (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
-}
-
-
-/*
- * This code is used when we have to copy the data and apply a pixel
- * format translation.  Typically this only happens in 12-bit mode.
- */
-
-METHODDEF(void)
-copy_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		 JDIMENSION rows_supplied)
-{
-  ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
-  register char * bufferptr;
-  register JSAMPROW ptr;
-  register JDIMENSION col;
-
-  ptr = dest->pub.buffer[0];
-  bufferptr = dest->iobuffer;
-  for (col = dest->samples_per_row; col > 0; col--) {
-    PUTPPMSAMPLE(bufferptr, GETJSAMPLE(*ptr++));
-  }
-  (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
-}
-
-
-/*
- * Write some pixel data when color quantization is in effect.
- * We have to demap the color index values to straight data.
- */
-
-METHODDEF(void)
-put_demapped_rgb (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		  JDIMENSION rows_supplied)
-{
-  ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
-  register char * bufferptr;
-  register int pixval;
-  register JSAMPROW ptr;
-  register JSAMPROW color_map0 = cinfo->colormap[0];
-  register JSAMPROW color_map1 = cinfo->colormap[1];
-  register JSAMPROW color_map2 = cinfo->colormap[2];
-  register JDIMENSION col;
-
-  ptr = dest->pub.buffer[0];
-  bufferptr = dest->iobuffer;
-  for (col = cinfo->output_width; col > 0; col--) {
-    pixval = GETJSAMPLE(*ptr++);
-    PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map0[pixval]));
-    PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map1[pixval]));
-    PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map2[pixval]));
-  }
-  (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
-}
-
-
-METHODDEF(void)
-put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		   JDIMENSION rows_supplied)
-{
-  ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
-  register char * bufferptr;
-  register JSAMPROW ptr;
-  register JSAMPROW color_map = cinfo->colormap[0];
-  register JDIMENSION col;
-
-  ptr = dest->pub.buffer[0];
-  bufferptr = dest->iobuffer;
-  for (col = cinfo->output_width; col > 0; col--) {
-    PUTPPMSAMPLE(bufferptr, GETJSAMPLE(color_map[GETJSAMPLE(*ptr++)]));
-  }
-  (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
-}
-
-
-/*
- * Startup: write the file header.
- */
-
-METHODDEF(void)
-start_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  ppm_dest_ptr dest = (ppm_dest_ptr) dinfo;
-
-  /* Emit file header */
-  switch (cinfo->out_color_space) {
-  case JCS_GRAYSCALE:
-    /* emit header for raw PGM format */
-    fprintf(dest->pub.output_file, "P5\n%ld %ld\n%d\n",
-	    (long) cinfo->output_width, (long) cinfo->output_height,
-	    PPM_MAXVAL);
-    break;
-  case JCS_RGB:
-    /* emit header for raw PPM format */
-    fprintf(dest->pub.output_file, "P6\n%ld %ld\n%d\n",
-	    (long) cinfo->output_width, (long) cinfo->output_height,
-	    PPM_MAXVAL);
-    break;
-  default:
-    ERREXIT(cinfo, JERR_PPM_COLORSPACE);
-  }
-}
-
-
-/*
- * Finish up at the end of the file.
- */
-
-METHODDEF(void)
-finish_output_ppm (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  /* Make sure we wrote the output file OK */
-  fflush(dinfo->output_file);
-  if (ferror(dinfo->output_file))
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-}
-
-
-/*
- * The module selection routine for PPM format output.
- */
-
-GLOBAL(djpeg_dest_ptr)
-jinit_write_ppm (j_decompress_ptr cinfo)
-{
-  ppm_dest_ptr dest;
-
-  /* Create module interface object, fill in method pointers */
-  dest = (ppm_dest_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(ppm_dest_struct));
-  dest->pub.start_output = start_output_ppm;
-  dest->pub.finish_output = finish_output_ppm;
-
-  /* Calculate output image dimensions so we can allocate space */
-  jpeg_calc_output_dimensions(cinfo);
-
-  /* Create physical I/O buffer.  Note we make this near on a PC. */
-  dest->samples_per_row = cinfo->output_width * cinfo->out_color_components;
-  dest->buffer_width = dest->samples_per_row * (BYTESPERSAMPLE * SIZEOF(char));
-  dest->iobuffer = (char *) (*cinfo->mem->alloc_small)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width);
-
-  if (cinfo->quantize_colors || BITS_IN_JSAMPLE != 8 ||
-      SIZEOF(JSAMPLE) != SIZEOF(char)) {
-    /* When quantizing, we need an output buffer for colormap indexes
-     * that's separate from the physical I/O buffer.  We also need a
-     * separate buffer if pixel format translation must take place.
-     */
-    dest->pub.buffer = (*cinfo->mem->alloc_sarray)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE,
-       cinfo->output_width * cinfo->output_components, (JDIMENSION) 1);
-    dest->pub.buffer_height = 1;
-    if (! cinfo->quantize_colors)
-      dest->pub.put_pixel_rows = copy_pixel_rows;
-    else if (cinfo->out_color_space == JCS_GRAYSCALE)
-      dest->pub.put_pixel_rows = put_demapped_gray;
-    else
-      dest->pub.put_pixel_rows = put_demapped_rgb;
-  } else {
-    /* We will fwrite() directly from decompressor output buffer. */
-    /* Synthesize a JSAMPARRAY pointer structure */
-    /* Cast here implies near->far pointer conversion on PCs */
-    dest->pixrow = (JSAMPROW) dest->iobuffer;
-    dest->pub.buffer = & dest->pixrow;
-    dest->pub.buffer_height = 1;
-    dest->pub.put_pixel_rows = put_pixel_rows;
-  }
-
-  return (djpeg_dest_ptr) dest;
-}
-
-#endif /* PPM_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/wrrle.c ./Shared/jpeg-6b/wrrle.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/wrrle.c	Mon Dec  1 12:30:42 2003
+++ ./Shared/jpeg-6b/wrrle.c	Wed Dec 31 19:00:00 1969
@@ -1,305 +0,0 @@
-/*
- * wrrle.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to write output images in RLE format.
- * The Utah Raster Toolkit library is required (version 3.1 or later).
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume output to
- * an ordinary stdio stream.
- *
- * Based on code contributed by Mike Lijewski,
- * with updates from Robert Hutchinson.
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef RLE_SUPPORTED
-
-/* rle.h is provided by the Utah Raster Toolkit. */
-
-#include <rle.h>
-
-/*
- * We assume that JSAMPLE has the same representation as rle_pixel,
- * to wit, "unsigned char".  Hence we can't cope with 12- or 16-bit samples.
- */
-
-#if BITS_IN_JSAMPLE != 8
-  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
-#endif
-
-
-/*
- * Since RLE stores scanlines bottom-to-top, we have to invert the image
- * from JPEG's top-to-bottom order.  To do this, we save the outgoing data
- * in a virtual array during put_pixel_row calls, then actually emit the
- * RLE file during finish_output.
- */
-
-
-/*
- * For now, if we emit an RLE color map then it is always 256 entries long,
- * though not all of the entries need be used.
- */
-
-#define CMAPBITS	8
-#define CMAPLENGTH	(1<<(CMAPBITS))
-
-typedef struct {
-  struct djpeg_dest_struct pub; /* public fields */
-
-  jvirt_sarray_ptr image;	/* virtual array to store the output image */
-  rle_map *colormap;	 	/* RLE-style color map, or NULL if none */
-  rle_pixel **rle_row;		/* To pass rows to rle_putrow() */
-
-} rle_dest_struct;
-
-typedef rle_dest_struct * rle_dest_ptr;
-
-/* Forward declarations */
-METHODDEF(void) rle_put_pixel_rows
-    JPP((j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-	 JDIMENSION rows_supplied));
-
-
-/*
- * Write the file header.
- *
- * In this module it's easier to wait till finish_output to write anything.
- */
-
-METHODDEF(void)
-start_output_rle (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  rle_dest_ptr dest = (rle_dest_ptr) dinfo;
-  size_t cmapsize;
-  int i, ci;
-#ifdef PROGRESS_REPORT
-  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-#endif
-
-  /*
-   * Make sure the image can be stored in RLE format.
-   *
-   * - RLE stores image dimensions as *signed* 16 bit integers.  JPEG
-   *   uses unsigned, so we have to check the width.
-   *
-   * - Colorspace is expected to be grayscale or RGB.
-   *
-   * - The number of channels (components) is expected to be 1 (grayscale/
-   *   pseudocolor) or 3 (truecolor/directcolor).
-   *   (could be 2 or 4 if using an alpha channel, but we aren't)
-   */
-
-  if (cinfo->output_width > 32767 || cinfo->output_height > 32767)
-    ERREXIT2(cinfo, JERR_RLE_DIMENSIONS, cinfo->output_width, 
-	     cinfo->output_height);
-
-  if (cinfo->out_color_space != JCS_GRAYSCALE &&
-      cinfo->out_color_space != JCS_RGB)
-    ERREXIT(cinfo, JERR_RLE_COLORSPACE);
-
-  if (cinfo->output_components != 1 && cinfo->output_components != 3)
-    ERREXIT1(cinfo, JERR_RLE_TOOMANYCHANNELS, cinfo->num_components);
-
-  /* Convert colormap, if any, to RLE format. */
-
-  dest->colormap = NULL;
-
-  if (cinfo->quantize_colors) {
-    /* Allocate storage for RLE-style cmap, zero any extra entries */
-    cmapsize = cinfo->out_color_components * CMAPLENGTH * SIZEOF(rle_map);
-    dest->colormap = (rle_map *) (*cinfo->mem->alloc_small)
-      ((j_common_ptr) cinfo, JPOOL_IMAGE, cmapsize);
-    MEMZERO(dest->colormap, cmapsize);
-
-    /* Save away data in RLE format --- note 8-bit left shift! */
-    /* Shifting would need adjustment for JSAMPLEs wider than 8 bits. */
-    for (ci = 0; ci < cinfo->out_color_components; ci++) {
-      for (i = 0; i < cinfo->actual_number_of_colors; i++) {
-        dest->colormap[ci * CMAPLENGTH + i] =
-          GETJSAMPLE(cinfo->colormap[ci][i]) << 8;
-      }
-    }
-  }
-
-  /* Set the output buffer to the first row */
-  dest->pub.buffer = (*cinfo->mem->access_virt_sarray)
-    ((j_common_ptr) cinfo, dest->image, (JDIMENSION) 0, (JDIMENSION) 1, TRUE);
-  dest->pub.buffer_height = 1;
-
-  dest->pub.put_pixel_rows = rle_put_pixel_rows;
-
-#ifdef PROGRESS_REPORT
-  if (progress != NULL) {
-    progress->total_extra_passes++;  /* count file writing as separate pass */
-  }
-#endif
-}
-
-
-/*
- * Write some pixel data.
- *
- * This routine just saves the data away in a virtual array.
- */
-
-METHODDEF(void)
-rle_put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		    JDIMENSION rows_supplied)
-{
-  rle_dest_ptr dest = (rle_dest_ptr) dinfo;
-
-  if (cinfo->output_scanline < cinfo->output_height) {
-    dest->pub.buffer = (*cinfo->mem->access_virt_sarray)
-      ((j_common_ptr) cinfo, dest->image,
-       cinfo->output_scanline, (JDIMENSION) 1, TRUE);
-  }
-}
-
-/*
- * Finish up at the end of the file.
- *
- * Here is where we really output the RLE file.
- */
-
-METHODDEF(void)
-finish_output_rle (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  rle_dest_ptr dest = (rle_dest_ptr) dinfo;
-  rle_hdr header;		/* Output file information */
-  rle_pixel **rle_row, *red, *green, *blue;
-  JSAMPROW output_row;
-  char cmapcomment[80];
-  int row, col;
-  int ci;
-#ifdef PROGRESS_REPORT
-  cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
-#endif
-
-  /* Initialize the header info */
-  header = *rle_hdr_init(NULL);
-  header.rle_file = dest->pub.output_file;
-  header.xmin     = 0;
-  header.xmax     = cinfo->output_width  - 1;
-  header.ymin     = 0;
-  header.ymax     = cinfo->output_height - 1;
-  header.alpha    = 0;
-  header.ncolors  = cinfo->output_components;
-  for (ci = 0; ci < cinfo->output_components; ci++) {
-    RLE_SET_BIT(header, ci);
-  }
-  if (cinfo->quantize_colors) {
-    header.ncmap   = cinfo->out_color_components;
-    header.cmaplen = CMAPBITS;
-    header.cmap    = dest->colormap;
-    /* Add a comment to the output image with the true colormap length. */
-    sprintf(cmapcomment, "color_map_length=%d", cinfo->actual_number_of_colors);
-    rle_putcom(cmapcomment, &header);
-  }
-
-  /* Emit the RLE header and color map (if any) */
-  rle_put_setup(&header);
-
-  /* Now output the RLE data from our virtual array.
-   * We assume here that (a) rle_pixel is represented the same as JSAMPLE,
-   * and (b) we are not on a machine where FAR pointers differ from regular.
-   */
-
-#ifdef PROGRESS_REPORT
-  if (progress != NULL) {
-    progress->pub.pass_limit = cinfo->output_height;
-    progress->pub.pass_counter = 0;
-    (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-  }
-#endif
-
-  if (cinfo->output_components == 1) {
-    for (row = cinfo->output_height-1; row >= 0; row--) {
-      rle_row = (rle_pixel **) (*cinfo->mem->access_virt_sarray)
-        ((j_common_ptr) cinfo, dest->image,
-	 (JDIMENSION) row, (JDIMENSION) 1, FALSE);
-      rle_putrow(rle_row, (int) cinfo->output_width, &header);
-#ifdef PROGRESS_REPORT
-      if (progress != NULL) {
-        progress->pub.pass_counter++;
-        (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-      }
-#endif
-    }
-  } else {
-    for (row = cinfo->output_height-1; row >= 0; row--) {
-      rle_row = (rle_pixel **) dest->rle_row;
-      output_row = * (*cinfo->mem->access_virt_sarray)
-        ((j_common_ptr) cinfo, dest->image,
-	 (JDIMENSION) row, (JDIMENSION) 1, FALSE);
-      red = rle_row[0];
-      green = rle_row[1];
-      blue = rle_row[2];
-      for (col = cinfo->output_width; col > 0; col--) {
-        *red++ = GETJSAMPLE(*output_row++);
-        *green++ = GETJSAMPLE(*output_row++);
-        *blue++ = GETJSAMPLE(*output_row++);
-      }
-      rle_putrow(rle_row, (int) cinfo->output_width, &header);
-#ifdef PROGRESS_REPORT
-      if (progress != NULL) {
-        progress->pub.pass_counter++;
-        (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
-      }
-#endif
-    }
-  }
-
-#ifdef PROGRESS_REPORT
-  if (progress != NULL)
-    progress->completed_extra_passes++;
-#endif
-
-  /* Emit file trailer */
-  rle_puteof(&header);
-  fflush(dest->pub.output_file);
-  if (ferror(dest->pub.output_file))
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-}
-
-
-/*
- * The module selection routine for RLE format output.
- */
-
-GLOBAL(djpeg_dest_ptr)
-jinit_write_rle (j_decompress_ptr cinfo)
-{
-  rle_dest_ptr dest;
-
-  /* Create module interface object, fill in method pointers */
-  dest = (rle_dest_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-                                  SIZEOF(rle_dest_struct));
-  dest->pub.start_output = start_output_rle;
-  dest->pub.finish_output = finish_output_rle;
-
-  /* Calculate output image dimensions so we can allocate space */
-  jpeg_calc_output_dimensions(cinfo);
-
-  /* Allocate a work array for output to the RLE library. */
-  dest->rle_row = (*cinfo->mem->alloc_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE,
-     cinfo->output_width, (JDIMENSION) cinfo->output_components);
-
-  /* Allocate a virtual array to hold the image. */
-  dest->image = (*cinfo->mem->request_virt_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
-     (JDIMENSION) (cinfo->output_width * cinfo->output_components),
-     cinfo->output_height, (JDIMENSION) 1);
-
-  return (djpeg_dest_ptr) dest;
-}
-
-#endif /* RLE_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/jpeg-6b/wrtarga.c ./Shared/jpeg-6b/wrtarga.c
--- ../Tekkotsu_2.3/Shared/jpeg-6b/wrtarga.c	Mon Dec  1 12:30:42 2003
+++ ./Shared/jpeg-6b/wrtarga.c	Wed Dec 31 19:00:00 1969
@@ -1,253 +0,0 @@
-/*
- * wrtarga.c
- *
- * Copyright (C) 1991-1996, Thomas G. Lane.
- * This file is part of the Independent JPEG Group's software.
- * For conditions of distribution and use, see the accompanying README file.
- *
- * This file contains routines to write output images in Targa format.
- *
- * These routines may need modification for non-Unix environments or
- * specialized applications.  As they stand, they assume output to
- * an ordinary stdio stream.
- *
- * Based on code contributed by Lee Daniel Crocker.
- */
-
-#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
-
-#ifdef TARGA_SUPPORTED
-
-
-/*
- * To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
- * This is not yet implemented.
- */
-
-#if BITS_IN_JSAMPLE != 8
-  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
-#endif
-
-/*
- * The output buffer needs to be writable by fwrite().  On PCs, we must
- * allocate the buffer in near data space, because we are assuming small-data
- * memory model, wherein fwrite() can't reach far memory.  If you need to
- * process very wide images on a PC, you might have to compile in large-memory
- * model, or else replace fwrite() with a putc() loop --- which will be much
- * slower.
- */
-
-
-/* Private version of data destination object */
-
-typedef struct {
-  struct djpeg_dest_struct pub;	/* public fields */
-
-  char *iobuffer;		/* physical I/O buffer */
-  JDIMENSION buffer_width;	/* width of one row */
-} tga_dest_struct;
-
-typedef tga_dest_struct * tga_dest_ptr;
-
-
-LOCAL(void)
-write_header (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, int num_colors)
-/* Create and write a Targa header */
-{
-  char targaheader[18];
-
-  /* Set unused fields of header to 0 */
-  MEMZERO(targaheader, SIZEOF(targaheader));
-
-  if (num_colors > 0) {
-    targaheader[1] = 1;		/* color map type 1 */
-    targaheader[5] = (char) (num_colors & 0xFF);
-    targaheader[6] = (char) (num_colors >> 8);
-    targaheader[7] = 24;	/* 24 bits per cmap entry */
-  }
-
-  targaheader[12] = (char) (cinfo->output_width & 0xFF);
-  targaheader[13] = (char) (cinfo->output_width >> 8);
-  targaheader[14] = (char) (cinfo->output_height & 0xFF);
-  targaheader[15] = (char) (cinfo->output_height >> 8);
-  targaheader[17] = 0x20;	/* Top-down, non-interlaced */
-
-  if (cinfo->out_color_space == JCS_GRAYSCALE) {
-    targaheader[2] = 3;		/* image type = uncompressed gray-scale */
-    targaheader[16] = 8;	/* bits per pixel */
-  } else {			/* must be RGB */
-    if (num_colors > 0) {
-      targaheader[2] = 1;	/* image type = colormapped RGB */
-      targaheader[16] = 8;
-    } else {
-      targaheader[2] = 2;	/* image type = uncompressed RGB */
-      targaheader[16] = 24;
-    }
-  }
-
-  if (JFWRITE(dinfo->output_file, targaheader, 18) != (size_t) 18)
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-}
-
-
-/*
- * Write some pixel data.
- * In this module rows_supplied will always be 1.
- */
-
-METHODDEF(void)
-put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		JDIMENSION rows_supplied)
-/* used for unquantized full-color output */
-{
-  tga_dest_ptr dest = (tga_dest_ptr) dinfo;
-  register JSAMPROW inptr;
-  register char * outptr;
-  register JDIMENSION col;
-
-  inptr = dest->pub.buffer[0];
-  outptr = dest->iobuffer;
-  for (col = cinfo->output_width; col > 0; col--) {
-    outptr[0] = (char) GETJSAMPLE(inptr[2]); /* RGB to BGR order */
-    outptr[1] = (char) GETJSAMPLE(inptr[1]);
-    outptr[2] = (char) GETJSAMPLE(inptr[0]);
-    inptr += 3, outptr += 3;
-  }
-  (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
-}
-
-METHODDEF(void)
-put_gray_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-	       JDIMENSION rows_supplied)
-/* used for grayscale OR quantized color output */
-{
-  tga_dest_ptr dest = (tga_dest_ptr) dinfo;
-  register JSAMPROW inptr;
-  register char * outptr;
-  register JDIMENSION col;
-
-  inptr = dest->pub.buffer[0];
-  outptr = dest->iobuffer;
-  for (col = cinfo->output_width; col > 0; col--) {
-    *outptr++ = (char) GETJSAMPLE(*inptr++);
-  }
-  (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
-}
-
-
-/*
- * Write some demapped pixel data when color quantization is in effect.
- * For Targa, this is only applied to grayscale data.
- */
-
-METHODDEF(void)
-put_demapped_gray (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
-		   JDIMENSION rows_supplied)
-{
-  tga_dest_ptr dest = (tga_dest_ptr) dinfo;
-  register JSAMPROW inptr;
-  register char * outptr;
-  register JSAMPROW color_map0 = cinfo->colormap[0];
-  register JDIMENSION col;
-
-  inptr = dest->pub.buffer[0];
-  outptr = dest->iobuffer;
-  for (col = cinfo->output_width; col > 0; col--) {
-    *outptr++ = (char) GETJSAMPLE(color_map0[GETJSAMPLE(*inptr++)]);
-  }
-  (void) JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width);
-}
-
-
-/*
- * Startup: write the file header.
- */
-
-METHODDEF(void)
-start_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  tga_dest_ptr dest = (tga_dest_ptr) dinfo;
-  int num_colors, i;
-  FILE *outfile;
-
-  if (cinfo->out_color_space == JCS_GRAYSCALE) {
-    /* Targa doesn't have a mapped grayscale format, so we will */
-    /* demap quantized gray output.  Never emit a colormap. */
-    write_header(cinfo, dinfo, 0);
-    if (cinfo->quantize_colors)
-      dest->pub.put_pixel_rows = put_demapped_gray;
-    else
-      dest->pub.put_pixel_rows = put_gray_rows;
-  } else if (cinfo->out_color_space == JCS_RGB) {
-    if (cinfo->quantize_colors) {
-      /* We only support 8-bit colormap indexes, so only 256 colors */
-      num_colors = cinfo->actual_number_of_colors;
-      if (num_colors > 256)
-	ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, num_colors);
-      write_header(cinfo, dinfo, num_colors);
-      /* Write the colormap.  Note Targa uses BGR byte order */
-      outfile = dest->pub.output_file;
-      for (i = 0; i < num_colors; i++) {
-	putc(GETJSAMPLE(cinfo->colormap[2][i]), outfile);
-	putc(GETJSAMPLE(cinfo->colormap[1][i]), outfile);
-	putc(GETJSAMPLE(cinfo->colormap[0][i]), outfile);
-      }
-      dest->pub.put_pixel_rows = put_gray_rows;
-    } else {
-      write_header(cinfo, dinfo, 0);
-      dest->pub.put_pixel_rows = put_pixel_rows;
-    }
-  } else {
-    ERREXIT(cinfo, JERR_TGA_COLORSPACE);
-  }
-}
-
-
-/*
- * Finish up at the end of the file.
- */
-
-METHODDEF(void)
-finish_output_tga (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
-{
-  /* Make sure we wrote the output file OK */
-  fflush(dinfo->output_file);
-  if (ferror(dinfo->output_file))
-    ERREXIT(cinfo, JERR_FILE_WRITE);
-}
-
-
-/*
- * The module selection routine for Targa format output.
- */
-
-GLOBAL(djpeg_dest_ptr)
-jinit_write_targa (j_decompress_ptr cinfo)
-{
-  tga_dest_ptr dest;
-
-  /* Create module interface object, fill in method pointers */
-  dest = (tga_dest_ptr)
-      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				  SIZEOF(tga_dest_struct));
-  dest->pub.start_output = start_output_tga;
-  dest->pub.finish_output = finish_output_tga;
-
-  /* Calculate output image dimensions so we can allocate space */
-  jpeg_calc_output_dimensions(cinfo);
-
-  /* Create I/O buffer.  Note we make this near on a PC. */
-  dest->buffer_width = cinfo->output_width * cinfo->output_components;
-  dest->iobuffer = (char *)
-    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
-				(size_t) (dest->buffer_width * SIZEOF(char)));
-
-  /* Create decompressor output buffer. */
-  dest->pub.buffer = (*cinfo->mem->alloc_sarray)
-    ((j_common_ptr) cinfo, JPOOL_IMAGE, dest->buffer_width, (JDIMENSION) 1);
-  dest->pub.buffer_height = 1;
-
-  return (djpeg_dest_ptr) dest;
-}
-
-#endif /* TARGA_SUPPORTED */
diff -urdN ../Tekkotsu_2.3/Shared/newmat/CVS/Entries ./Shared/newmat/CVS/Entries
--- ../Tekkotsu_2.3/Shared/newmat/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,38 @@
+/Makefile/1.12/Wed Aug 10 02:20:09 2005//Ttekkotsu-2_4
+/bandmat.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/boolean.h/1.1/Wed Jun 16 21:16:40 2004//Ttekkotsu-2_4
+/cholesky.cpp/1.2/Tue Jul 26 03:21:58 2005//Ttekkotsu-2_4
+/controlw.h/1.1/Wed Jun 16 21:16:40 2004//Ttekkotsu-2_4
+/evalue.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/fft.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/hholder.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/include.h/1.2/Fri Jul  2 00:19:33 2004//Ttekkotsu-2_4
+/jacobi.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/myexcept.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/myexcept.h/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newfft.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/newmat.h/1.4/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/newmat1.cpp/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmat2.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/newmat3.cpp/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmat4.cpp/1.2/Fri Jul 23 21:31:20 2004//Ttekkotsu-2_4
+/newmat5.cpp/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmat6.cpp/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmat7.cpp/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmat8.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/newmat9.cpp/1.5/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/newmatap.h/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmatex.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/newmatio.h/1.2/Wed Dec 15 03:56:28 2004//Ttekkotsu-2_4
+/newmatnl.cpp/1.3/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/newmatnl.h/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmatrc.h/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/newmatrm.cpp/1.2/Tue Jul 26 03:21:58 2005//Ttekkotsu-2_4
+/newmatrm.h/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/precisio.h/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/readme.txt/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/sort.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+/submat.cpp/1.1/Wed Jun 16 21:16:41 2004//Ttekkotsu-2_4
+/svd.cpp/1.2/Tue Jul 26 03:21:59 2005//Ttekkotsu-2_4
+D/docs////
+D/extra////
diff -urdN ../Tekkotsu_2.3/Shared/newmat/CVS/Repository ./Shared/newmat/CVS/Repository
--- ../Tekkotsu_2.3/Shared/newmat/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/CVS/Repository	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Tekkotsu/Shared/newmat
diff -urdN ../Tekkotsu_2.3/Shared/newmat/CVS/Root ./Shared/newmat/CVS/Root
--- ../Tekkotsu_2.3/Shared/newmat/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/CVS/Root	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Shared/newmat/CVS/Tag ./Shared/newmat/CVS/Tag
--- ../Tekkotsu_2.3/Shared/newmat/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/CVS/Tag	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Shared/newmat/Makefile ./Shared/newmat/Makefile
--- ../Tekkotsu_2.3/Shared/newmat/Makefile	Tue Nov  9 16:26:13 2004
+++ ./Shared/newmat/Makefile	Tue Aug  9 22:20:09 2005
@@ -7,9 +7,7 @@
 $(error An error has occured, TEKKOTSU_ENVIRONMENT_CONFIGURATION was not defined)
 endif
 include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
-FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(FILTERSYSWARN))
-COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(COLORFILT))
-BUILDDIR=$(patsubst $(TEKKOTSU_ROOT)/%,../../%,$(TK_BD)/Shared/newmat)
+BUILDDIR=$(TK_LIB_BD)/Shared/newmat
 SRCSUFFIX=.cpp
 
 # You may need to adjust these cc options:
@@ -17,6 +15,7 @@
           -Wall -W -Wlarger-than-8192 -Wpointer-arith -Wcast-qual \
           -Woverloaded-virtual -Wdeprecated -Wnon-virtual-dtor \
           -O3 -frename-registers -fomit-frame-pointer -fno-common \
+          -DWANT_MATH -DWANT_STREAM -DWANT_STRING
 
 #          -Wshadow -Weffc++
 
@@ -34,8 +33,15 @@
 # file rename command
 MV= mv
 
+# if precompiled headers are enabled by the Environment.conf, then
+# this file will be created with the names of all current .h files
+# and then precompiled
+PCH=all.h
+
 # End of configurable options.
 
+INCLUDE_PCH:=$(if $(TEKKOTSU_PCH),-include $(BUILDDIR)/$(PCH))
+
 # source files:
 LIBSOURCES= bandmat.cpp cholesky.cpp evalue.cpp fft.cpp hholder.cpp \
             jacobi.cpp myexcept.cpp newfft.cpp newmat1.cpp newmat2.cpp \
@@ -45,9 +51,9 @@
 
 SOURCES= $(LIBSOURCES)
 
-# files included by source files
-INCLUDES= boolean.h include.h newmatap.h newmatio.h newmatrc.h precisio.h \
-          controlw.h myexcept.h newmat.h newmatnl.h newmatrm.h solution.h
+# files included by the precompiled header (not necessarily all headers... some give trouble)
+INCLUDES= include.h newmat.h newmatap.h newmatrc.h \
+          controlw.h myexcept.h newmatnl.h precisio.h
 
 LIBOBJECTS= $(addprefix $(BUILDDIR)/,$(LIBSOURCES:.cpp=.o))
 # newmat1.o newmat2.o newmat3.o newmat4.o newmat5.o newmat6.o newmat7.o newmat8.o newmat9.o newmatex.o bandmat.o submat.o myexcept.o cholesky.o evalue.o fft.o hholder.o jacobi.o newfft.o sort.o svd.o newmatrm.o newmatnl.o
@@ -63,16 +69,34 @@
 	@$(AR2) $@
 
 clean:
-	$(RM) *.o *.a *.log core
+	$(RM) *.o *.a *.log core $(PCH)
+	$(RM) -r $(BUILDDIR)
 
-%.o:
+%:: %.o;
+
+%.o: $(if $(TEKKOTSU_PCH),$(BUILDDIR)/$(PCH).gch)
 	@mkdir -p $(dir $@)
 	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(BUILDDIR)/%,%,$@)); \
 	echo "Compiling NEWMAT::$$src... (Reduced warnings)"; \
-	$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+	$(CXX) $(CXXFLAGS) $(INCLUDE_PCH) -o $@ -c $$src > $*.log 2>&1; \
 	retval=$$?; \
 	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
 	test $$retval -eq 0;
+
+$(BUILDDIR)/$(PCH).gch: $(PCH)
+	@mkdir -p $(dir $@)
+	@src=$(PCH); \
+	echo "Pre-compiling NEWMAT::$$src... (Reduced warnings)"; \
+	$(CXX) $(CXXFLAGS) -x c++-header -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0;
+
+$(PCH): $(INCLUDES)
+	@rm -f $@;
+	@for x in $^ ; do \
+		echo "#include \"$$x\"" >> $@; \
+	done
 
 $(BUILDDIR)/newmat1.o:     	newmat1.cpp newmat.h include.h myexcept.h
 
diff -urdN ../Tekkotsu_2.3/Shared/newmat/bandmat.cpp ./Shared/newmat/bandmat.cpp
--- ../Tekkotsu_2.3/Shared/newmat/bandmat.cpp	Wed Jun 16 17:16:40 2004
+++ ./Shared/newmat/bandmat.cpp	Mon Jul 25 23:21:59 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4,9: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH                    // include.h will get math fns
+#endif
 
 //#define WANT_STREAM
 
diff -urdN ../Tekkotsu_2.3/Shared/newmat/cholesky.cpp ./Shared/newmat/cholesky.cpp
--- ../Tekkotsu_2.3/Shared/newmat/cholesky.cpp	Wed Jun 16 17:16:40 2004
+++ ./Shared/newmat/cholesky.cpp	Mon Jul 25 23:21:58 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 //#define WANT_STREAM
 
 #include "include.h"
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Entries ./Shared/newmat/docs/CVS/Entries
--- ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,3 @@
+/nm11.htm/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/rbd.css/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+D/images////
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Repository ./Shared/newmat/docs/CVS/Repository
--- ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/CVS/Repository	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Tekkotsu/Shared/newmat/docs
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Root ./Shared/newmat/docs/CVS/Root
--- ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/CVS/Root	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Tag ./Shared/newmat/docs/CVS/Tag
--- ../Tekkotsu_2.3/Shared/newmat/docs/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/CVS/Tag	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Entries ./Shared/newmat/docs/images/CVS/Entries
--- ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/images/CVS/Entries	Wed Aug 10 11:03:20 2005
@@ -0,0 +1,2 @@
+/add_time.png/1.1/Wed Jun 16 21:16:45 2004/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Repository ./Shared/newmat/docs/images/CVS/Repository
--- ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/images/CVS/Repository	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Tekkotsu/Shared/newmat/docs/images
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Root ./Shared/newmat/docs/images/CVS/Root
--- ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/images/CVS/Root	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Tag ./Shared/newmat/docs/images/CVS/Tag
--- ../Tekkotsu_2.3/Shared/newmat/docs/images/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/docs/images/CVS/Tag	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Shared/newmat/evalue.cpp ./Shared/newmat/evalue.cpp
--- ../Tekkotsu_2.3/Shared/newmat/evalue.cpp	Wed Jun 16 17:16:40 2004
+++ ./Shared/newmat/evalue.cpp	Mon Jul 25 23:21:59 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "include.h"
 #include "newmatap.h"
diff -urdN ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Entries ./Shared/newmat/extra/CVS/Entries
--- ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/extra/CVS/Entries	Wed Aug 10 11:03:20 2005
@@ -0,0 +1,48 @@
+/example.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/example.txt/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/garch.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/garch.dat/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/garch.txt/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/newmat.lfl/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nl_ex.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nl_ex.txt/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_b55.mak/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_b56.mak/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_cc.mak/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_gnu.mak/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_i5.mak/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_il5.mak/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_m6.mak/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/nm_targ.txt/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/sl_ex.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/sl_ex.txt/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/solution.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/solution.h/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/test_exc.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/test_exc.txt/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt.h/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt.txt/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt1.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt2.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt3.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt4.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt5.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt6.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt7.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt8.cpp/1.1/Wed Jun 16 21:16:45 2004//Ttekkotsu-2_4
+/tmt9.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmta.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtb.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtc.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtd.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmte.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtf.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtg.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmth.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmti.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtj.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtk.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtl.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+/tmtm.cpp/1.1/Wed Jun 16 21:16:46 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Repository ./Shared/newmat/extra/CVS/Repository
--- ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/extra/CVS/Repository	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Tekkotsu/Shared/newmat/extra
diff -urdN ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Root ./Shared/newmat/extra/CVS/Root
--- ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/extra/CVS/Root	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Tag ./Shared/newmat/extra/CVS/Tag
--- ../Tekkotsu_2.3/Shared/newmat/extra/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Shared/newmat/extra/CVS/Tag	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Shared/newmat/fft.cpp ./Shared/newmat/fft.cpp
--- ../Tekkotsu_2.3/Shared/newmat/fft.cpp	Wed Jun 16 17:16:40 2004
+++ ./Shared/newmat/fft.cpp	Mon Jul 25 23:21:59 2005
@@ -3,7 +3,9 @@
 // Copyright (C) 1991,2,3,4,8: R B Davies
 
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 // #define WANT_STREAM
 
 #include "include.h"
diff -urdN ../Tekkotsu_2.3/Shared/newmat/hholder.cpp ./Shared/newmat/hholder.cpp
--- ../Tekkotsu_2.3/Shared/newmat/hholder.cpp	Wed Jun 16 17:16:40 2004
+++ ./Shared/newmat/hholder.cpp	Mon Jul 25 23:21:59 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 //#define WANT_STREAM
 
 #include "include.h"
diff -urdN ../Tekkotsu_2.3/Shared/newmat/jacobi.cpp ./Shared/newmat/jacobi.cpp
--- ../Tekkotsu_2.3/Shared/newmat/jacobi.cpp	Wed Jun 16 17:16:40 2004
+++ ./Shared/newmat/jacobi.cpp	Mon Jul 25 23:21:59 2005
@@ -5,8 +5,9 @@
 
 //#define WANT_STREAM
 
-
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "include.h"
 #include "newmatap.h"
diff -urdN ../Tekkotsu_2.3/Shared/newmat/myexcept.cpp ./Shared/newmat/myexcept.cpp
--- ../Tekkotsu_2.3/Shared/newmat/myexcept.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/myexcept.cpp	Mon Jul 25 23:21:59 2005
@@ -3,8 +3,12 @@
 // Copyright (C) 1993,4,6: R B Davies
 
 
+#ifndef WANT_STREAM
 #define WANT_STREAM                    // include.h will get stream fns
+#endif
+#ifndef WANT_STRING
 #define WANT_STRING
+#endif
 
 #include "include.h"                   // include standard files
 
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newfft.cpp ./Shared/newmat/newfft.cpp
--- ../Tekkotsu_2.3/Shared/newmat/newfft.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/newfft.cpp	Mon Jul 25 23:21:59 2005
@@ -91,9 +91,13 @@
 //    IN X, AND THE SINE TRANSFORM IN Y.
 
 
+#ifndef WANT_STREAM
 #define WANT_STREAM
+#endif
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "newmatap.h"
 
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newmat.h ./Shared/newmat/newmat.h
--- ../Tekkotsu_2.3/Shared/newmat/newmat.h	Fri Jul 23 17:31:20 2004
+++ ./Shared/newmat/newmat.h	Mon Jul 25 23:21:59 2005
@@ -940,7 +940,7 @@
    bool d;
    bool sing;
    void ludcmp();
-   void operator=(const CroutMatrix& m) {}     // not allowed
+   void operator=(const CroutMatrix& /*m*/) {}     // not allowed
 public:
    CroutMatrix(const BaseMatrix&);
    MatrixType Type() const;
@@ -1160,7 +1160,7 @@
    int storage2;
    void ludcmp();
    int m1,m2;                                   // lower and upper
-   void operator=(const BandLUMatrix& m) {}     // no allowed
+   void operator=(const BandLUMatrix& /*m*/) {}     // no allowed
 public:
    BandLUMatrix(const BaseMatrix&);
    MatrixType Type() const;
@@ -1273,6 +1273,8 @@
    friend class GeneralMatrix;
    friend class GenericMatrix;
 public:
+   MultipliedMatrix(const MultipliedMatrix& mm) // needed a copy constructor to silence gcc4 warning
+      : BaseMatrix(mm), bm1(mm.bm1),bm2(mm.bm2) {}
    ~MultipliedMatrix() {}
    GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp);
    MatrixBandWidth BandWidth() const;
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newmat2.cpp ./Shared/newmat/newmat2.cpp
--- ../Tekkotsu_2.3/Shared/newmat/newmat2.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/newmat2.cpp	Mon Jul 25 23:21:59 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "include.h"
 
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newmat8.cpp ./Shared/newmat/newmat8.cpp
--- ../Tekkotsu_2.3/Shared/newmat/newmat8.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/newmat8.cpp	Mon Jul 25 23:21:59 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4,8: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "include.h"
 
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newmat9.cpp ./Shared/newmat/newmat9.cpp
--- ../Tekkotsu_2.3/Shared/newmat/newmat9.cpp	Thu Dec 16 19:32:36 2004
+++ ./Shared/newmat/newmat9.cpp	Mon Jul 25 23:21:59 2005
@@ -3,13 +3,16 @@
 // Copyright (C) 1991,2,3,4: R B Davies
 
 
+#ifndef WANT_STREAM
 #define WANT_STREAM
+#endif
 
 #include "include.h"
 
 #include "newmat.h"
 #include "newmatio.h"
 #include "newmatrc.h"
+#include <iomanip>
 
 #ifdef use_namespace
 namespace NEWMAT {
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newmatex.cpp ./Shared/newmat/newmatex.cpp
--- ../Tekkotsu_2.3/Shared/newmat/newmatex.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/newmatex.cpp	Mon Jul 25 23:21:59 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1992,3,4,7: R B Davies
 
+#ifndef WANT_STREAM
 #define WANT_STREAM                  // include.h will get stream fns
+#endif
 
 #include "include.h"                 // include standard files
 #include "newmat.h"
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newmatnl.cpp ./Shared/newmat/newmatnl.cpp
--- ../Tekkotsu_2.3/Shared/newmat/newmatnl.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/newmatnl.cpp	Mon Jul 25 23:21:59 2005
@@ -3,11 +3,17 @@
 // Copyright (C) 1993,4,5,6: R B Davies
 
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
+
+#ifndef WANT_STREAM
 #define WANT_STREAM
+#endif
 
 #include "newmatap.h"
 #include "newmatnl.h"
+#include <iomanip>
 
 #ifdef use_namespace
 namespace NEWMAT {
diff -urdN ../Tekkotsu_2.3/Shared/newmat/newmatrm.cpp ./Shared/newmat/newmatrm.cpp
--- ../Tekkotsu_2.3/Shared/newmat/newmatrm.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/newmatrm.cpp	Mon Jul 25 23:21:58 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "newmat.h"
 #include "newmatrm.h"
diff -urdN ../Tekkotsu_2.3/Shared/newmat/sort.cpp ./Shared/newmat/sort.cpp
--- ../Tekkotsu_2.3/Shared/newmat/sort.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/sort.cpp	Mon Jul 25 23:21:59 2005
@@ -2,7 +2,9 @@
 
 // Copyright (C) 1991,2,3,4: R B Davies
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "include.h"
 
diff -urdN ../Tekkotsu_2.3/Shared/newmat/svd.cpp ./Shared/newmat/svd.cpp
--- ../Tekkotsu_2.3/Shared/newmat/svd.cpp	Wed Jun 16 17:16:41 2004
+++ ./Shared/newmat/svd.cpp	Mon Jul 25 23:21:59 2005
@@ -3,7 +3,9 @@
 // Copyright (C) 1991,2,3,4,5: R B Davies
 // Updated 17 July, 1995
 
+#ifndef WANT_MATH
 #define WANT_MATH
+#endif
 
 #include "include.h"
 #include "newmatap.h"
diff -urdN ../Tekkotsu_2.3/Shared/plist.cc ./Shared/plist.cc
--- ../Tekkotsu_2.3/Shared/plist.cc	Wed Dec 31 19:00:00 1969
+++ ./Shared/plist.cc	Wed Jul 27 01:58:24 2005
@@ -0,0 +1,414 @@
+#include "plist.h"
+#include <libxml/xmlmemory.h>
+#include <libxml/parser.h>
+#include <iomanip>
+
+using namespace std;
+
+namespace plist {
+
+	ObjectBase::ObjectBase()
+	  : XMLLoadSave()
+	{}
+	
+	ObjectBase::~ObjectBase() {}
+	
+	void ObjectBase::setParseTree(xmlDoc * doc) const {
+		XMLLoadSave::setParseTree(doc);
+		if(xmldocument==NULL)
+			return;
+		xmlNodePtr cur = xmlNewNode(NULL,(const xmlChar*)"plist");
+		xmlNewProp(cur,(const xmlChar*)"version",(const xmlChar*)"1.0");
+		xmlDocSetRootElement(xmldocument,cur);
+		xmlCreateIntSubset(xmldocument,(const xmlChar*)"plist",(const xmlChar*)"-//Apple Computer//DTD PLIST 1.0//EN",(const xmlChar*)"http://www.apple.com/DTDs/PropertyList-1.0.dtd");
+	}
+	
+	xmlNode* ObjectBase::FindRootXMLElement(xmlDoc* doc) const {
+		if(doc==NULL)
+			return NULL;
+		xmlNode* root=XMLLoadSave::FindRootXMLElement(doc);
+		string filename;
+		if(doc->name!=NULL && doc->name[0]!='\0') {
+			filename="document '";
+			filename+=doc->name;
+			filename+="' ";
+		}
+		if (root == NULL)
+			throw bad_format(root,"Error: plist read empty document");
+		if (xmlStrcmp(root->name, (const xmlChar *)"plist"))
+			throw bad_format(root,"Error: plist read document of the wrong type, root node != plist");
+		if (!xmlHasProp(root,(const xmlChar*)"version"))
+			cerr << "Warning: plist " << filename << "does not carry version number, assuming 1.0" << endl;
+		else {
+			xmlChar* strv=xmlGetProp(root,(const xmlChar*)"version");
+			double version=strtod((const char*)strv,NULL);
+			if(version>1.0)
+				cerr << "WARNING: plist " << filename << "is version " << strv << ", this software only knows 1.0.  Trying anyway..." << endl;
+			if(version==0)
+				cerr << "WARNING: plist " << filename << "seems to have invalid version '" << strv << "', this software only knows 1.0.  Trying anyway..." << endl;
+			xmlFree(strv);
+		}
+		
+		// find first element node within the plist
+		xmlNode* cur=root->children;
+		while(cur!=NULL && cur->type!=XML_ELEMENT_NODE)
+			cur=cur->next;
+		if(cur==NULL) //empty plist
+			cur = xmlNewChild(root,NULL,(const xmlChar*)"",NULL);
+		return cur;
+	}
+	
+	int ObjectBase::xStrEqual(const xChar* a, const xChar* b) {
+		return xmlStrEqual(a,b);
+	}
+	int ObjectBase::xStrCaseEqual(const xChar* a, const xChar* b) {
+		return !xmlStrcasecmp(a,b);
+	}
+	ObjectBase::xChar* ObjectBase::xNodeGetContent(xmlNode* node) {
+		return xmlNodeGetContent(node);
+	}
+	void ObjectBase::xNodeSetContent(xmlNode* node, const xChar* content) {
+		xmlNodeSetContent(node,content);
+	}
+	const ObjectBase::xChar* ObjectBase::xNodeGetName(xmlNode* node) {
+		return node->name;
+	}
+	bool ObjectBase::xNodeHasName(xmlNode* node, const char* name) {
+		return xmlStrEqual(node->name,(const xmlChar*)name);
+	}
+	void ObjectBase::xNodeSetName(xmlNode* node, const xChar* name) {
+		xmlNodeSetName(node,name);
+	}
+	xmlAttr* ObjectBase::xHasProperty(xmlNode* node, const xChar* name) {
+		return xmlHasProp(node,name);
+	}
+	ObjectBase::xChar* ObjectBase::xGetProperty(xmlNode* node, const xChar* name) {
+		return xmlGetProp(node,name);
+	}
+	long ObjectBase::xGetLineNo(xmlNode* node) {
+		return xmlGetLineNo(node);
+	}
+	void ObjectBase::xFree(void* ptr) {
+		xmlFree(ptr);
+	}
+
+	Dictionary::~Dictionary() {
+		delete dictionaryListeners;
+		dictionaryListeners=NULL;
+	}
+
+	void Dictionary::addEntry(const std::string& name, ObjectBase& val) {
+		dict_t::iterator it=dict.find(name);
+		if(it!=dict.end()) {
+			cerr << "Warning: addEntry("<<name<<","<<val<<") conflicts with previous addEntry("<<name<<","<<val<<")"<<endl;
+			cerr << "         (use setEntry() if you expect you might need to overwrite)" << endl;
+			it->second=&val;
+			return;
+		}
+		dict[name]=&val;
+	}
+
+	void Dictionary::addEntry(const std::string& name, ObjectBase& val, const std::string& comment) {
+		comments[name]=comment;
+		dict_t::iterator it=dict.find(name);
+		if(it!=dict.end()) {
+			cerr << "Warning: addEntry("<<name<<","<<val<<") conflicts with previous addEntry("<<name<<","<<val<<")"<<endl;
+			cerr << "         (use setEntry() if you expect you might need to overwrite)" << endl;
+			it->second=&val;
+			return;
+		}
+		dict[name]=&val;
+	}
+	
+	const std::string& Dictionary::getComment(const std::string& name) const {
+		comments_t::const_iterator it=comments.find(name);
+		static const std::string empty;
+		return (it!=comments.end()) ? it->second : empty;
+	}
+
+	ObjectBase* Dictionary::findEntry(const std::string& name) const {
+		//do we have a key with this name?
+		dict_t::const_iterator it=dict.find(name);
+		if(it!=dict.end())
+			return it->second; //yes, return it
+		
+		//perhaps there's a sub-dictionary, separated by '.'
+		size_t p=name.find(".");
+		if(p==string::npos)
+			return NULL; //no, '.'s found -- go away
+		it=dict.find(name.substr(0,p));
+		if(it==dict.end())
+			return NULL; //no entry matching prefix -- go away
+		const Dictionary* d=dynamic_cast<const Dictionary*>(it->second);
+		if(d==NULL)
+			return NULL; //matching prefix is not a dictionary -- go away
+		
+		//found a matching sub-dictionary, have it find the rest recursively
+		return d->findEntry(name.substr(p+1));
+	}
+
+	void Dictionary::LoadXML(xmlNode* node) {
+		//check if our node has been set to NULL (invalid or not found)
+		if(node==NULL)
+			return;
+		
+		std::string comment;
+		
+		//process children nodes
+		for(xmlNode* cur = skipToElement(node->children,comment); cur!=NULL; cur = skipToElement(cur->next,comment)) {
+						
+			//find the next key node
+			xmlNode * k=cur;
+			if(xmlStrcmp(k->name, (const xmlChar *)"key"))
+				throw bad_format(k,"Dictionary format error: expect data in pairs of key and value (two values found in a row)");
+			cur=skipToElement(cur->next);
+			
+			//find the following value (non-key) node
+			xmlNode * v=cur;
+			if(v==NULL)
+				throw bad_format(cur,"Dictionary format error: expect data in pairs of key and value (dictionary ended with hanging key)");
+			if(!xmlStrcmp(v->name, (const xmlChar *)"key"))
+				throw bad_format(v,"Dictionary format error: expect data in pairs of key and value (two keys found in a row)");
+			
+			//find corresponding entry
+			xmlChar* cont=xmlNodeGetContent(k);
+			string key=(const char*)cont;
+			xmlFree(cont);
+			dict_t::const_iterator it=dict.find(key);
+			if(it==dict.end()) {
+				if(warnUnused)
+					cerr << "Warning: reading plist dictionary, key '" << key << "' does not match a registered variable.  Ignoring..." << endl;
+				continue;
+			}
+			if(comment.size()!=0)
+				setComment(key,comment);
+			it->second->LoadXML(v);
+		}
+	}
+	
+	void Dictionary::SaveXML(xmlNode* node) const {
+		//check if our node has been set to NULL (invalid or not found)
+		if(node==NULL)
+			return;
+		
+		//set the type of the current node
+		xmlNodeSetName(node,(const xmlChar*)"dict");
+		
+		// we'll use this to keep track of which nodes were already present, so we'll
+		// know which ones were missing for which we need to make new nodes
+		dict_t seen;
+
+		//find the depth of the target node in the xml tree to maintain proper indentation
+		std::string perIndent("    ");
+		std::string indentStr;
+		for(xmlNode* cur=node->parent; cur!=NULL; cur=cur->parent) {
+			if((void*)cur==(void*)node->doc) { //if we hit the document node, discount it and we're done
+				if(indentStr.size()>0)
+					indentStr=indentStr.substr(0,indentStr.size()-perIndent.size());
+				break;
+			}
+			indentStr+=perIndent;
+		}
+		
+		//This will hold any comments found between elements -- if no comment is found, a new one may be added
+		std::string comment;
+
+		//process children nodes
+		for(xmlNode* cur = skipToElement(node->children,comment); cur!=NULL; cur = skipToElement(cur->next,comment)) {
+			
+			//find the next key node
+			xmlNode * k=cur;
+			if(xmlStrcmp(k->name, (const xmlChar *)"key"))
+				throw bad_format(k,"Dictionary format error: expect data in pairs of key and value (two values found in a row)");
+			cur=skipToElement(cur->next);
+			
+			//find the following value (non-key) node
+			xmlNode * v=cur;
+			if(v==NULL)
+				throw bad_format(cur,"Dictionary format error: expect data in pairs of key and value (dictionary ended with hanging key)");
+			if(!xmlStrcmp(v->name, (const xmlChar *)"key"))
+				throw bad_format(v,"Dictionary format error: expect data in pairs of key and value (two keys found in a row)");
+			
+			//find corresponding entry
+			xmlChar* cont=xmlNodeGetContent(k);
+			string key=(const char*)cont;
+			xmlFree(cont);
+			dict_t::const_iterator it=dict.find(key);
+			if(it==dict.end()) {
+				if(warnUnused)
+					cerr << "Warning: reading plist dictionary, key '" << key << "' does not match a registered variable.  Ignoring..." << endl;
+				continue;
+			}
+			if(comment.size()==0) {
+				bool isSub=dynamic_cast<Dictionary*>(it->second);
+				if(isSub) {
+					xmlAddPrevSibling(k,xmlNewText((const xmlChar*)"\n"));
+					xmlAddPrevSibling(k,xmlNewComment((const xmlChar*)("======== "+it->first+" ========").c_str()));
+				}
+				comments_t::const_iterator cit=comments.find(key);
+				if(cit!=comments.end()) {
+					if(isSub || cit->second.substr(0,key.size())==key)
+						comment=cit->second;
+					else //if not a sub-dictionary, and comment doesn't already start with entry name, prepend entry name
+						comment=key+": "+cit->second;
+					xmlAddPrevSibling(k,xmlNewText((const xmlChar*)"\n"));
+					xmlAddPrevSibling(k,xmlNewComment((const xmlChar*)comment.c_str()));
+					xmlAddPrevSibling(k,xmlNewText((const xmlChar*)("\n"+indentStr).c_str()));
+				}
+			}
+			it->second->SaveXML(v);
+			seen.insert(*it);
+		}
+
+		if(seen.size()!=dict.size()) {
+			// the main dictionary has entries that weren't seen... find which ones
+			// if needed, this could be made faster (O(n) vs. current O(n lg n)) by assuming the maps
+			// are sorted and moving two iterators through together instead of repeated find()'s
+			for(dict_t::const_iterator it=dict.begin(); it!=dict.end(); ++it) {
+				if(seen.find(it->first)==seen.end()) {
+					//we didn't see this node in the existing xml tree, have to add a new node pair for it
+					bool isSub=dynamic_cast<Dictionary*>(it->second);
+					if(isSub) {
+						xmlAddChild(node,xmlNewText((const xmlChar*)"\n"));
+						xmlAddChild(node,xmlNewComment((const xmlChar*)("======== "+it->first+" ========").c_str()));
+					}
+					comments_t::const_iterator cit=comments.find(it->first);
+					if(cit!=comments.end()) {
+						if(isSub || cit->second.substr(0,it->first.size())==it->first)
+							comment=cit->second;
+						else
+							comment=it->first+": "+cit->second;
+						xmlAddChild(node,xmlNewText((const xmlChar*)"\n"));
+						xmlAddChild(node,xmlNewComment((const xmlChar*)comment.c_str()));
+					}
+					xmlAddChild(node,xmlNewText((const xmlChar*)("\n"+indentStr).c_str()));
+					xmlNode* k=xmlNewChild(node,NULL,(const xmlChar*)"key",(const xmlChar*)it->first.c_str());
+					if(k==NULL)
+						throw bad_format(node,"Error: plist Dictionary xml error on saving key");
+					xmlAddChild(node,xmlNewText((const xmlChar*)" "));
+					xmlNode* v=xmlNewChild(node,NULL,(const xmlChar*)"",NULL);
+					if(v==NULL)
+						throw bad_format(node,"Error: plist Dictionary xml error on saving value");
+					if(indentStr.size()>=perIndent.size())
+						xmlAddChild(node,xmlNewText((const xmlChar*)("\n"+indentStr.substr(perIndent.size())).c_str()));
+					else
+						xmlAddChild(node,xmlNewText((const xmlChar*)("\n")));
+					it->second->SaveXML(v);
+				}
+			}
+		}
+	}
+
+	unsigned int Dictionary::getLongestKeyLen() const {
+		size_t longest=0;
+		for(Dictionary::dict_t::const_iterator it=dict.begin(); it!=dict.end(); ++it) {
+			size_t cur=it->first.size();
+			if(Dictionary* dp=dynamic_cast<Dictionary*>(it->second))
+				cur+=dp->getLongestKeyLen()+1;
+			longest=std::max(longest,cur);
+		}
+		return longest;
+	}
+	
+	void Dictionary::addDictionaryListener(DictionaryListener* vl) {
+		if(vl!=NULL) {
+			if(dictionaryListeners==NULL)
+				dictionaryListeners=new std::list<DictionaryListener*>;
+			dictionaryListeners->push_back(vl);
+		}
+	}
+		
+	void Dictionary::removeDictionaryListener(DictionaryListener* vl) {
+		if(dictionaryListeners==NULL)
+			return;
+		std::list<DictionaryListener*>::iterator it=find(dictionaryListeners->begin(),dictionaryListeners->end(),vl);
+		if(it!=dictionaryListeners->end()) {
+			dictionaryListeners->erase(it);
+			if(dictionaryListeners->empty()) {
+				delete dictionaryListeners;
+				dictionaryListeners=NULL;
+			}
+		}
+	}
+	
+	void Dictionary::fireEntryAdded(ObjectBase& val) {
+		if(dictionaryListeners==NULL)
+			return;
+		std::list<DictionaryListener*>::iterator it=dictionaryListeners->begin();
+		while(it!=dictionaryListeners->end()) {
+			std::list<DictionaryListener*>::iterator cur=it++; //increment early in case the listener changes subscription
+			(*cur)->plistDictionaryEntryAdded(*this,val);
+		}
+	}
+
+	void Dictionary::fireEntryRemoved(ObjectBase& val) {
+		if(dictionaryListeners==NULL)
+			return;
+		std::list<DictionaryListener*>::iterator it=dictionaryListeners->begin();
+		while(it!=dictionaryListeners->end()) {
+			std::list<DictionaryListener*>::iterator cur=it++; //increment early in case the listener changes subscription
+			(*cur)->plistDictionaryEntryRemoved(*this,val);
+		}
+	}
+
+	std::ostream& operator<<(std::ostream& os, const Dictionary& d) {
+		unsigned int longest=std::max(d.getLongestKeyLen(),static_cast<unsigned int>(os.width()));
+		for(Dictionary::dict_t::const_iterator it=d.dict.begin(); it!=d.dict.end(); ++it)
+			if(Dictionary* dp=dynamic_cast<Dictionary*>(it->second)) {
+				stringstream ss;
+				ss << setw(longest-it->first.size()-1) << *dp;
+				string line;
+				for(getline(ss,line); ss; getline(ss,line))
+					os << it->first << "." << line << endl;
+			} else {
+				os << left << setw(longest) << it->first << " = " << *it->second << endl;
+			}
+		return os;
+	}
+	
+	PrimitiveBase::~PrimitiveBase() {
+		delete primitiveListeners;
+		primitiveListeners=NULL;
+	}
+
+	void PrimitiveBase::addPrimitiveListener(PrimitiveListener* vl) {
+		if(vl!=NULL) {
+			if(primitiveListeners==NULL)
+				primitiveListeners=new std::list<PrimitiveListener*>;
+			primitiveListeners->push_back(vl);
+		}
+	}
+	void PrimitiveBase::removePrimitiveListener(PrimitiveListener* vl) {
+		if(primitiveListeners==NULL)
+			return;
+		std::list<PrimitiveListener*>::iterator it=find(primitiveListeners->begin(),primitiveListeners->end(),vl);
+		if(it!=primitiveListeners->end()) {
+			primitiveListeners->erase(it);
+			if(primitiveListeners->empty()) {
+				delete primitiveListeners;
+				primitiveListeners=NULL;
+			}
+		}
+	}
+	void PrimitiveBase::fireValueChanged() const {
+		if(primitiveListeners==NULL)
+			return;
+		std::list<PrimitiveListener*>::const_iterator it=primitiveListeners->begin();
+		while(it!=primitiveListeners->end()) {
+			std::list<PrimitiveListener*>::const_iterator cur=it++; //increment early in case the listener changes subscription
+			(*cur)->plistValueChanged(*this);
+		}
+	}
+	
+} //namespace plist
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
+ * $State: Exp $
+ * $Date: 2005/07/27 05:58:24 $
+ */
diff -urdN ../Tekkotsu_2.3/Shared/plist.h ./Shared/plist.h
--- ../Tekkotsu_2.3/Shared/plist.h	Wed Dec 31 19:00:00 1969
+++ ./Shared/plist.h	Sun Aug  7 00:11:04 2005
@@ -0,0 +1,742 @@
+//-*-c++-*-
+#ifndef INCLUDED_PListSupport_h_
+#define INCLUDED_PListSupport_h_
+
+/*
+ From: <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ 
+<!ENTITY % plistObject "(array | data | date | dict | real | integer | string | true | false )" >
+<!ELEMENT plist %plistObject;>
+<!ATTLIST plist version CDATA "1.0" >
+
+<!-- Collections -->
+<!ELEMENT array (%plistObject;)*>
+<!ELEMENT dict (key, %plistObject;)*>
+<!ELEMENT key (#PCDATA)>
+
+<!--- Primitive types -->
+<!ELEMENT string (#PCDATA)>
+<!ELEMENT data (#PCDATA)> <!-- Contents interpreted as Base-64 encoded -->
+<!ELEMENT date (#PCDATA)> <!-- Contents should conform to a subset of ISO 8601 (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'.  Smaller units may be omitted with a loss of precision) -->
+
+<!-- Numerical primitives -->
+<!ELEMENT true EMPTY>  <!-- Boolean constant true -->
+<!ELEMENT false EMPTY> <!-- Boolean constant false -->
+<!ELEMENT real (#PCDATA)> <!-- Contents should represent a floating point number matching ("+" | "-")? d+ ("."d*)? ("E" ("+" | "-") d+)? where d is a digit 0-9.  -->
+<!ELEMENT integer (#PCDATA)> <!-- Contents should represent a (possibly signed) integer number in base 10 -->
+*/
+
+#include "XMLLoadSave.h"
+#include <exception>
+#include <string>
+#include <iostream>
+#include <iomanip>
+#include <sstream>
+#include <map>
+#include <list>
+
+//! A collection of classes to implement the Propery List data storage format, a XML standard used by Apple and others
+namespace plist {
+	
+	//! Base class for the plist listener callbacks
+	class Listener {
+	public:
+		//! destructor
+		virtual ~Listener() {}
+	};
+	
+	class PrimitiveBase;
+	//! If you wish to be notified any time a particular plist primitive's value has been changed, inherit from this and implement the callback, then register it with the plist object through Primitive::addPrimitiveListener()
+	class PrimitiveListener : public Listener {
+	public:
+		//! This will be called whenever a plist you have registered with is changed
+		/*! @a pl is const to help you avoid infinite recursion from an
+		 *  accidental modification of @a pl's value -- use a const cast
+		 *  if you're sure you know what you're doing */
+		virtual void plistValueChanged(const PrimitiveBase& pl)=0;
+	};
+	
+	class ObjectBase;
+	class Dictionary;
+	//! If you wish to be notified any time an entry is added or removed from a Dictionary, inherit from this and implement one or both of the functions, then register it with the dictionary's Dictionary::addDictionaryListener()
+	class DictionaryListener : public Listener {
+	public:
+		//! This will be called whenever an entry is added to the dictionary
+		virtual void plistDictionaryEntryAdded(Dictionary& /*dict*/, ObjectBase& /*primitive*/) {}
+		//! This will be called whenever an entry is added to the dictionary
+		virtual void plistDictionaryEntryRemoved(Dictionary& /*dict*/, ObjectBase& /*primitive*/) {}
+	};
+	
+	//! This base class provides the root functionality for all plist entities -- Dictionary and the various templated subclasses of PrimitiveBase
+	/*! The subclasses may throw std::bad_format if the
+	 *  document is poorly structured or bad values are found. */
+	class ObjectBase : public XMLLoadSave {
+	public:
+		ObjectBase(); //!< constructor
+		virtual ~ObjectBase()=0; //!< destructor
+		
+	protected:
+		//!@name Inherited from XMLLoadSave
+		virtual void setParseTree(xmlDoc * doc) const;
+		virtual xmlNode* FindRootXMLElement(xmlDoc* doc) const;
+		//@}
+		
+		//!Provides indirect access to the libxml function of the same name
+		//!@name libxml Forwards
+		typedef unsigned char xChar;
+		static int xStrEqual(const xChar* a, const xChar* b);
+		static int xStrCaseEqual(const xChar* a, const xChar* b);
+		static xChar* xNodeGetContent(xmlNode* node);
+		static void xNodeSetContent(xmlNode* node, const xChar* content);
+		static const xChar* xNodeGetName(xmlNode* node);
+		static bool xNodeHasName(xmlNode* node, const char* name);
+		static void xNodeSetName(xmlNode* node, const xChar* name);
+		static xmlAttr* xHasProperty(xmlNode* node, const xChar* name);
+		static xChar* xGetProperty(xmlNode* node, const xChar* name);
+		static long xGetLineNo(xmlNode* node);
+		static void xFree(void* ptr);
+		//@}
+	};
+	
+	//! Maintains a set of (key,value) pairs, where a value can be any subclass of ObjectBase
+	/*! This class supports callbacks upon modification through the use of the
+	 *  DictionaryListener interface.  Note that we only store a pointer to the
+	 *  listener list, which is typically unallocated when no listeners are
+	 *  active.  This should ensure minimal memory usage per object, as well as
+	 *  support safe storage of plist objects in inter-process shared memory
+	 *  regions.
+	 *
+	 *  If you are using these in a shared memory region, just be sure that only
+	 *  the process with listeners does any and all modifications, and that it
+	 *  unsubscribes before detaching from the region (or else destroys the region
+	 *  itself)
+	 *
+	 *  There isn't a callback if entries themselves are modified, only when new
+	 *  entries are added, or old ones removed.  If you want to know any time any
+	 *  aspect of any entry is modified, listen for the add and remove callbacks,
+	 *  and then add yourself as a listener to each entry individually.  */
+	class Dictionary : public ObjectBase {
+		friend std::ostream& operator<<(std::ostream& os, const Dictionary& d);
+	public:
+		//! constructor
+		Dictionary() : ObjectBase(), dictionaryListeners(), warnUnused(true), dict(), comments() {autoFormat=false;}
+		//! copy constructor (don't assign listeners)
+		Dictionary(const Dictionary& d) : ObjectBase(d), dictionaryListeners(), warnUnused(d.warnUnused), dict(d.dict), comments(d.comments) {}
+		//! assignment (don't assign listeners)
+		Dictionary& operator=(const Dictionary& d) { if(&d==this) return *this; ObjectBase::operator=(d); warnUnused=d.warnUnused; dict=d.dict; comments=d.comments; return *this; }
+		//! destructor
+		virtual ~Dictionary();
+		
+		//! insert a new entry to the dictionary, with key @a name and value @a val (replaces any previous entry by same name, but gives a warning)
+		void addEntry(const std::string& name, ObjectBase& val);
+		//! insert a new entry to the dictionary, with key @a name and value @a val (replaces any previous entry by same name, but gives a warning)
+		void addEntry(const std::string& name, ObjectBase& val, const std::string& comment);
+		//! replaces previous entry of the same name, or adds it if it doesn't exist; use addEntry if you want to assert that the name does not already exist
+		void setEntry(const std::string& name, ObjectBase& val) { dict[name]=&val; }
+		//! replaces previous comment for @a name, or adds it if it doesn't already exist (can preceed actual entry!)
+		void setComment(const std::string& name, const std::string& comment) { comments[name]=comment; }
+		//! returns comment retrieved from loaded file, or any subsequent call to setComment
+		const std::string& getComment(const std::string& name) const;
+		//! remove the entry with key @a name
+		void removeEntry(const std::string& name) { dict.erase(name); }
+		//! return the value of the key @a name, or NULL if it doesn't exist
+		ObjectBase* findEntry(const std::string& name) const;
+		
+		void LoadXML(xmlNode* node);
+		void SaveXML(xmlNode* node) const;
+		
+		void setUnusedWarning(bool b) { warnUnused=b; } //!< set #warnUnused
+		bool getUnusedWarning() { return warnUnused; } //!< returns #warnUnused
+
+		//! get notified of changes; be sure to call removeValueListener before destructing @a vl!
+		virtual void addDictionaryListener(DictionaryListener* vl);
+		//! no longer take notification of changes to this object's value
+		virtual void removeDictionaryListener(DictionaryListener* vl);
+		
+	protected:
+		//! run through #dictionaryListeners, calling DictionaryListener::plistDictionaryEntryAdded(*this,val)
+		virtual void fireEntryAdded(ObjectBase& val);
+		//! run through #dictionaryListeners, calling DictionaryListener::plistDictionaryEntryRemoved(*this,val)
+		virtual void fireEntryRemoved(ObjectBase& val);
+		//! stores a list of the current listeners
+		std::list<DictionaryListener*>* dictionaryListeners;
+
+		//! return the length of the longest key for formatting purposes
+		unsigned int getLongestKeyLen() const;
+		//! if true (the default) LoadXML will give warnings if there are unused entries in the node it is passed
+		bool warnUnused;
+
+		//! shorthand for the type of #dict
+		typedef std::map<std::string,ObjectBase*> dict_t;
+		//! storage of entries -- mapping from keys to value pointers
+		dict_t dict;
+
+		//! shorthand for the type of #comments
+		typedef std::map<std::string,std::string> comments_t;
+		//! storage of entry comments -- mapping from keys to help text comments for manual editing or user feedback
+		/*! not every key necessarily has a comment! */
+		comments_t comments;
+	};
+	//! provides textual output
+	std::ostream& operator<<(std::ostream& os, const Dictionary& d);
+
+
+	//! Provides common functionality to all primitive value classes (implemented in a templated subclass Primitive)
+	/*! This class supports callbacks upon modification through the use of the
+	 *  PrimitiveListener interface.  Note that we only store a pointer to the
+	 *  listener list, which is typically unallocated when no listeners are
+	 *  active.  This should ensure minimal memory usage per object, as well as
+	 *  support safe storage of plist objects in inter-process shared memory
+	 *  regions.
+	 *
+	 *  If you are using these in a shared memory region, just be sure that only
+	 *  the process with listeners does any and all modifications, and that it
+	 *  unsubscribes before detaching from the region (or else destroys the region
+	 *  itself) */
+	class PrimitiveBase : public ObjectBase {
+	public:
+		//! constructor
+		PrimitiveBase() : ObjectBase(), primitiveListeners() {}
+		//! copy constructor (don't copy listeners)
+		PrimitiveBase(const PrimitiveBase& pb) : ObjectBase(pb), primitiveListeners() {}
+		//! assignment (don't assign listeners)
+		PrimitiveBase& operator=(const PrimitiveBase& pb) { ObjectBase::operator=(pb); return *this; }
+		//! destructor
+		~PrimitiveBase();
+		
+		//! assign a new value
+		virtual void set(const std::string& str)=0;
+		//! return current value as a string
+		virtual std::string get() const=0;
+
+		//! get notified of changes; be sure to call removeValueListener before destructing @a vl!
+		virtual void addPrimitiveListener(PrimitiveListener* vl);
+		//! no longer take notification of changes to this object's value
+		virtual void removePrimitiveListener(PrimitiveListener* vl);
+
+	protected:
+		//! run through #primitiveListeners, calling PrimitiveListener::plistValueChanged(*this)
+		virtual void fireValueChanged() const;
+		//! stores a list of the current listeners
+		std::list<PrimitiveListener*>* primitiveListeners;
+	};
+	//! output stringified value (from PrimitiveBase::get()) to stream
+	inline std::ostream& operator<<(std::ostream& os, const PrimitiveBase& pb) {
+		return os << pb.get();
+	}
+	//! input value from next word in @a is, via PrimitiveBase::set()
+	inline std::istream& operator>>(std::istream& is, PrimitiveBase& pb) {
+		std::string s;
+		is >> s;
+		pb.set(s);
+		return is;
+	}
+	
+
+	//! Implements type-specific functionality through template specialization, mainly involving value conversion and stringification formatting
+	/*! Provides smart-pointer style functionality for transparent
+	 *  access to the value storage, as well as automatic casting
+	 *  to and from the value type so you can almost always treat
+	 *  the Primitive as if it was the value itself. */
+	template<typename T>
+	class Primitive : public PrimitiveBase {
+	public:
+		Primitive() : ObjectBase(), val() {} //!< constructor
+		Primitive(const T& v) : ObjectBase(), val(v) {} //!< constructor, automatic casting from the value type
+		Primitive& operator=(const T& v) { val=v; fireValueChanged(); return *this; } //!< assignment
+		//T& operator*() { return val; } //!< access value -- if #val is modified, this won't know, so PrimitiveListeners are going to be clueless
+		const T& operator*() const { return val; } //!< smart pointer access to value
+		//T* operator->() { return &val; } //!< smart pointer access to value -- if #val is modified, this won't know, so PrimitiveListeners are going to be clueless
+		const T* operator->() const { return &val; } //!< smart pointer access to value
+		operator T() const { return val; } //!< automatic casting to the value type
+/*		void LoadXML(xmlNode* node) {
+			if(node==NULL)
+				return;
+			//decode base64 from xml node
+			//val->LoadBuffer(buf,bufsize);
+			fireValueChanged(); 
+		}
+		void SaveXML(xmlNode* node) const {
+			if(node==NULL)
+				return;
+			unsigned int bufsize=val->getBinSize();
+			char * buf = new char[bufsize];
+			val->SaveBuffer(buf,bufsize);
+			//base64 encode into xml node
+			delete [] buf;
+		}*/
+	protected:
+		T val; //!< value storage
+	};
+
+	//! provides a @c bool specialization of Primitive<T>
+	/*! A @c bool can be treated as either a string or an integer\n
+	 *  When saving, "true" or "false" will be used, but users could
+	 *  also specify "yes"/"no" or "on"/"off".  If an integer is used,
+	 *  it will be interpreted as usual: 0==false, otherwise true. */
+	template<>
+	class Primitive<bool> : public PrimitiveBase {
+	public:
+		Primitive() : PrimitiveBase(), val() {} //!< constructor
+		Primitive(const bool& v) : PrimitiveBase(), val(v) {} //!< casting constructor
+		Primitive& operator=(const bool& v) { val=v; fireValueChanged(); return *this; } //!< assignment constructor
+		//bool& operator*() { return val; }
+		const bool& operator*() const { return val; } //!< dereference will return data storage
+		//bool* operator->() { return &val; }
+		const bool* operator->() const { return &val; } //!< can use -> to access members of data storage
+		operator bool() const { return val; } //!< casting operator
+		void LoadXML(xmlNode* node) {
+			if(node==NULL)
+				return;
+			if(xNodeHasName(node,"true")) {
+				val=true;
+				fireValueChanged(); 
+			} else if(xNodeHasName(node,"false")) {
+				val=false;
+				fireValueChanged(); 
+			} else if(xNodeHasName(node,"integer") || xNodeHasName(node,"real")) {
+				xChar * cont=xNodeGetContent(node);
+				std::stringstream str((char*)cont);
+				str >> val;
+				xFree(cont);
+				fireValueChanged(); 
+			} else if(xNodeHasName(node,"string")) {
+				xChar * cont=xNodeGetContent(node);
+				try {
+					set((char*)cont);
+					std::cerr << "Warning: plist boolean expects value of '<true/>', '<false/>', or numeric.  String value of '" << (char*)cont << "' is not recommended." << std::endl;
+				} catch(const bad_format& err) {
+					xFree(cont);
+					throw bad_format(node,err.what());
+				} catch(...) {
+					xFree(cont);
+					throw;
+				}
+				xFree(cont);
+			} else
+				throw bad_format(node,"Error: plist boolean must be 'true', 'false', or numeric type");
+		}
+		void SaveXML(xmlNode* node) const {
+			if(node==NULL)
+				return;
+			xNodeSetName(node,(const xChar*)(val?"true":"false"));
+			xNodeSetContent(node,NULL);
+		}
+		void set(const std::string& str) {
+			if(str=="true" || str=="yes" || str=="on")
+				val=true;
+			else if(str=="false" || str=="no" || str=="off")
+				val=false;
+			else {
+				float t;
+				if(sscanf(str.c_str(),"%g",&t)==0)
+					throw bad_format(NULL,"Error: plist boolean must be 'true', 'false', or numeric type");
+				val=t;
+			}
+			fireValueChanged(); 
+		}
+		std::string get() const {
+			return val?"true":"false";
+		}
+	protected:
+		bool val; //!< the actual data storage
+	};
+
+	//! provides a @c char specialization of Primitive<T>
+	/*! A @c char can be treated as either a string or an integer, you can use
+	 *  the setNumeric(bool) function to indicate which style to use when saving */
+	template<>
+	class Primitive<char> : public PrimitiveBase {
+	public:
+		Primitive() : PrimitiveBase(), val(), numeric(false) {} //!< constructor
+		Primitive(const char& v, bool isNum=false) : PrimitiveBase(), val(v), numeric(isNum) {} //!< casting constructor
+		Primitive& operator=(const char& v) { val=v; fireValueChanged(); return *this; } //!< assignment
+		Primitive& operator+=(const char& v) { val+=v; fireValueChanged(); return *this; } //!< add-assign
+		Primitive& operator-=(const char& v) { val-=v; fireValueChanged(); return *this; } //!< subtract-assign
+		Primitive& operator*=(const char& v) { val*=v; fireValueChanged(); return *this; } //!< multiply-assign
+		Primitive& operator/=(const char& v) { val/=v; fireValueChanged(); return *this; } //!< divide-assign
+		//char& operator*() { return val; }
+		const char& operator*() const { return val; } //!< dereference will return data storage
+		//char* operator->() { return &val; }
+		const char* operator->() const { return &val; } //!< can use -> to access members of data storage
+		operator char() const { return val; } //!< casting operator
+		void setNumeric(bool isNum) { numeric=isNum; } //!< sets #numeric
+		bool getNumeric() const { return numeric; } //!< returns #numeric
+		void LoadXML(xmlNode* node) {
+			if(node==NULL)
+				return;
+			xChar* cont=xNodeGetContent(node);
+			try {
+				if(xNodeHasName(node,"string")) {
+					set((char*)cont);
+				} else if(xNodeHasName(node,"integer")) {
+					val=strtol((const char*)cont,NULL,0);
+					fireValueChanged(); 
+				} else if(xNodeHasName(node,"real")) {
+					val=(char)strtod((const char*)cont,NULL);
+					fireValueChanged(); 
+				} else if(xNodeHasName(node,"true")) {
+					val=true;
+					fireValueChanged(); 
+				} else if(xNodeHasName(node,"false")) {
+					val=false;
+					fireValueChanged(); 
+				} else {
+					throw bad_format(node,"Error: plist char must be either a string or integer");
+				} 
+			} catch(const bad_format& err) {
+				xFree(cont);
+				throw bad_format(node,err.what());
+			} catch(...) {
+				xFree(cont);
+				throw;
+			}
+			xFree(cont);
+		}
+		void SaveXML(xmlNode* node) const {
+			if(node==NULL)
+				return;
+			if(numeric) {
+				xNodeSetName(node,(const xChar*)"integer");
+				std::stringstream str;
+				str << (int)val;
+				xNodeSetContent(node,(const xChar*)str.str().c_str());
+			} else {
+				xNodeSetName(node,(const xChar*)"string");
+				xChar str[2] = {val,'\0'};
+				xNodeSetContent(node,(const xChar*)str);
+			}
+		}
+		void set(const std::string& str) {
+			if(str.size()==0)
+				throw bad_format(NULL,"Error: plist char must have non-empty content");
+			val=str[0];
+			if(str.size()!=1)
+				std::cerr << "Warning: plist expected single char, found multi-char string '" << str << "'" << std::endl;
+			fireValueChanged(); 
+		}
+		std::string get() const {
+			return std::string(1,val);
+		}
+	protected:
+		char val; //!< data storage
+		bool numeric; //!< if true, requests that saves store the numeric value instead of corresponding character
+	};
+	
+	//! provides an @c unsigned @c char specialization of Primitive<T>
+	/*! A @c char can be treated as either a string or an integer, you can use
+	 *  the setNumeric(bool) function to indicate which style to use when saving */
+	template<>
+	class Primitive<unsigned char> : public PrimitiveBase {
+	public:
+		Primitive() : PrimitiveBase(), val(), numeric(false) {} //!< constructor
+		Primitive(const unsigned char& v, bool isNum=false) : PrimitiveBase(), val(v), numeric(isNum) {} //!< casting constructor
+		Primitive& operator=(const unsigned char& v) { val=v; fireValueChanged(); return *this; } //!< assignment
+		Primitive& operator+=(const unsigned char& v) { val+=v; fireValueChanged(); return *this; } //!< add-assign
+		Primitive& operator-=(const unsigned char& v) { val-=v; fireValueChanged(); return *this; } //!< subtract-assign
+		Primitive& operator*=(const unsigned char& v) { val*=v; fireValueChanged(); return *this; } //!< multiple-assign
+		Primitive& operator/=(const unsigned char& v) { val/=v; fireValueChanged(); return *this; } //!< divide-assign
+		//unsigned char& operator*() { return val; }
+		const unsigned char& operator*() const { return val; } //!< dereference will return data storage
+		//unsigned char* operator->() { return &val; }
+		const unsigned char* operator->() const { return &val; } //!< can use -> to access members of data storage
+		operator unsigned char() const { return val; } //!< casting operator
+		void setNumeric(bool isNum) { numeric=isNum; } //!< sets #numeric
+		bool getNumeric() const { return numeric; } //!< returns #numeric
+		void LoadXML(xmlNode* node) {
+			if(node==NULL)
+				return;
+			xChar* cont=xNodeGetContent(node);
+			try {
+				if(xNodeHasName(node,"string")) {
+					set((char*)cont);
+				} else if(xNodeHasName(node,"integer")) {
+					val=strtol((const char*)cont,NULL,0);
+					fireValueChanged(); 
+				} else if(xNodeHasName(node,"real")) {
+					val=(char)strtod((const char*)cont,NULL);
+					fireValueChanged(); 
+				} else if(xNodeHasName(node,"true")) {
+					val=true;
+					fireValueChanged(); 
+				} else if(xNodeHasName(node,"false")) {
+					val=false;
+					fireValueChanged(); 
+				} else {
+					throw bad_format(node,"Error: plist unsigned char must be either a string or integer");
+				} 
+			} catch(const bad_format& err) {
+				xFree(cont);
+				throw bad_format(node,err.what());
+			} catch(...) {
+				xFree(cont);
+				throw;
+			}
+			xFree(cont);
+		}
+		void SaveXML(xmlNode* node) const {
+			if(node==NULL)
+				return;
+			if(numeric) {
+				xNodeSetName(node,(const xChar*)"integer");
+				std::stringstream str;
+				str << (int)val;
+				xNodeSetContent(node,(const xChar*)str.str().c_str());
+			} else {
+				xNodeSetName(node,(const xChar*)"string");
+				xChar str[2] = {val,'\0'};
+				xNodeSetContent(node,(const xChar*)str);
+			}
+		}
+		void set(const std::string& str) {
+			if(str.size()==0)
+				throw bad_format(NULL,"Error: plist char must have non-empty content");
+			val=str[0];
+			if(str.size()!=1)
+				std::cerr << "Warning: plist expected single char, found multi-char string '" << str << "'" << std::endl;
+		}
+		std::string get() const {
+			return std::string(1,val);
+		}
+	protected:
+		unsigned char val; //!< data storage
+		bool numeric; //!< if true, requests that saves store the numeric value instead of corresponding character
+	};
+
+	
+//! a macro to provide template specializations for the numeric primitives, which only need to vary their string name
+#define PLIST_OBJECT_SPECIALIZATION(T,PRIM) \
+	template<> \
+	class Primitive<T> : public PrimitiveBase { \
+	public: \
+		Primitive() : PrimitiveBase(), val() {} \
+		Primitive(const T& v) : PrimitiveBase(), val(v) {} \
+		Primitive& operator=(const T& v) { val=v; fireValueChanged(); return *this; } \
+		Primitive& operator+=(const T& v) { val+=v; fireValueChanged(); return *this; } \
+		Primitive& operator-=(const T& v) { val-=v; fireValueChanged(); return *this; } \
+		Primitive& operator*=(const T& v) { val*=v; fireValueChanged(); return *this; } \
+		Primitive& operator/=(const T& v) { val/=v; fireValueChanged(); return *this; } \
+		/*T& operator*() { return val; }*/ \
+		const T& operator*() const { return val; } \
+		/*T* operator->() { return &val; }*/ \
+		const T* operator->() const { return &val; } \
+		operator T() const { return val; } \
+		void LoadXML(xmlNode* node) { \
+			if(node==NULL) \
+				return; \
+			bool bt=xNodeHasName(node,"true"); \
+			bool bf=xNodeHasName(node,"false"); \
+			if(!bt && !bf && !xNodeHasName(node,"integer") && !xNodeHasName(node,"real") && !xNodeHasName(node,"string")) \
+				throw bad_format(node,"Error: plist "#T" expects "PRIM" type"); \
+			if(!xNodeHasName(node,PRIM)) \
+				std::cerr << "Warning: plist expected "PRIM" got " << (const char*)xNodeGetName(node) << ", trying to convert. (line " << xGetLineNo(node) << ")" << std::endl; \
+			if(bt) \
+				val = true; \
+			else if(bf) \
+				val = false; \
+			else { \
+				xChar * cont=xNodeGetContent(node); \
+				std::stringstream str((const char*)cont); \
+				str >> val; \
+				xFree(cont); \
+			} \
+			fireValueChanged(); \
+		} \
+		void SaveXML(xmlNode* node) const { \
+			if(node==NULL) \
+				return; \
+			xNodeSetName(node,(const xChar*)PRIM); \
+			std::stringstream str; \
+			str <<std::setprecision(128)<< val; \
+			xNodeSetContent(node,(const xChar*)str.str().c_str()); \
+		} \
+		void set(const std::string& str) { \
+			std::stringstream sstr(str); \
+			sstr >> val; \
+			fireValueChanged(); \
+		} \
+		std::string get() const { \
+			std::stringstream sstr; \
+			sstr <<std::setprecision(128)<< val; \
+			return sstr.str(); \
+		} \
+	protected: \
+		T val; \
+	}
+	
+	PLIST_OBJECT_SPECIALIZATION(short,"integer"); //!< short instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(unsigned short,"integer"); //!< unsigned short instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(int,"integer"); //!< int instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(unsigned int,"integer"); //!< unsigned int instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(long,"integer"); //!< long instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(unsigned long,"integer"); //!< unsigned long instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(long long,"integer"); //!< long long instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(unsigned long long,"integer"); //!< unsigned long long instance of PrimitiveBase ("integer")
+	PLIST_OBJECT_SPECIALIZATION(float,"real"); //!< float instance of PrimitiveBase ("real")
+	PLIST_OBJECT_SPECIALIZATION(double,"real"); //!< double instance of PrimitiveBase ("real")
+
+	//! Provides a @c std::string specialization of Primitive<T>
+	/*! Doesn't need to provide a operator cast because we subclass std::string itself! */
+	template<>
+	class Primitive<std::string> : public PrimitiveBase, public std::string {
+	public:
+		Primitive() : PrimitiveBase(), std::string() {} //!< constructor
+		Primitive(const std::string& v) : PrimitiveBase(), std::string(v) {} //!< casting constructor
+		Primitive& operator=(const std::string& v) { std::string::operator=(v); fireValueChanged(); return *this; } //!< assignment
+		//std::string& operator*() { return *this; }
+		const std::string& operator*() const { return *this; } //!< dereference will return data storage as a string (for uniformity with the other Primitives, although unnecessary with this instantiation)
+		//std::string* operator->() { return this; }
+		const std::string* operator->() const { return this; } //!< returns a pointer to this (for uniformity with the other Primitives, although unnecessary with this instantiation)
+		//no casting operator because we subclass string
+		void LoadXML(xmlNode* node) {
+			if(node==NULL)
+				return;
+			if(xNodeHasName(node,"string")) {
+				xChar * cont=xNodeGetContent(node);
+				*this=(char*)cont;
+				xFree(cont);
+			} else {
+				if(xNodeHasName(node,"integer") || xNodeHasName(node,"real")) {
+					xChar * cont=xNodeGetContent(node);
+					*this=(char*)cont;
+					xFree(cont);
+				} else if(xNodeHasName(node,"true"))
+					*this="true";
+				else if(xNodeHasName(node,"false"))
+					*this="false";
+				else
+					throw bad_format(node,"Error: plist string must be 'true', 'false', or numeric type");
+				std::cerr << "Warning: plist string expected, found " << (const char*)xNodeGetName(node) << " on line " << xGetLineNo(node) << std::endl;
+				fireValueChanged(); 
+			}
+		}
+		void SaveXML(xmlNode* node) const {
+			if(node==NULL)
+				return;
+			xNodeSetName(node,(const xChar*)"string");
+			xNodeSetContent(node,(const xChar*)c_str());
+		}
+		void set(const std::string& str) {
+			*this=str;
+			fireValueChanged(); 
+		}
+		std::string get() const {
+			return *this;
+		}
+	};
+	
+	//! Provides an interface for the use of enumerations in a plist -- you can specify values by either the string name or the corresponding integer value
+	/*! Where an array of names is required, you must order the array such that
+	 *  the enumeration value can be used as an index into the array.
+	 *  The 'maxval' parameters should be one above the maximum enumeration -- 
+	 *  if your enumeration runs sequentially from 0 to n, #max should be the
+	 *  number of enumerations: n+1 */
+	template<typename T> 
+	class NamedEnumeration : public PrimitiveBase {
+	public:
+		NamedEnumeration() : PrimitiveBase(), val(), names(NULL), max(0) {} //!< constructor
+		NamedEnumeration(const NamedEnumeration& ne) : PrimitiveBase(ne), val(ne.val), names(ne.names), max(ne.max) {} //!< copy constructor
+		NamedEnumeration(const T& v, const char * const* enumnames, unsigned int maxval) : PrimitiveBase(), val(v), names(enumnames), max(maxval) {} //!< constructor, pass initial value, array of strings (the names), and the one-plus-maximum enum value (i.e. the number of enumeration values if they run sequentially from 0)
+		NamedEnumeration(const T& v) : PrimitiveBase(), val(v), names(NULL), max(0) {} //!< automatic casting from the enumeration
+		NamedEnumeration& operator=(const T& v) { val=v; fireValueChanged(); return *this; } //!< assignment from enumeration value (numeric)
+		NamedEnumeration& operator=(const std::string& v) { set(v); return *this; } //!< assignment from string
+		NamedEnumeration& operator=(const NamedEnumeration& ne) { PrimitiveBase::operator=(ne); val=ne.val; return *this; } //!< assignment
+		//T& operator*() { return val; }
+		const T& operator*() const { return val; } //!< value access
+		operator T() const { return val; } //!< automatic casting to the enumeration value
+		void setNames(const char *  const* enumnames, unsigned int maxval) { names=enumnames; max=maxval; } //!< (re)set the array of names and one-plus-maximum enum value (i.e. the number of enumeration values if they run sequentially from 0)
+		const char*  const* getNames() const { return names; } //!< returns the array of names previously provided from constructor or setNames()
+		const char* getName(unsigned int i) const { return names[i]; } //!< returns the name for a particular index
+		unsigned int getMax() const { return max; } //!< returns the one-past-maximum of enumeration values previously provided to constructor or setNames()
+
+		void LoadXML(xmlNode* node) {
+			if(node==NULL)
+				return;
+			if(xNodeHasName(node,"true") || xNodeHasName(node,"false")) {
+				std::string name=(const char*)xNodeGetName(node);
+				unsigned int i=findName(name.c_str());
+				if(i==-1U)
+					throw bad_format(node,("Error: plist NamedEnumeration cannot be '"+name+"'").c_str());
+				val=static_cast<T>(i);
+				std::cerr << "Warning: plist NamedEnumeration should use <string>" << name << "</string>, not <" << name << "/>" << std::endl;
+			} else if(xNodeHasName(node,"integer") || xNodeHasName(node,"real") || xNodeHasName(node,"string")) {
+				xChar * cont=xNodeGetContent(node);
+				try {
+					set((char*)cont);
+				} catch(const bad_format& err) {
+					xFree(cont);
+					throw bad_format(node,err.what());
+				} catch(...) {
+					xFree(cont);
+					throw;
+				}
+				xFree(cont);
+			} else
+				throw bad_format(node,"Error: plist NamedEnumeration must be numeric or valid string");
+		}
+		void SaveXML(xmlNode* node) const {
+			if(node==NULL)
+				return;
+			if(names!=NULL && names[val]!=NULL && val>0 && (unsigned int)val<max) {
+				xNodeSetName(node,(const xChar*)"string");
+			} else {
+				xNodeSetName(node,(const xChar*)"integer");
+			}
+			xNodeSetContent(node,(const xChar*)get().c_str());
+		}
+		void set(const std::string& str) {
+			unsigned int i=findName(str.c_str());
+			if(i==-1U) {
+				if(sscanf(str.c_str(),"%d",&i)==0)
+					throw bad_format(NULL,"Error: plist NamedEnumeration must be numeric or valid string");
+			}
+			val=static_cast<T>(i);
+			fireValueChanged(); 
+		}
+		std::string get() const {
+			if(names!=NULL && names[val]!=NULL && val>=0 && (unsigned int)val<max)
+				return names[val];
+			std::stringstream str;
+			str << val;
+			return str.str();
+		}
+	protected:
+		//! returns the enum corresponding to @a name
+		unsigned int findName(const char* name) {
+			if(name==NULL || names==NULL)
+				return -1U;
+			for(unsigned int i=0; i<max; i++)
+				if(names[i] && strcmp(name,names[i])==0)
+					return i;
+			return -1U;
+		}
+		T val; //!< storage of enum value
+		const char *  const* names; //!< pointer to array of names -- enum value must be able to serve as index for lookup
+		unsigned int max; //!< one-plus-maximum enum value, i.e. the number of enum entries if they are ordered sequentially from 0
+	};
+	
+	//! output of an ObjectBase to a stream
+	inline std::ostream& operator<<(std::ostream& os, const ObjectBase& pb) {
+		if(const PrimitiveBase * pbp=dynamic_cast<const PrimitiveBase*>(&pb))
+			os << *pbp;
+		else if(const Dictionary * dp=dynamic_cast<const Dictionary*>(&pb))
+			os << *dp;
+		else
+			os << "[Unknown ObjectBase subclass, edit " << __FILE__ << ":" << __LINE__ << "]";
+		return os;
+	}
+	
+} //namespace plist
+
+/*! @file
+ * @brief Provides the plist namespace, a collection of classes to implement the Propery List data storage format, a XML standard used by Apple and others
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:04 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Shared/string_util.cc ./Shared/string_util.cc
--- ../Tekkotsu_2.3/Shared/string_util.cc	Wed Jan 14 15:45:28 2004
+++ ./Shared/string_util.cc	Wed Jun  1 01:47:49 2005
@@ -25,6 +25,18 @@
 		return std::string();
 	}
 
+	std::string trim(const std::string& str) {
+		if(str.size()==0)
+			return str;
+		unsigned int b=0;
+		unsigned int e=str.size()-1;
+		while(b<str.size() && isspace(str[b]))
+			b++;
+		while(b<e && isspace(str[e]))
+			e--;
+		return str.substr(b,e-b+1);
+	}
+	
 	bool parseArgs(const std::string& input, std::vector<std::string>& args, std::vector<unsigned int>& offsets) {
 		std::string cur;
 		bool isDoubleQuote=false;
@@ -89,8 +101,8 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2004/01/14 20:45:28 $
+ * $Date: 2005/06/01 05:47:49 $
  */
diff -urdN ../Tekkotsu_2.3/Shared/string_util.h ./Shared/string_util.h
--- ../Tekkotsu_2.3/Shared/string_util.h	Wed Dec 22 20:47:07 2004
+++ ./Shared/string_util.h	Wed Jun  1 01:47:49 2005
@@ -16,6 +16,9 @@
 	//! returns @a str with @a pre removed - if @a pre is not fully matched, @a str is returned unchanged
 	std::string removePrefix(const std::string& str, const std::string& pre);
 	
+	//! removes whitespace (as defined by isspace()) from the beginning and end of @a str, and returns the result
+	std::string trim(const std::string& str);
+	
 	//! parses the input string into an arg list, with corresponding offsets of each arg in the original input
 	bool parseArgs(const std::string& input, std::vector<std::string>& args, std::vector<unsigned int>& offsets); 
 };
@@ -25,10 +28,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/06/01 05:47:49 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Sound/CVS/Entries ./Sound/CVS/Entries
--- ../Tekkotsu_2.3/Sound/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Sound/CVS/Entries	Wed Aug 10 11:03:20 2005
@@ -0,0 +1,6 @@
+/SoundManager.cc/1.2/Wed Jun  1 05:47:53 2005//Ttekkotsu-2_4
+/SoundManager.h/1.3/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/SoundManagerMsg.h/1.2/Wed Jun  1 05:47:54 2005//Ttekkotsu-2_4
+/WAV.cc/1.2/Wed Jun  1 05:47:54 2005//Ttekkotsu-2_4
+/WAV.h/1.2/Wed Jun  1 05:47:54 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Sound/CVS/Repository ./Sound/CVS/Repository
--- ../Tekkotsu_2.3/Sound/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Sound/CVS/Repository	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Tekkotsu/Sound
diff -urdN ../Tekkotsu_2.3/Sound/CVS/Root ./Sound/CVS/Root
--- ../Tekkotsu_2.3/Sound/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Sound/CVS/Root	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Sound/CVS/Tag ./Sound/CVS/Tag
--- ../Tekkotsu_2.3/Sound/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Sound/CVS/Tag	Wed Aug 10 11:03:20 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Sound/SoundManager.cc ./Sound/SoundManager.cc
--- ../Tekkotsu_2.3/Sound/SoundManager.cc	Wed Dec 31 19:00:00 1969
+++ ./Sound/SoundManager.cc	Wed Jun  1 01:47:53 2005
@@ -0,0 +1,883 @@
+#include "Shared/Config.h"
+#include "SoundManager.h"
+#include "IPC/LockScope.h"
+#include "WAV.h"
+#include "Events/EventRouter.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fstream>
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OSubject.h>
+#  include <OPENR/ObjcommEvent.h>
+#endif
+
+using namespace std;
+
+SoundManager * sndman=NULL;
+
+//!for convenience when locking each of the functions
+typedef LockScope<ProcessID::NumProcesses> AutoLock;
+
+SoundManager::SoundManager()
+: mixerBuffer(0), mixerBufferSize(0), sndlist(),playlist(),chanlist(),mix_mode(Fast),queue_mode(Override),max_chan(4),lock(),sn(0)
+{}
+
+#ifdef PLATFORM_APERIOS
+void
+SoundManager::InitAccess(OSubject* subj) {
+	subjs[ProcessID::getID()]=subj;
+}
+#else //PLATFORM_LOCAL
+void
+SoundManager::InitAccess(MessageQueueBase& sndbufq) {
+	subjs[ProcessID::getID()]=&sndbufq;
+}
+#endif //PLATFORM-specific initialization
+
+SoundManager::~SoundManager() {
+	StopPlay();
+	if(!sndlist.empty())
+		cerr << "Warning: SoundManager was deleted with active sound buffer references" << endl;
+	while(!sndlist.empty()) {
+		sndlist_t::index_t it=sndlist.begin();
+		if(sndlist[it].rcr==NULL)
+			cerr << sndlist[it].name << " was still inflight (IPC), with " << sndlist[it].ref << " sound references" << endl;
+		else {
+			cerr << sndlist[it].name << " was deleted, with " << sndlist[it].ref << " sound references and " << sndlist[it].rcr->NumberOfReference() << " region references (one will be removed)" << endl;
+			sndlist[it].rcr->RemoveReference();
+		}
+		sndlist.erase(it);
+	}
+	delete[] mixerBuffer;
+}
+
+//!@todo this does one more copy than it really needs to
+SoundManager::Snd_ID
+SoundManager::LoadFile(std::string const &name) {
+	AutoLock autolock(lock,ProcessID::getID());
+	if (name.size() == 0) {
+	  cout << "SoundManager::LoadFile() null filename" << endl;
+	  return invalid_Snd_ID;
+	};
+	std::string path(config->sound.makePath(name));
+	Snd_ID id=lookupPath(path);
+	if(id!=invalid_Snd_ID) {
+		//		cout << "add reference to pre-existing" << endl;
+		sndlist[id].ref++;
+	} else {
+		//		cout << "load new file" << endl;
+		struct stat buf;
+		if(stat(path.c_str(),&buf)==-1) {
+			cout << "SoundManager::LoadFile(): Sound file not found: " << path << endl;
+			return invalid_Snd_ID;
+		}
+		byte * sndbuf=new byte[buf.st_size];
+		std::ifstream file(path.c_str());
+		file.read(reinterpret_cast<char*>(sndbuf),buf.st_size);
+		WAV wav;
+		WAVError error = wav.Set(sndbuf);
+		if (error != WAV_SUCCESS) {
+			printf("%s : %s %d: '%s'","SoundManager::LoadFile()","wav.Set() FAILED",error, path.c_str());
+			return invalid_Snd_ID;
+		}
+		if(wav.GetSamplingRate()!=config->sound.sample_rate || wav.GetBitsPerSample()!=config->sound.sample_bits) {
+			printf("%s : %s %d","SoundManager::LoadFile()","bad sample rate/bits", error);
+			return invalid_Snd_ID;
+		}
+		//cout << "Loading " << name << endl;
+		id=LoadBuffer(reinterpret_cast<char*>(wav.GetDataStart()),wav.GetDataEnd()-wav.GetDataStart());
+		delete [] sndbuf;
+		if(path.size()>MAX_NAME_LEN)
+			strncpy(sndlist[id].name,path.substr(path.size()-MAX_NAME_LEN).c_str(),MAX_NAME_LEN);
+		else
+			strncpy(sndlist[id].name,path.c_str(),MAX_NAME_LEN);
+	}
+	return id;
+}
+
+SoundManager::Snd_ID
+SoundManager::LoadBuffer(const char buf[], unsigned int len) {
+	cout << "SoundManager::LoadBuffer() of " << len << " bytes" << endl;
+	if(buf==NULL || len==0)
+		return invalid_Snd_ID;
+	AutoLock autolock(lock,ProcessID::getID());
+	//setup region
+	RCRegion * region=initRegion(len+MSG_SIZE);
+	//setup message
+	SoundManagerMsg * msg=new (reinterpret_cast<SoundManagerMsg*>(region->Base())) SoundManagerMsg;
+	Snd_ID msgid=sndlist.new_front();
+	msg->setAdd(msgid,sn);
+	//init sound structure
+	sndlist[msg->getID()].rcr=NULL;  // set by SoundPlay upon reception
+	sndlist[msg->getID()].data=NULL; // set by SoundPlay upon reception
+	sndlist[msg->getID()].ref=1;
+	sndlist[msg->getID()].len=len;
+	sndlist[msg->getID()].sn=sn;
+	//copy buffer, do any filtering needed here
+	const byte* src=reinterpret_cast<const byte*>(buf);
+	byte* dest=reinterpret_cast<byte*>(region->Base())+MSG_SIZE;
+	byte* end=dest+len;
+	if (config->sound.sample_bits==8)
+		while (dest < end)
+			*dest++ = *src++ ^ 0x80; // offset binary -> signed char 
+	else
+		while (dest < end)
+			*dest++ = *src++;
+	//cout << "SoundManager init region " << region->ID().key << endl;
+	//send message
+	if(ProcessID::getID()==ProcessID::SoundProcess) {
+		//if SoundPlay is preloading files, don't need to do inter-object comm
+		sndlist[msg->getID()].rcr=region;
+		sndlist[msg->getID()].data=reinterpret_cast<byte*>(region->Base()+MSG_SIZE);		
+	} else {
+#ifdef PLATFORM_APERIOS
+		//cout << "Send new at " << get_time() << '-';
+		subjs[ProcessID::getID()]->SetData(region);
+		subjs[ProcessID::getID()]->NotifyObservers();
+		//cout << get_time() << endl;
+#else
+		subjs[ProcessID::getID()]->sendMessage(region);
+		region->RemoveReference();
+#endif
+	}
+	return msgid;
+}
+	
+void
+SoundManager::ReleaseFile(std::string const &name) {
+	AutoLock autolock(lock,ProcessID::getID());
+	Release(lookupPath(config->sound.makePath(name)));
+}
+
+void
+SoundManager::Release(Snd_ID id) {
+	if(id==invalid_Snd_ID)
+		return;
+	if(sndlist[id].ref==0) {
+		cerr << "SoundManager::Release() " << id << " extra release" << endl;
+		return;
+	}
+	AutoLock autolock(lock,ProcessID::getID());
+	sndlist[id].ref--;
+	if(sndlist[id].ref==0) {
+		if(sndlist[id].rcr!=NULL) {
+			//The sound buffer is attached in the sound process, we need to detach it.
+			//Note that if this was NULL, we just assume that's because the message for the
+			//region is still in transit from the originating process, and erase the sndlist entry.
+			//Then when that buffer does arrive, we'll discover the sndlist entry is invalid and ignore it
+			if(ProcessID::getID()==ProcessID::SoundProcess) {
+				//we're currently running in sound process -- don't need to send ourselves an IPC message
+				sndlist[id].rcr->RemoveReference();
+				sndlist[id].rcr=NULL;
+			} else {
+				//we're currently running in a foreign process -- have to send message to sound process to release
+				//setup region
+				RCRegion * region=initRegion(MSG_SIZE);
+				//setup message
+				SoundManagerMsg * msg=new (reinterpret_cast<SoundManagerMsg*>(region->Base())) SoundManagerMsg;
+				msg->setDelete(sndlist[id].rcr);
+				//cout << "Sending delete msg for " << sndlist[id].name << endl;
+				//send message
+#ifdef PLATFORM_APERIOS
+				//cout << "Send delete at " << get_time() << '-';
+				subjs[ProcessID::getID()]->SetData(region);
+				subjs[ProcessID::getID()]->NotifyObservers();
+				//cout << get_time() << endl;
+#else
+				subjs[ProcessID::getID()]->sendMessage(region);
+				region->RemoveReference();
+#endif
+			}
+		}
+		//clean up sound data structure
+		sndlist[id].sn=0; // we use '1' for the first issued, so 0 marks it as invalid
+		sndlist.erase(id);
+	}
+}
+
+SoundManager::Play_ID
+SoundManager::PlayFile(std::string const &name) {
+  if(playlist.size()>=playlist_t::MAX_ENTRIES)
+		return invalid_Play_ID;	
+	AutoLock autolock(lock,ProcessID::getID());
+	Snd_ID sndid=LoadFile(name);
+	if(sndid==invalid_Snd_ID)
+		return invalid_Play_ID;
+	sndlist[sndid].ref--;
+	return Play(sndid);
+}
+
+SoundManager::Play_ID
+SoundManager::PlayBuffer(const char buf[], unsigned int len) {
+	if(playlist.size()>=playlist_t::MAX_ENTRIES || buf==NULL || len==0)
+		return invalid_Play_ID;	
+	AutoLock autolock(lock,ProcessID::getID());
+	Snd_ID sndid=LoadBuffer(buf,len);
+	if(sndid==invalid_Snd_ID)
+		return invalid_Play_ID;
+	sndlist[sndid].ref--;
+	return Play(sndid);
+}
+	
+SoundManager::Play_ID
+SoundManager::Play(Snd_ID id) {
+	//	cout << "Play " << id << endl;
+	if(id==invalid_Snd_ID)
+		return invalid_Play_ID;
+	AutoLock autolock(lock,ProcessID::getID());
+	Play_ID playid=playlist.new_front();
+	if(playid!=invalid_Play_ID) {
+		sndlist[id].ref++;
+		playlist[playid].snd_id=id;
+		playlist[playid].offset=0;
+		//playlist.size() should be greater than or equal to chanlist.size
+		//so if we got a playid, we can get a channel slot.
+		chanlist.push_front(playid);
+
+		//setup message to "wake-up" 
+		//(only really need if chanlist was empty)
+		//		if(chanlist.size()==1) { //commented out because sometimes doesn't wake up, thinks it's playing but isn't
+		if(ProcessID::getID()!=ProcessID::SoundProcess) {
+			RCRegion * region=initRegion(MSG_SIZE);
+			ASSERT(region!=NULL,"initRegion returned NULL");
+			SoundManagerMsg * msg=new (reinterpret_cast<SoundManagerMsg*>(region->Base())) SoundManagerMsg;
+			msg->setWakeup();
+#ifdef PLATFORM_APERIOS
+			//cout << "Send wakeup at " << get_time() << '-';
+			subjs[ProcessID::getID()]->SetData(region);
+			subjs[ProcessID::getID()]->NotifyObservers();
+			//cout << get_time() << endl;
+#else
+			subjs[ProcessID::getID()]->sendMessage(region);
+			region->RemoveReference();
+#endif
+		}
+		//		}
+		
+		if(sndlist[id].rcr!=NULL) {
+			const char * name=sndlist[playlist[playid].snd_id].name;
+			if(name[0]!='\0')
+				erouter->postEvent(EventBase::audioEGID,playid,EventBase::activateETID,0,name,1);
+			else
+				erouter->postEvent(EventBase::audioEGID,playid,EventBase::activateETID,0);
+		}
+	}
+	return playid;
+}
+	
+SoundManager::Play_ID
+SoundManager::ChainFile(Play_ID base, std::string const &next) {
+       if(base==invalid_Play_ID)
+		return base;
+	Play_ID orig=base;
+	while(playlist[base].next_id!=invalid_Play_ID)
+		base=playlist[base].next_id;
+	Play_ID nplay=playlist.new_front();
+	if(nplay==invalid_Play_ID)
+		return nplay;
+	Snd_ID nsnd=LoadFile(next);
+	if(nsnd==invalid_Snd_ID) {
+		playlist.pop_front();
+		return invalid_Play_ID;
+	}
+	playlist[nplay].snd_id=nsnd;
+	playlist[base].next_id=nplay;
+	return orig;
+}
+
+SoundManager::Play_ID
+SoundManager::ChainBuffer(Play_ID base, const char buf[], unsigned int len) {
+	if(base==invalid_Play_ID || buf==NULL || len==0)
+		return base;
+	Play_ID orig=base;
+	while(playlist[base].next_id!=invalid_Play_ID)
+		base=playlist[base].next_id;
+	Play_ID nplay=playlist.new_front();
+	if(nplay==invalid_Play_ID)
+		return nplay;
+	Snd_ID nsnd=LoadBuffer(buf,len);
+	if(nsnd==invalid_Snd_ID) {
+		playlist.pop_front();
+		return invalid_Play_ID;
+	}
+	playlist[nplay].snd_id=nsnd;
+	playlist[base].next_id=nplay;
+	return orig;
+}
+
+SoundManager::Play_ID
+SoundManager::Chain(Play_ID base, Snd_ID next) {
+	if(base==invalid_Play_ID || next==invalid_Snd_ID)
+		return base;
+	Play_ID orig=base;
+	while(playlist[base].next_id!=invalid_Play_ID)
+		base=playlist[base].next_id;
+	Play_ID nplay=playlist.new_front();
+	if(nplay==invalid_Play_ID)
+		return nplay;
+	playlist[nplay].snd_id=next;
+	playlist[base].next_id=nplay;
+	return orig;
+}
+
+void
+SoundManager::StopPlay() {
+	while(!playlist.empty())
+		StopPlay(playlist.begin());
+}
+
+void
+SoundManager::StopPlay(Play_ID id) {
+	if(id==invalid_Play_ID)
+		return;
+	AutoLock autolock(lock,ProcessID::getID());
+	//cout << "Stopping sound " << id << ": " << sndlist[playlist[id].snd_id].name << endl;
+	//we start at the back (oldest) since these are the most likely to be removed...
+	for(chanlist_t::index_t it=chanlist.prev(chanlist.end()); it!=chanlist.end(); it=chanlist.prev(it))
+		if(chanlist[it]==id) {
+			std::string name=sndlist[playlist[id].snd_id].name;
+			Release(playlist[id].snd_id);
+			playlist.erase(id);
+			chanlist.erase(it);
+			playlist[id].cumulative+=playlist[id].offset;
+			unsigned int ms=playlist[id].cumulative/(config->sound.sample_bits/8)/(config->sound.sample_rate/1000);
+			if(name.size()>0)
+				erouter->postEvent(EventBase::audioEGID,id,EventBase::deactivateETID,ms,name,0);
+			else
+				erouter->postEvent(EventBase::audioEGID,id,EventBase::deactivateETID,ms);
+			return;
+		}
+	cerr << "SoundManager::StopPlay(): " << id << " does not seem to be playing" << endl;
+}
+
+void
+SoundManager::PausePlay(Play_ID id) {
+	if(id==invalid_Play_ID)
+		return;
+	AutoLock autolock(lock,ProcessID::getID());
+	for(chanlist_t::index_t it=chanlist.begin(); it!=chanlist.end(); it=chanlist.next(it))
+		if(chanlist[it]==id) {
+			chanlist.erase(it);
+			return;
+		}
+}
+	
+void
+SoundManager::ResumePlay(Play_ID id) {
+	if(id==invalid_Play_ID)
+		return;
+	AutoLock autolock(lock,ProcessID::getID());
+	for(chanlist_t::index_t it=chanlist.begin(); it!=chanlist.end(); it=chanlist.next(it))
+		if(chanlist[it]==id)
+			return;
+	chanlist.push_front(id);
+}
+	
+void
+SoundManager::SetMode(unsigned int max_channels, MixMode_t mixer_mode, QueueMode_t queuing_mode) {
+	AutoLock autolock(lock,ProcessID::getID());
+	max_chan=max_channels;
+	mix_mode=mixer_mode;
+	queue_mode=queuing_mode;
+}
+
+unsigned int
+SoundManager::GetRemainTime(Play_ID id) const {
+	AutoLock autolock(lock,ProcessID::getID());
+	unsigned int t=0;
+	while(id!=invalid_Play_ID) {
+		t+=sndlist[playlist[id].snd_id].len-playlist[id].offset;
+		id=playlist[id].next_id;
+	}
+	const unsigned int bytesPerMS=config->sound.sample_bits/8*config->sound.sample_rate/1000;
+	return t/bytesPerMS;
+}
+
+void
+SoundManager::MixChannel(Play_ID channelId, void* buf, size_t destSize) {
+	char *dest = (char*) buf;
+	
+	PlayState& channel = playlist[channelId];
+	while (destSize > 0) {
+		const SoundData& buffer = sndlist[channel.snd_id];
+		const char* samples = ((char*) (buffer.data)) + channel.offset;
+		const unsigned int samplesSize = buffer.len - channel.offset;
+		if (samplesSize > destSize) {
+			memcpy(dest, samples, destSize);
+			channel.offset += destSize;
+			dest += destSize;
+			destSize = 0;
+			return;
+		} else {
+			memcpy(dest, samples, samplesSize);
+			channel.offset += samplesSize;
+			dest += samplesSize;
+			destSize -= samplesSize;
+			if (endPlay(channelId)) {
+				break;
+			}
+		}
+	}
+	if (destSize > 0) {
+		memset(dest, 0, destSize);
+	}
+}
+
+void
+SoundManager::MixChannelAdditively(Play_ID channelId, int bitsPerSample, MixMode_t mode,
+                                   short scalingFactor, void* buf, size_t destSize)
+{
+	PlayState& channel = playlist[channelId];
+	while (destSize > 0) {
+		const SoundData& buffer = sndlist[channel.snd_id];
+		const unsigned int samplesSize = buffer.len - channel.offset;
+		const unsigned int mixedSamplesSize =
+			((mode == Fast)
+				? ((samplesSize > destSize) ? destSize : samplesSize)
+				: ((samplesSize > destSize / 2) ? destSize / 2 : samplesSize)); 
+		
+		if (bitsPerSample == 8) {
+			//  8-bit mode
+			const char* samples = (char*) (buffer.data + channel.offset);
+			if (mode == Fast) {
+				// 8-bit mixing
+				char *dest = (char*) buf;
+				for (size_t i = 0; i < mixedSamplesSize; i++) {
+					*dest += samples[i] / scalingFactor;
+					dest++;
+				}
+				destSize -= (char*) dest - (char*) buf;
+				buf = dest;
+			} else {
+				// 16-bit mixing
+				short* dest = (short*) buf;
+				for (size_t i = 0; i < mixedSamplesSize; i++) {
+					*dest += samples[i];
+					*dest++;
+				}
+				destSize -= (char*) dest - (char*) buf;
+				buf = dest;
+			}
+		} else {
+			// 16-bit mode
+			const short* samples = (short*) (buffer.data + channel.offset);
+			if (mode == Fast) {
+				// 16-bit mixing
+				short* dest = (short*) buf;
+				for (size_t i = 0; i < mixedSamplesSize / 2; i++) {
+					*dest += samples[i] / scalingFactor;
+					*dest++;
+				}
+				destSize -= (char*) dest - (char*) buf;
+				buf = dest;
+			} else {
+				// 32-bit mixing
+				int* dest = (int*) buf;
+				for (size_t i = 0; i < mixedSamplesSize / 2; i++) {
+					*dest += samples[i];
+					*dest++;
+				}
+				destSize -= (char*) dest - (char*) buf;
+				buf = dest;
+			}
+		}
+		channel.offset += mixedSamplesSize;
+		if (destSize == 0) {
+			return;
+		} else {
+			if (endPlay(channelId)) {
+				return;
+			}
+		}
+	}
+}
+
+#ifdef PLATFORM_APERIOS
+unsigned int
+SoundManager::CopyTo(OSoundVectorData* data) {
+	AutoLock autolock(lock,ProcessID::getID());
+	return CopyTo(data->GetData(0), data->GetInfo(0)->dataSize);
+}
+
+void
+SoundManager::ReceivedMsg(const ONotifyEvent& event) {
+	//cout << "Got msg at " << get_time() << endl;
+	for(int x=0; x<event.NumOfData(); x++)
+		ProcessMsg(event.RCData(x));
+}
+#endif
+
+unsigned int SoundManager::CopyTo(void * dest, size_t destSize) {
+	AutoLock autolock(lock,ProcessID::getID());
+
+	void * origdest=dest;
+	size_t origDestSize=destSize;
+	if(chanlist.size() == 0) {
+		memset(dest, 0, destSize);
+		return 0;
+	}
+	
+	std::vector<Play_ID> channels;
+	selectChannels(channels);
+	
+	if (channels.size() == 0) {
+		// No channels to mix
+		memset(dest, 0, destSize); 
+	} else if (channels.size() == 1) {
+		// One channel to mix
+		MixChannel(channels.front(), dest, destSize);
+	} else {
+		// Several channels to mix	
+		const MixMode_t mode = mix_mode;
+		const int bitsPerSample = config->sound.sample_bits;
+		if (mode == Quality) {
+			// Quality mixing uses an intermediate buffer
+			if ((mixerBuffer == 0) || (mixerBufferSize < destSize * 2)) {
+				delete[] mixerBuffer;
+				mixerBuffer = 0;
+				mixerBufferSize = destSize * 2;
+				mixerBuffer = new int[(mixerBufferSize / 4) + 1]; // makes sure it's int-aligned
+			}
+			memset(mixerBuffer, 0,  mixerBufferSize);
+			dest = mixerBuffer;
+			destSize *= 2;
+		} else {
+			// Fast mixing does not use the intermeridate buffer
+			memset(dest, 0, destSize);
+		}
+		
+		const int channelCount = channels.size();
+		const short scalingFactor = (short) ((mode == Fast) ? channelCount : 1);  
+		for(std::vector<Play_ID>::iterator i = channels.begin(); i != channels.end(); i++)
+			MixChannelAdditively(*i, bitsPerSample, mode, scalingFactor, dest, destSize);
+		
+		if (mode == Quality) {
+			// Quality mixing uses an intermediate buffer
+			// Scale the buffer
+			destSize /= 2;
+			if (bitsPerSample == 8) {
+				//  8-bit mode
+				char* destChar = (char*) origdest;
+				short* mixerBufferShort = (short*) mixerBuffer;
+				for (size_t i = 0; i < destSize; i++) {
+					destChar[i] = (char) (mixerBufferShort[i] / channelCount);
+				} 
+			} else {
+				// 16-bit mode
+				short* destShort = (short*) origdest;
+				const size_t destSampleCount = destSize / 2; 
+				for (size_t i = 0; i < destSampleCount; i++) {
+					destShort[i] = (short) (mixerBuffer[i] / channelCount);
+				}
+			}
+		}
+	}
+	
+	updateChannels(channels, origDestSize);
+	return channels.size(); 
+}
+
+void SoundManager::ProcessMsg(RCRegion * rcr) {
+	SoundManagerMsg * msg = reinterpret_cast<SoundManagerMsg*>(rcr->Base());
+	//cout << "Processing " << msg << ": " << rcr->ID().key << endl;
+	switch(msg->type) {
+		case SoundManagerMsg::add: {
+			//cout << "it's an add of " << msg->id << ", sn=" << msg->sn << " (expecting " << sndlist[msg->id].sn << ", next sn is " << sn << ")" << endl;
+			//first check msg->id's validity, in case it was deleted while in-flight
+			/* //since Release marks deleted entries with serial number 0, we can get around this
+			bool valid=false;
+			for(Snd_ID it=sndlist.begin(); it!=sndlist.end(); it=sndlist.next(it)) {
+				if(it==msg->id) {
+					valid=true;
+					break;
+				}
+			}
+			if(!valid) {
+				//was deleted while buffer was still in-flight, ignore this message
+				break; //leaves switch statement, try next message if any
+			}
+			//now, even though the sound id is valid, verify the serial numbers match
+			*/
+			if(sndlist[msg->id].sn!=msg->sn) {
+				/*this means that the sound this message references was deleted while
+				* in-flight, even if some crazy process (perhaps the same one) has
+				* created and destroyed a number of sounds before we got this message */
+				/* So although there is a sound for this id, it's a different sound than
+				* the one this message refers to, and we should ignore this message */
+				cerr << "Warning: serial numbers don't match... may be pathological sound usage (many load/releases very quickly)" << endl;
+				break; //leaves switch statement, try next message if any
+			}
+			ASSERT(sndlist[msg->id].rcr==NULL,"The sndlist entry for an add message already has an attached region, I'm going to leak the old region")
+			rcr->AddReference();
+			sndlist[msg->id].rcr=rcr;
+			sndlist[msg->id].data=reinterpret_cast<byte*>(rcr->Base()+MSG_SIZE);
+			//look to see if there's any play's for the sound we just finished loading
+			for(playlist_t::index_t it=playlist.begin();it!=playlist.end();it=playlist.next(it))
+				if(playlist[it].snd_id==msg->id) {
+					//send an event if there are
+					const char * name=sndlist[playlist[it].snd_id].name;
+					if(name[0]!='\0')
+						erouter->postEvent(EventBase::audioEGID,it,EventBase::activateETID,0,name,1);
+					else
+						erouter->postEvent(EventBase::audioEGID,it,EventBase::activateETID,0);
+				}
+		} break;
+			case SoundManagerMsg::del: {
+				//cout << "it's an del" << endl;
+				if(msg->region==NULL) {
+					cerr << "SoundManager received a delete message for a NULL region" << endl;
+				} else {
+					msg->region->RemoveReference();
+				}
+			} break;
+			case SoundManagerMsg::wakeup: {
+				//cout << "it's a wakeup" << endl;
+				//doesn't need to do anything, just causes SoundPlay process to check activity
+			} break;
+			default:
+				printf("*** WARNING *** unknown SoundManager msg type received\n");
+	}
+}
+
+
+//protected:
+
+RCRegion*
+SoundManager::initRegion(unsigned int size) {
+	sn++; //so the first serial number handed out will be '1', leaving '0' as 'invalid'
+#ifdef PLATFORM_APERIOS
+	unsigned int pagesize=4096;
+	sError err=GetPageSize(&pagesize);
+	ASSERT(err==sSUCCESS,"Error "<<err<<" getting page size");
+	unsigned int pages=(size+pagesize-1)/pagesize;
+	return new RCRegion(pages*pagesize);
+#else
+	char name[RCRegion::MAX_NAME_LEN];
+	snprintf(name,RCRegion::MAX_NAME_LEN,"SndMsg.%d.%d",ProcessID::getID(),sn);
+	name[RCRegion::MAX_NAME_LEN-1]='\0';
+	//cout << "Created " << name << endl;
+	return new RCRegion(name,size);
+#endif
+}
+
+SoundManager::Snd_ID 
+SoundManager::lookupPath(std::string const &path) const {
+	std::string clippedPath;
+	const char* cpath=NULL;
+	if(path.size()>MAX_NAME_LEN) {  //compare against the end of the string if it's too long -- the end is more likely to be unique
+		clippedPath=path.substr(path.size()-MAX_NAME_LEN);
+		cpath=clippedPath.c_str();
+	} else
+		cpath=path.c_str();
+	for(sndlist_t::index_t it=sndlist.begin(); it!=sndlist.end(); it=sndlist.next(it)) {
+		if(strncasecmp(cpath,sndlist[it].name,MAX_NAME_LEN)==0)
+			return it;
+	}
+	return invalid_Snd_ID;
+}
+
+void
+SoundManager::selectChannels(std::vector<Play_ID>& mix) {
+	unsigned int selected=0;
+	switch(queue_mode) {
+	case Enqueue: { //select the oldest channels
+		for(chanlist_t::index_t it=chanlist.prev(chanlist.end());it!=chanlist.end();it=chanlist.prev(it)) {
+			if(sndlist[playlist[chanlist[it]].snd_id].data!=NULL) {
+				mix.push_back(chanlist[it]);
+				selected++;
+				if(selected==max_chan)
+					return;
+			}
+		}
+	} break;
+	case Override:
+	case Pause: { //select the youngest channels (difference between these two is in the final update)
+		for(chanlist_t::index_t it=chanlist.begin(); it!=chanlist.end(); it=chanlist.next(it)) {
+			if(sndlist[playlist[chanlist[it]].snd_id].data!=NULL) {
+				mix.push_back(chanlist[it]);
+				selected++;
+				if(selected==max_chan)
+					return;
+			}
+		}
+	} break;
+	case Stop: { //select the youngest, stop anything that remains
+		unsigned int numkeep=0;
+		chanlist_t::index_t it=chanlist.begin();
+		for(;it!=chanlist.end(); it=chanlist.next(it), numkeep++) {
+			if(sndlist[playlist[chanlist[it]].snd_id].data!=NULL) {
+				mix.push_back(chanlist[it]);
+				selected++;
+				if(selected==max_chan) {
+					for(unsigned int i=chanlist.size()-numkeep-1; i>0; i--)
+						endPlay(chanlist.back());
+					return;
+				}
+			}
+		}
+	} break;
+	default:
+		cout << "SoundManager::selectChannels(): Illegal queue mode" << endl;
+	}
+}
+
+void
+SoundManager::updateChannels(const std::vector<Play_ID>& mixs,size_t used) {
+	switch(queue_mode) {
+	case Enqueue:
+	case Pause:
+	case Stop: 
+		break;
+	case Override: { //increase offset of everything that wasn't selected
+		//assumes mode hasn't changed since the mix list was created... (so order is same as chanlist)
+		chanlist_t::index_t it=chanlist.begin(); 
+		std::vector<Play_ID>::const_iterator mixit=mixs.begin();
+		for(;it!=chanlist.end(); it=chanlist.next(it)) {
+			for(;mixit!=mixs.end(); mixit++) //some mixs may have been stopped during play
+				if(*mixit==chanlist[it])
+					break;
+			if(mixit==mixs.end())
+				break;
+		}
+		for(;it!=chanlist.end(); it=chanlist.next(it)) {
+			const Play_ID channelId = chanlist[it];
+			PlayState &channel = playlist[channelId];
+			size_t skip = used;
+			while (skip > 0) {
+				SoundData &buffer = sndlist[channel.snd_id];
+				// FIXME: Don't know why the buffer.data != 0 check is done 
+				if (buffer.data != 0) {
+					size_t remain = buffer.len - channel.offset;
+					if (remain < skip) {
+						channel.offset = buffer.len;
+						skip -= buffer.len;
+						if (endPlay(channelId)) {
+							break;
+						}
+					} else {
+						channel.offset += skip;
+						skip = 0;
+					}
+				} else {
+					break;
+				}
+			}
+		}
+	} break;
+	default:
+		cout << "SoundManager::updateChannels(): Illegal queue mode" << endl;
+	}
+}
+
+bool
+SoundManager::endPlay(Play_ID id) {
+	if(playlist[id].next_id==invalid_Play_ID) {
+		StopPlay(id);
+		return true;
+	} else {
+		//copies the next one into current so that the Play_ID consistently refers to the same "sound"
+		Play_ID next=playlist[id].next_id;
+		//		cout << "play " << id << " moving from " << playlist[id].snd_id << " to " << playlist[next].snd_id << endl;
+		Release(playlist[id].snd_id);
+		playlist[id].snd_id=playlist[next].snd_id;
+		playlist[id].cumulative+=playlist[id].offset;
+		playlist[id].offset=0;
+		playlist[id].next_id=playlist[next].next_id;
+		playlist.erase(next);
+		unsigned int ms=playlist[id].cumulative/(config->sound.sample_bits/8)/(config->sound.sample_rate/1000);
+		const char * name=sndlist[playlist[id].snd_id].name;
+		if(name[0]!='\0')
+			erouter->postEvent(EventBase::audioEGID,id,EventBase::statusETID,ms,name,1);
+		else
+			erouter->postEvent(EventBase::audioEGID,id,EventBase::statusETID,ms);
+		return false;
+	}
+}
+
+SoundManager::SoundData::SoundData()
+	: rcr(NULL), data(NULL), len(0), ref(0), sn(0)
+{
+	name[0]='\0';
+}
+
+SoundManager::PlayState::PlayState()
+	: snd_id(invalid_Snd_ID), offset(0), cumulative(0), next_id(invalid_Play_ID)
+{}
+
+
+/*! @file
+ * @brief Implements SoundManager, which provides sound effects and caching services, as well as mixing buffers for the SoundPlay process
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:53 $
+ */
+
+
+
+
+//This is a faster mix algo using bit shifting, but it doesn't work with
+// non power of two number of channels, despite my efforts... eh, maybe
+// i'll fix it later...
+		// NOT WORKING
+		/*
+		if(mixs.size()==2 || mix_mode==Fast) {
+			unsigned int shift=0;
+			unsigned int offset=0;
+			unsigned int tmp=mixs.size();
+			while(tmp>1) {
+				tmp>>=1;
+				shift++;
+			}
+			unsigned int mask;
+			if(config->sound.sample_bits==8) {
+				unsigned int c=(unsigned char)~0;
+				c>>=shift;
+				mask=(c<<24)|(c<<16)|(c<<8)|c;
+				offset=(1<<7)|(1<<15)|(1<<23)|(1<<31);
+			} else {
+				unsigned int c=(unsigned short)~0;
+				c>>=shift;
+				mask=(c<<16)|c;
+				offset=(1<<31)|(1<<15);
+			}
+			memset(dest,0,avail);
+			for(unsigned int c=0; c<mixs.size(); c++) {
+				if(ends[c]-srcs[c]>avail) {
+					for(unsigned int * beg=(unsigned int*)dest;beg<(unsigned int*)end;beg++) {
+						const unsigned int src=*(unsigned int*)srcs[c];
+						if(beg==(unsigned int*)dest) {
+							cout << src <<' '<< (void*)src << endl;
+							unsigned int x=((src^offset)>>shift)&mask;
+							cout << x <<' '<< (void*)x << endl;
+							cout << "****" << endl;
+						}
+						*beg+=((src^offset)>>shift)&mask;
+						if(beg==(unsigned int*)dest)
+							cout << *beg <<' '<< (void*)*beg << endl << "########" << endl;
+						srcs[c]+=sizeof(int);
+					}
+					playlist[mixs[c]].offset+=avail;
+				} else {
+					unsigned int * beg=(unsigned int*)dest;
+					for(;srcs[c]<ends[c];srcs[c]+=sizeof(int)) {
+						const unsigned int src=*(unsigned int*)srcs[c];
+						*beg+=((src^offset)>>shift)&mask;
+						beg++;
+					}
+					for(;beg<(unsigned int*)end; beg++)
+						*beg+=offset>>shift;
+					playlist[mixs[c]].offset=sndlist[playlist[mixs[c]].snd_id].len;
+					StopPlay(mixs[c]);
+				}
+			}
+			unsigned int leftover=(offset>>shift)*((1<<shift)-mixs.size());
+			for(unsigned int * beg=(unsigned int*)dest;beg<(unsigned int*)end;beg++)
+				*beg=*(beg+leftover)^offset;
+			updateChannels(avail);
+			return mixs.size();
+			} else*/
diff -urdN ../Tekkotsu_2.3/Sound/SoundManager.h ./Sound/SoundManager.h
--- ../Tekkotsu_2.3/Sound/SoundManager.h	Wed Dec 31 19:00:00 1969
+++ ./Sound/SoundManager.h	Sun Aug  7 00:11:04 2005
@@ -0,0 +1,309 @@
+//-*-c++-*-
+#ifndef INCLUDED_SoundManager_h_
+#define INCLUDED_SoundManager_h_
+
+#include "IPC/RCRegion.h"
+#include "Shared/ODataFormats.h"
+
+#include <string>
+#include <vector>
+#include "IPC/ListMemBuf.h"
+#include "IPC/MutexLock.h"
+#include "SoundManagerMsg.h"
+#include "IPC/ProcessID.h"
+
+#ifdef PLATFORM_APERIOS
+class OSubject;
+class ONotifyEvent;
+#else
+#  include "IPC/MessageQueue.h"
+#endif
+
+//! Provides sound effects and caching services, as well as mixing buffers for the SoundPlay process
+/*! Provides easy methods for playing back sounds, either from files
+ *  on the memory stick, or from dynamically generated buffers.  You
+ *  can chain playback commands so that when one sound finishes,
+ *  another picks up automatically.  This might be handy if, say,
+ *  someone wants to write an MP3 player ;) The sounds would be too
+ *  large to load into memory all at once, but you could load a block
+ *  at a time and chain them so it seamlessly moves from one to the
+ *  other.
+ *  
+ *  You can also preload sounds (LoadFile()) before playing them so
+ *  there's no delay while loading after you request a sound to be
+ *  played.  Just be sure to release the file (ReleaseFile()) again
+ *  when you're done with it ;)
+ *
+ *  All functions will attempt to lock the SoundManager.  Remember,
+ *  this is running in a shared memory region, accessible by the
+ *  SoundPlay process and both the Main and Motion processes (so
+ *  MotionCommands can play sounds!)
+ *
+ *  One could be tempted to draw parallels to the MotionManager, and
+ *  envision a system with SoundCommands that are handed over and can
+ *  dynamically compute sound buffers as needed.  If you have the time
+ *  and inclination, the job's all yours... (Midi players, speech
+ *  synthesizer, ...?)
+ *
+ *  @todo Volume control, variable playback speed, support more wav
+ *  file formats (latter two are the same thing if you think about it
+ *  - need to be able to resample on the fly)
+ *  
+ *  @todo Add functions to hand out regions to be filled out to avoid
+ *  copying into the buffer.
+ */
+class SoundManager {
+public:
+	virtual ~SoundManager();
+
+	//!constructor, should only be called by the receiving process (SoundPlay)
+	SoundManager();
+#ifdef PLATFORM_APERIOS
+	//!Each process needs to call this before it can send sounds to the SoundPlay process
+	void InitAccess(OSubject* subj);
+#else //PLATFORM_LOCAL
+	//!Each process (except SoundPlay) needs to call this before it can send sounds to the SoundPlay process
+	void InitAccess(MessageQueueBase& sndbufq);
+#endif
+	
+	//!This is used for referring to sound data so you can start playing it or release it
+	typedef SoundManagerMsg::Snd_ID Snd_ID;
+	static const Snd_ID invalid_Snd_ID=(Snd_ID)-1; //!< for reporting errors
+	static const Snd_ID MAX_SND=50; //!< the number of sounds that can be loaded at any given time
+	
+	//!This is for referring to instances of the play command so you can stop, pause, or monitor progress (later versions will send events upon completion)
+	typedef unsigned short Play_ID;
+	static const Play_ID invalid_Play_ID=(Play_ID)-1; //!< for reporting errors
+	static const Play_ID MAX_PLAY=256; //!< the number of sounds that can be enqueued at the same time (see MixMode_t)
+
+	static const unsigned int MAX_NAME_LEN=128;   //!<maximum length of a path
+
+	//!Used to set the mode for mixing multiple sound channels
+	/*!Feel free to add a higher quality mixer if you're an audiophile - I'm pretty new to sound processing*/
+	enum MixMode_t {
+		// there's some prototype code for a bit-shifting 'Faster' quality level, but it hasn't been finished... 'Fast' is the default for now.
+		Fast,    //!< uses real division to maintain volume level, without increasing intermediary precision, which causes low-order bit error in exchange for less CPU usage
+		Quality  //!< uses real division to maintain volume level, using an intermediary higher precision buffer for mixing
+	};
+
+	enum QueueMode_t {
+		Enqueue,        //!< newer sounds are played when a channel opens up (when old sound finishes)
+		Pause,          //!< newer sounds pause oldest sound, which continues when a channel opens
+		Stop,           //!< newer sounds stop oldest sound
+		Override,       //!< older sounds have play heads advanced, but don't get mixed until a channel opens
+	};
+
+	//!loads a wav file (if it matches Config::sound_config settings - can't do resampling yet)
+	/*!Since the SoundManager does the loading, if the same file is being played more than once, only once copy is stored in memory 
+	 * @param name can be either a full path, or a partial path relative to Config::sound_config::root
+	 * @return ID number for future references (can also use name)
+	 * The sound data will be cached until ReleaseFile() or Release() is called a matching number of times*/
+	Snd_ID LoadFile(std::string const &name);
+
+	//!loads raw samples from a buffer (assumes matches Config::sound_config settings)
+	/*!The sound data will be cached until Release() is called a matching number of times.\n
+	 * This function is useful for dynamic sound sources.  A copy will be made. */
+	Snd_ID LoadBuffer(const char buf[], unsigned int len);
+	
+	//!Marks the sound buffer to be released after the last play command completes (or right now if not being played)
+	void ReleaseFile(std::string const &name);
+
+	//!Marks the sound buffer to be released after the last play command completes (or right now if not being played)
+	void Release(Snd_ID id);
+	
+	//!play a wav file (if it matches Config::sound_config settings - can't do resampling yet)
+	/*!Will do a call to LoadFile() first, and then automatically release the sound again when complete.
+	 * @param name can be either a full path, or a partial path relative to Config::sound_config::root
+	 * @return ID number for future references
+	 * The sound data will not be cached after done playing unless a call to LoadFile is made*/
+	Play_ID PlayFile(std::string const &name);
+
+	//!loads raw samples from a buffer (assumes buffer matches Config::sound_config settings)
+	/*!The sound data will be released after done playing*/
+	Play_ID PlayBuffer(const char buf[], unsigned int len);
+	
+	//!plays a previously loaded buffer or file
+	Play_ID Play(Snd_ID id);
+	
+	//!allows automatic queuing of sounds - good for dynamic sound sources!
+	/*!if you chain more than once to the same base, the new buffers are appended
+	 * to the end of the chain - the new buffer doesn't replace the current chain
+	 * @return @a base - just for convenience of multiple calls*/
+	Play_ID ChainFile(Play_ID base, std::string const &next);
+
+	//!allows automatic queuing of sounds - good for dynamic sound sources!
+	/*!if you chain more than once to the same base, the new buffers are appended
+	 * to the end of the chain - the new buffer doesn't replace the current chain
+	 * @return @a base - just for convenience of multiple calls*/
+	Play_ID ChainBuffer(Play_ID base, const char buf[], unsigned int len);
+
+	//!allows automatic queuing of sounds - good for dynamic sound sources!
+	/*!if you chain more than once to the same base, the new buffers are appended
+	 * to the end of the chain - the new buffer doesn't replace the current chain
+	 * @return @a base - just for convenience of multiple calls*/
+	Play_ID Chain(Play_ID base, Snd_ID next);
+	
+	//!Lets you stop playback of all sounds
+	void StopPlay();
+
+	//!Lets you stop playback of a sound
+	void StopPlay(Play_ID id);
+	
+	//!Lets you pause playback
+	void PausePlay(Play_ID id);
+	
+	//!Lets you resume playback
+	void ResumePlay(Play_ID id);
+	
+	//!Lets you control the maximum number of channels (currently playing sounds), method for mixing (applies when max_chan>1), and queuing method (for when overflow channels)
+	void SetMode(unsigned int max_channels, MixMode_t mixer_mode, QueueMode_t queuing_mode);
+
+	//!Gives the time until the sound finishes, in milliseconds.  Subtract 32 to get guarranteed valid time for this ID.
+	/*!You should be passing the beginning of a chain to get proper results...\n
+	 * May be slightly conservative (will report too small a time) because this
+	 * does not account for delay until SoundPlay picks up the message that a
+	 * sound has been added.\n
+	 * However, it is slighly optimistic (will report too large a time) because
+	 * it processes a buffer all at one go, so it could mark the sound as finished
+	 * (and cause the ID to go invalid) up to RobotInfo::SoundBufferTime (32 ms)
+	 * before the sound finishes.  So subtract SoundBufferTime if you want to be
+	 * absolutely sure the ID will still valid. */
+	unsigned int GetRemainTime(Play_ID id) const;
+	
+#ifdef PLATFORM_APERIOS
+	//!Copies the sound data to the OPENR buffer, ready to be passed to the system, only called by SoundPlay
+	/*!@return the number of active sounds */
+	unsigned int CopyTo(OSoundVectorData* data);
+
+	//!updates internal data structures on the SoundPlay side - you shouldn't be calling this
+	void ReceivedMsg(const ONotifyEvent& event);
+#endif
+
+	//!Copies the sound data to the specified memory buffer, ready to be passed to the system
+	/*!@return the number of active sounds */
+	unsigned int CopyTo(void * dest, size_t destSize);
+	
+	//!updates internal data structures on the SoundPlay side - you shouldn't be calling this
+	void ProcessMsg(RCRegion * rcr);
+	
+	//! returns number of sounds currently playing
+	unsigned int GetNumPlaying() { return chanlist.size(); }
+	
+protected:
+	//!Mixes the channel into the buffer
+	void MixChannel(Play_ID channelId, void* buf, size_t size);
+	
+	//!Mixes the channel into the buffer additively
+	/*!If mode is Quality, then the size of the buffer should be double the normal
+	* size. */
+	void MixChannelAdditively(Play_ID channelId, int bitsPerSample, MixMode_t mode, short scalingFactor, void* buf, size_t size);
+	
+	//!The intermediate mixer buffer used for Quality mode mixing
+	int* mixerBuffer;
+	
+	//!Size (in bytes) of the intermediate mixer buffer
+	size_t mixerBufferSize;
+
+	//!Sets up a shared region to hold a sound - rounds to nearest page size
+	RCRegion* initRegion(unsigned int size);
+
+	//!Looks to see if @a name matches any of the sounds in sndlist (converts to absolute path if not already)
+	Snd_ID lookupPath(std::string const &name) const;
+
+	//!selects which of the channels are actually to be mixed together, depending on queue_mode
+	void selectChannels(std::vector<Play_ID>& mix);
+
+	//!update the offsets of sounds which weren't mixed (when needed depending on queue_mode)
+	void updateChannels(const std::vector<Play_ID>& mixs,size_t used);
+
+	//!called when a buffer end is reached, may reset buffer to next in chain, or just StopPlay()
+	bool endPlay(Play_ID id);
+
+	//!Holds data about the loaded sounds
+	struct SoundData {
+		SoundData();                             //!<constructor
+		RCRegion * rcr;                          //!<shared region - don't need to share among processes, just collect in SoundPlay
+		byte* data;                              //!<point to data in region (for convenience, only valid in SoundPlay)
+		unsigned int len;                        //!<size of the sound
+		unsigned int ref;                        //!<reference counter
+		unsigned int sn;                         //!<serial number, allows us to verify that a given message buffer does indeed match this sound, and wasn't delayed in processing
+		char name[SoundManager::MAX_NAME_LEN];   //!<stores the path to the file, empty if from a buffer
+	private:
+		SoundData(const SoundData&);             //!< don't call
+		SoundData operator=(const SoundData&);   //!< don't call
+	};
+	//!For convenience
+	typedef ListMemBuf<SoundData,MAX_SND,Snd_ID> sndlist_t;
+	//!Holds a list of all currently loaded sounds
+	sndlist_t sndlist;
+	
+	//!Holds data about sounds currently being played
+	struct PlayState {
+		PlayState();            //!<constructor
+		Snd_ID snd_id;          //!<index of sound
+		unsigned int offset;    //!<position in the sound
+		unsigned int cumulative;//!<total time of playing (over queued sounds)
+		Play_ID next_id;        //!<lets you queue for continuous sound, or loop
+	};
+	//!For convenience
+	typedef ListMemBuf<PlayState,MAX_PLAY,Play_ID> playlist_t;
+	//!Holds a list of all sounds currently enqueued
+	playlist_t playlist;
+	//!For convenience
+	typedef ListMemBuf<Play_ID,MAX_PLAY,Play_ID> chanlist_t;
+	//!Holds a list of all currently playing sounds, ordered newest (front) to oldest(back)
+	chanlist_t chanlist;
+	
+	//!Current mixing mode, set by SetMode();
+	MixMode_t mix_mode;
+
+	//!Current queuing mode, set by SetMode();
+	QueueMode_t queue_mode;
+
+	//!Current maximum number of sounds to mix together
+	unsigned int max_chan;
+
+	//!Prevents multiple processes from accessing at the same time
+	mutable MutexLock<ProcessID::NumProcesses> lock;
+	
+	//!A serial number, incremented for each sound which is created
+	/*! This is used to verify that a sound message from a process
+	 *  refers to a current sound.  If you imaging a pathological
+	 *  process, which rapidly creates and releases sounds, it would 
+	 *  run through the sndlist ids, possibly before the sound process
+	 *  can process the incoming buffers.  So this is used to ensure
+	 *  that a given message refers to the current sound, and not one
+	 *  that was already released and then reassigned. */
+	unsigned int sn;
+
+	//!the size of a SoundManagerMsg, which is prefixed before each region sent/received by SoundManager (rounded up to nearest even word boundary)
+	static const unsigned int MSG_SIZE=((sizeof(SoundManagerMsg)-1)/8+1)*8;
+
+#ifdef PLATFORM_APERIOS
+	//!Storage of each process's subject object, used to internally transmit sound buffers to SoundPlay
+	OSubject * subjs[ProcessID::NumProcesses];
+#else //PLATFORM_LOCAL
+	//!Storage of each process's attachment of the message queue, used to internally transmit sound buffers to SoundPlay
+	MessageQueueBase * subjs[ProcessID::NumProcesses];
+#endif
+
+private:
+	SoundManager(const SoundManager&);           //!< don't call
+	SoundManager operator=(const SoundManager&); //!< don't call
+};
+
+//! lets you play a sound from anywhere in your code - just a one liner!
+extern SoundManager * sndman;
+
+/*! @file
+ * @brief Describes SoundManager, which provides sound effects and caching services, as well as mixing buffers for the SoundPlay process
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:04 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Sound/SoundManagerMsg.h ./Sound/SoundManagerMsg.h
--- ../Tekkotsu_2.3/Sound/SoundManagerMsg.h	Wed Dec 31 19:00:00 1969
+++ ./Sound/SoundManagerMsg.h	Wed Jun  1 01:47:54 2005
@@ -0,0 +1,70 @@
+//-*-c++-*-
+#ifndef INCLUDED_SoundManagerMsg_h
+#define INCLUDED_SoundManagerMsg_h
+
+class RCRegion;
+
+//! A small header that preceeds data sent by SoundManager between processes
+struct SoundManagerMsg {
+private:
+	friend class SoundManager;
+
+	//! the type to use when referring to Sounds
+	typedef unsigned short Snd_ID;
+
+	//! Denotes what type of message this is
+	enum MsgType { add, del, wakeup, unknown } type;
+	
+	//! The id of the sound this is in reference to
+	Snd_ID id;
+
+	//! The RCRegion to free, if it's a deletion
+	RCRegion * region;
+	
+	//! The serial number of the sound this is in reference to, see SoundManager::sn
+	unsigned int sn;
+	
+	//! constructor
+	SoundManagerMsg() : type(unknown), id(static_cast<Snd_ID>(-1)), region(NULL), sn(-1U) {}
+
+	//! virtual destructor
+	/*! doesn't do anything, but don't remove it, otherwise this would no longer be a virtual base class */
+	virtual ~SoundManagerMsg() {}
+
+	//! Accessor for the id number, set by SoundManager
+	Snd_ID getID() const { return id; }
+
+	//! Sets up the header as an add message
+	void setAdd(Snd_ID sndid, unsigned int sndsn) {
+		type=add;
+		id=sndid;
+		sn=sndsn;
+	}
+
+	//! Sets up the header as an erase message
+	void setDelete(RCRegion* rcregion) {
+		type=del;
+		region=rcregion;
+	}
+	
+	//! Sets up the header as a wakeup message
+	void setWakeup() {
+		type=wakeup;
+	}
+
+	SoundManagerMsg(const SoundManagerMsg&); //!< don't call
+	SoundManagerMsg operator=(const SoundManagerMsg&); //!< don't call
+};
+
+/*! @file
+ * @brief Defines SoundManagerMsg, a small header used by SoundManager for sending messages between processes
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:54 $
+ */
+
+#endif // INCLUDED_SoundManagerMsg_h
diff -urdN ../Tekkotsu_2.3/Sound/WAV.cc ./Sound/WAV.cc
--- ../Tekkotsu_2.3/Sound/WAV.cc	Wed Dec 31 19:00:00 1969
+++ ./Sound/WAV.cc	Wed Jun  1 01:47:54 2005
@@ -0,0 +1,251 @@
+/*! @file
+ * @brief Allows you to load WAV files from the memory stick
+ * @author Sony (Creator)
+ *
+ * This file is from the SoundPlay example from the Sony sample code, with a few if any modifications.
+ * Here's the license Sony provided with it:
+ *
+ * Copyright 2002,2003 Sony Corporation 
+ *
+ * Permission to use, copy, modify, and redistribute this software for
+ * non-commercial use is hereby granted.
+ *
+ * This software is provided "as is" without warranty of any kind,
+ * either expressed or implied, including but not limited to the
+ * implied warranties of fitness for a particular purpose.
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:54 $
+ */
+
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OPENR.h>
+#  include <OPENR/OSyslog.h>
+#endif
+#include "WAV.h"
+#include <cstring>
+#include <stdio.h>
+
+WAV::WAV() : soundInfo(), soundUnitSize(0), dataStart(0), dataEnd(0), dataCurrent(0)
+{
+}
+
+WAV::WAV(byte* addr) : soundInfo(), soundUnitSize(0), dataStart(0), dataEnd(0), dataCurrent(0)
+{
+    Set(addr);
+}
+
+WAVError
+WAV::Set(byte *addr)
+{
+    //
+    // Check Wav Header
+    //
+    if (strncmp((char *)addr, "RIFF", 4)) return WAV_NOT_RIFF;
+    addr += 4;
+
+    longword length = get_longword(addr);
+    addr += sizeof(longword);
+		//    OSYSDEBUG(( "length = %x\n", length));
+
+    if (strncmp((char *)addr, "WAVE", 4)) return WAV_NOT_WAV;
+    length -= 4;
+    addr += 4;
+
+    //
+    // Check Chunk
+    //
+    while (length > 8) {
+
+        size_t chunksize;
+        char *buf = (char *)addr;
+    
+        addr += 4;
+
+        chunksize = get_longword(addr);
+        addr += sizeof(longword);
+        length -= chunksize + 8;
+
+        if (!strncmp(buf, "fmt ", 4)) {
+
+            //
+            // Format Chunk
+            //
+
+            //
+            // Check WAV Type
+            //
+            soundInfo.format = (OSoundFormat)get_word(addr);
+            addr += sizeof(word);
+            if (soundInfo.format != osoundformatPCM) {
+                printf(("WAV_FORMAT_NOT_SUPPORTED\n"));
+                return WAV_FORMAT_NOT_SUPPORTED;
+            }
+
+            //
+            // Channel
+            //
+            soundInfo.channel = (OSoundChannel)get_word(addr);
+            addr += sizeof(word);
+            if (soundInfo.channel != osoundchannelMONO) {
+                printf(("WAV_CHANNEL_NOT_SUPPORTED\n"));
+                return WAV_CHANNEL_NOT_SUPPORTED;
+            }
+
+            //
+            // Sampling Rate
+            //
+            longword frq = get_longword(addr);
+            addr += sizeof(longword);
+            soundInfo.samplingRate = (word)frq;
+            if (soundInfo.samplingRate != 8000 &&
+                soundInfo.samplingRate != 16000) {
+                printf(("WAV_SAMPLINGRATE_NOT_SUPPORTED\n"));
+                return WAV_SAMPLINGRATE_NOT_SUPPORTED;
+            }
+
+            //
+            // DataSize Per sec
+            //
+            addr += sizeof(longword);
+
+            //
+            // Block Size
+            //
+            addr += sizeof(word);
+
+            //
+            // Bits Of Sample
+            //
+            soundInfo.bitsPerSample = get_word(addr);
+            addr += sizeof(word);
+            soundInfo.bitsPerSample *= soundInfo.channel;
+            if (soundInfo.bitsPerSample != 8 &&
+                soundInfo.bitsPerSample != 16) {
+                printf(("WAV_BITSPERSAMPLE_NOT_SUPPORTED\n"));
+                return WAV_BITSPERSAMPLE_NOT_SUPPORTED;
+            }
+
+            //
+            // Skip Extentded Infomation
+            //
+            addr += chunksize - FMTSIZE_WITHOUT_EXTINFO;
+            
+						//            OSYSDEBUG(( "fmt chunksize = %d\n", chunksize));
+						//            OSYSDEBUG(( "samplingRate  = %d\n", soundInfo.samplingRate));
+						//            OSYSDEBUG(( "bitsPerSample = %d\n", soundInfo.bitsPerSample));
+            
+        } else if (!strncmp(buf, "data", 4)) {
+
+            //
+            // Data Chunk
+            //
+					//            OSYSDEBUG(( "data chunksize = %d\n", chunksize));
+            soundInfo.dataSize = chunksize;
+            dataStart = dataCurrent = addr;
+            dataEnd = dataStart + soundInfo.dataSize;
+            break;
+
+        } else {
+
+            //
+            // Fact Chunk
+            //
+            addr += chunksize;
+        }
+    }
+
+    int rate = soundInfo.samplingRate;
+    int bits = soundInfo.bitsPerSample;
+    if (rate == 8000 & bits == 8) {
+        soundUnitSize = MONO8K8B_UNIT_SIZE;
+    } else if (rate == 16000 & bits == 16) {
+        soundUnitSize = MONO16K16B_UNIT_SIZE;
+    }
+    
+    return WAV_SUCCESS;
+}
+
+WAVError
+WAV::CopyTo(OSoundVectorData* data)
+{
+    if (dataCurrent >= dataEnd) return WAV_FAIL;
+    
+    OSoundInfo* sinfo = data->GetInfo(0);
+    if (soundUnitSize > sinfo->maxDataSize) {
+        printf(("WAV_SIZE_NOT_ENOUGH "));
+        return WAV_SIZE_NOT_ENOUGH;
+    }
+
+    sinfo->dataSize      = soundUnitSize;
+    sinfo->format        = soundInfo.format;
+    sinfo->channel       = soundInfo.channel;
+    sinfo->samplingRate  = soundInfo.samplingRate;
+    sinfo->bitsPerSample = soundInfo.bitsPerSample;
+
+    byte* src  = dataCurrent;
+    byte* dest = data->GetData(0);
+    byte* end;
+    int num = (int)(dataEnd - dataCurrent);
+
+    if (soundUnitSize <= (unsigned int)num) {
+    
+        end = dest + soundUnitSize;
+        if (soundUnitSize == MONO8K8B_UNIT_SIZE) {
+            while (dest < end) {
+                *dest++ = *src++ ^ 0x80; // offset binary -> signed char
+            }
+        } else { // MONO16K16B_UNIT_SIZE
+            while (dest < end) {
+                *dest++ = *src++;
+            }
+        }
+        dataCurrent += soundUnitSize;
+
+    } else {
+
+        end = dest + num;
+        if (soundUnitSize == MONO8K8B_UNIT_SIZE) {
+            while (dest < end) {
+                *dest++ = *src++ ^ 0x80; // offset binary -> signed char
+            }
+        } else { // MONO16K16B_UNIT_SIZE
+            while (dest < end) {
+                *dest++ = *src++;
+            }
+        }
+        memset(dest, 0x0, soundUnitSize - num);
+        dataCurrent = dataEnd;
+
+    }
+
+    return WAV_SUCCESS;
+}
+
+WAVError
+WAV::Rewind()
+{
+    dataCurrent = dataStart;
+    return WAV_SUCCESS;
+}
+
+longword
+WAV::get_longword(byte* ptr)
+{
+    longword lw0 = (longword)ptr[0];
+    longword lw1 = (longword)ptr[1] << 8;
+    longword lw2 = (longword)ptr[2] << 16;
+    longword lw3 = (longword)ptr[3] << 24;
+    return lw0 + lw1 + lw2 + lw3;
+}
+
+word
+WAV::get_word(byte* ptr)
+{
+    word w0 = (word)ptr[0];
+    word w1 = (word)ptr[1] << 8;
+    return w0 + w1;
+}
diff -urdN ../Tekkotsu_2.3/Sound/WAV.h ./Sound/WAV.h
--- ../Tekkotsu_2.3/Sound/WAV.h	Wed Dec 31 19:00:00 1969
+++ ./Sound/WAV.h	Wed Jun  1 01:47:54 2005
@@ -0,0 +1,80 @@
+/*! @file
+ * @brief Allows you to load WAV files from the memory stick
+ * @author Sony (Creator)
+ *
+ * This file is from the SoundPlay example from the Sony sample code, with a few if any modifications.
+ * Here's the license Sony provided with it:
+ *
+ * Copyright 2002,2003 Sony Corporation 
+ *
+ * Permission to use, copy, modify, and redistribute this software for
+ * non-commercial use is hereby granted.
+ *
+ * This software is provided "as is" without warranty of any kind,
+ * either expressed or implied, including but not limited to the
+ * implied warranties of fitness for a particular purpose.
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:47:54 $
+ */
+
+#ifndef WAV_h_DEFINED
+#define WAV_h_DEFINED
+
+#include "Shared/ODataFormats.h"
+
+enum WAVError {
+    WAV_SUCCESS,
+    WAV_FAIL,
+    WAV_NOT_RIFF,
+    WAV_NOT_WAV,
+    WAV_FORMAT_NOT_SUPPORTED,
+    WAV_CHANNEL_NOT_SUPPORTED,
+    WAV_SAMPLINGRATE_NOT_SUPPORTED,
+    WAV_BITSPERSAMPLE_NOT_SUPPORTED,
+    WAV_SIZE_NOT_ENOUGH,
+};
+
+class WAV {
+public:
+    WAV();
+    WAV(byte* addr);
+    ~WAV() {}
+
+    WAVError Set(byte *addr);
+    WAVError CopyTo(OSoundVectorData* data);
+    WAVError Rewind();
+
+    unsigned int    GetSamplingRate()  { return soundInfo.samplingRate;  }
+    unsigned int    GetBitsPerSample() { return soundInfo.bitsPerSample; }
+    size_t GetSoundUnitSize() { return soundUnitSize;           }
+		
+		byte*  GetDataStart()     { return dataStart;               }
+		byte*  GetDataEnd()       { return dataEnd;                 }
+
+private:
+    longword get_longword(byte* addr);
+    word     get_word(byte* addr);
+
+    // 8KHz 8bits MONO (8 * 1 * 1 * 32ms = 256)
+    static const size_t MONO8K8B_UNIT_SIZE  = 256;
+
+    // 16KHz 16bits MONO (16 * 2 * 1 * 32ms = 1024)
+    static const size_t MONO16K16B_UNIT_SIZE  = 1024;
+
+    static const size_t FMTSIZE_WITHOUT_EXTINFO = 16;
+
+    OSoundInfo soundInfo;
+    size_t     soundUnitSize;
+    byte*      dataStart;
+    byte*      dataEnd;
+    byte*      dataCurrent;
+
+		WAV(const WAV&); //!< don't call
+		WAV& operator=(const WAV&); //!< don't call
+};
+
+#endif // WAV_h_DEFINED
diff -urdN ../Tekkotsu_2.3/SoundPlay/SoundManager.cc ./SoundPlay/SoundManager.cc
--- ../Tekkotsu_2.3/SoundPlay/SoundManager.cc	Wed Dec 22 18:13:04 2004
+++ ./SoundPlay/SoundManager.cc	Wed Dec 31 19:00:00 1969
@@ -1,766 +0,0 @@
-#include "Shared/Config.h"
-#include "SoundManager.h"
-#include "Shared/LockScope.h"
-#include "WAV.h"
-#include "Events/EventRouter.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <fstream>
-#include <OPENR/OSubject.h>
-#include <OPENR/ObjcommEvent.h>
-
-
-SoundManager * sndman=NULL;
-
-//!for convenience when locking each of the functions
-typedef LockScope<ProcessID::NumProcesses> AutoLock;
-
-SoundManager::SoundManager()
-	: mixerBuffer(0), mixerBufferSize(0),
-		sndlist(),playlist(),chanlist(),mix_mode(Fast),queue_mode(Override),max_chan(4),lock()
-{
-}
-
-SoundManager::~SoundManager() {
-	delete[] mixerBuffer;
-}
-
-void
-SoundManager::InitAccess(OSubject* subj) {
-	subjs[ProcessID::getID()]=subj;
-}
-
-//!@todo this does one more copy than it really needs to
-SoundManager::Snd_ID
-SoundManager::LoadFile(std::string const &name) {
-	AutoLock autolock(lock,ProcessID::getID());
-	if (name.size() == 0) {
-	  cout << "SoundManager::LoadFile() null filename" << endl;
-	  return invalid_Snd_ID;
-	};
-	std::string path(config->sound.makePath(name));
-	Snd_ID id=lookupPath(path);
-	if(id!=invalid_Snd_ID) {
-		//		cout << "add reference to pre-existing" << endl;
-		sndlist[id].ref++;
-	} else {
-		//		cout << "load new file" << endl;
-		struct stat buf;
-		if(stat(path.c_str(),&buf)==-1) {
-			cout << "SoundManager::LoadFile(): Sound file not found: " << path << endl;
-			return invalid_Snd_ID;
-		}
-		byte * sndbuf=new byte[buf.st_size];
-		std::ifstream file(path.c_str());
-		file.read(reinterpret_cast<char*>(sndbuf),buf.st_size);
-		WAV wav;
-		WAVError error = wav.Set(sndbuf);
-		if (error != WAV_SUCCESS) {
-			OSYSLOG1((osyslogERROR, "%s : %s %d: '%s'","SoundManager::LoadFile()","wav.Set() FAILED",
-				  error, path.c_str()));
-			return invalid_Snd_ID;
-		}
-		if(wav.GetSamplingRate()!=config->sound.sample_rate || wav.GetBitsPerSample()!=config->sound.sample_bits) {
-			OSYSLOG1((osyslogERROR, "%s : %s %s","SoundManager::LoadFile()","bad sample rate/bits", error));
-			return invalid_Snd_ID;
-		}
-		id=LoadBuffer(reinterpret_cast<char*>(wav.GetDataStart()),wav.GetDataEnd()-wav.GetDataStart());
-		delete [] sndbuf;
-		strncpy(sndlist[id].name,path.c_str(),MAX_NAME_LEN);
-	}
-	return id;
-}
-
-SoundManager::Snd_ID
-SoundManager::LoadBuffer(const char buf[], unsigned int len) {
-	cout << "SoundManager::LoadBuffer() of " << len << " bytes" << endl;
-	if(buf==NULL || len==0)
-		return invalid_Snd_ID;
-	AutoLock autolock(lock,ProcessID::getID());
-	//setup region
-	RCRegion * region=initRegion(len+SoundManagerMsg::MSG_SIZE);
-	//setup message
-	SoundManagerMsg * msg=new (reinterpret_cast<SoundManagerMsg*>(region->Base())) SoundManagerMsg;
-	msg->setAdd(sndlist.new_front());
-	//init sound structure
-	sndlist[msg->getID()].rcr=NULL;  // set by SoundPlay upon reception
-	sndlist[msg->getID()].data=NULL; // set by SoundPlay upon reception
-	sndlist[msg->getID()].ref=1;
-	sndlist[msg->getID()].len=len;
-	//copy buffer, do any filtering needed here
-	const byte* src=reinterpret_cast<const byte*>(buf);
-	byte* dest=reinterpret_cast<byte*>(region->Base())+SoundManagerMsg::MSG_SIZE;
-	byte* end=dest+len;
-	if (config->sound.sample_bits==8)
-		while (dest < end)
-			*dest++ = *src++ ^ 0x80; // offset binary -> signed char 
-	else
-		while (dest < end)
-			*dest++ = *src++;
-	//send message
-	if(ProcessID::getID()==ProcessID::SoundProcess) {
-		//if SoundPlay is preloading files, don't need to do inter-object comm
-		sndlist[msg->getID()].rcr=region;
-		sndlist[msg->getID()].data=reinterpret_cast<byte*>(region->Base()+SoundManagerMsg::MSG_SIZE);		
-	} else {
-		subjs[ProcessID::getID()]->SetData(region);
-		subjs[ProcessID::getID()]->NotifyObservers();
-	}
-	return msg->getID();
-}
-	
-void
-SoundManager::ReleaseFile(std::string const &name) {
-	AutoLock autolock(lock,ProcessID::getID());
-	Release(lookupPath(name));
-}
-
-void
-SoundManager::Release(Snd_ID id) {
-	if(id==invalid_Snd_ID)
-		return;
-	if(sndlist[id].ref==0) {
-		cout << "SoundManager::Release() " << id << " extra release" << endl;
-		return;
-	}
-	AutoLock autolock(lock,ProcessID::getID());
-	sndlist[id].ref--;
-	if(sndlist[id].ref==0) {
-		//cout << "releasing snd_id " << id << endl;
-		//setup region
-		RCRegion * region=initRegion(SoundManagerMsg::MSG_SIZE);
-		//setup message
-		SoundManagerMsg * msg=new (reinterpret_cast<SoundManagerMsg*>(region->Base())) SoundManagerMsg;
-		msg->setDelete(sndlist[id].rcr);
-		//clean up sound data structure
-		sndlist.erase(id);
-		//send message
-		if(ProcessID::getID()==ProcessID::SoundProcess) {
-			msg->region->RemoveReference();
-		} else {
-			subjs[ProcessID::getID()]->SetData(region);
-			subjs[ProcessID::getID()]->NotifyObservers();
-		}
-	}
-}
-
-SoundManager::Play_ID
-SoundManager::PlayFile(std::string const &name) {
-  if(playlist.size()>=playlist_t::MAX_ENTRIES)
-		return invalid_Play_ID;	
-	AutoLock autolock(lock,ProcessID::getID());
-	Snd_ID sndid=LoadFile(name);
-	if(sndid==invalid_Snd_ID)
-		return invalid_Play_ID;
-	sndlist[sndid].ref--;
-	return Play(sndid);
-}
-
-SoundManager::Play_ID
-SoundManager::PlayBuffer(const char buf[], unsigned int len) {
-	if(playlist.size()>=playlist_t::MAX_ENTRIES || buf==NULL || len==0)
-		return invalid_Play_ID;	
-	AutoLock autolock(lock,ProcessID::getID());
-	Snd_ID sndid=LoadBuffer(buf,len);
-	if(sndid==invalid_Snd_ID)
-		return invalid_Play_ID;
-	sndlist[sndid].ref--;
-	return Play(sndid);
-}
-	
-SoundManager::Play_ID
-SoundManager::Play(Snd_ID id) {
-	//	cout << "Play " << id << endl;
-	if(id==invalid_Snd_ID)
-		return invalid_Play_ID;
-	AutoLock autolock(lock,ProcessID::getID());
-	Play_ID playid=playlist.new_front();
-	if(playid!=invalid_Play_ID) {
-		sndlist[id].ref++;
-		playlist[playid].snd_id=id;
-		playlist[playid].offset=0;
-		//playlist.size() should be greater than or equal to chanlist.size
-		//so if we got a playid, we can get a channel slot.
-		chanlist.push_front(playid);
-
-		//setup message to "wake-up" 
-		//(only really need if chanlist was empty)
-		//		if(chanlist.size()==1) { //commented out because sometimes doesn't wake up, thinks it's playing but isn't
-		if(ProcessID::getID()!=ProcessID::SoundProcess) {
-			RCRegion * region=initRegion(SoundManagerMsg::MSG_SIZE);
-			ASSERT(region!=NULL,"initRegion returned NULL");
-			SoundManagerMsg * msg=new (reinterpret_cast<SoundManagerMsg*>(region->Base())) SoundManagerMsg;
-			msg->setWakeup();
-			subjs[ProcessID::getID()]->SetData(region);
-			subjs[ProcessID::getID()]->NotifyObservers();
-		}
-		//		}
-		
-		if(sndlist[id].rcr!=NULL) {
-			const char * name=sndlist[playlist[playid].snd_id].name;
-			if(name[0]!='\0')
-				erouter->postEvent(EventBase::audioEGID,playid,EventBase::activateETID,0,name,1);
-			else
-				erouter->postEvent(EventBase::audioEGID,playid,EventBase::activateETID,0);
-		}
-	}
-	return playid;
-}
-	
-SoundManager::Play_ID
-SoundManager::ChainFile(Play_ID base, std::string const &next) {
-       if(base==invalid_Play_ID)
-		return base;
-	Play_ID orig=base;
-	while(playlist[base].next_id!=invalid_Play_ID)
-		base=playlist[base].next_id;
-	Play_ID nplay=playlist.new_front();
-	if(nplay==invalid_Play_ID)
-		return nplay;
-	Snd_ID nsnd=LoadFile(next);
-	if(nsnd==invalid_Snd_ID) {
-		playlist.pop_front();
-		return invalid_Play_ID;
-	}
-	playlist[nplay].snd_id=nsnd;
-	playlist[base].next_id=nplay;
-	return orig;
-}
-
-SoundManager::Play_ID
-SoundManager::ChainBuffer(Play_ID base, const char buf[], unsigned int len) {
-	if(base==invalid_Play_ID || buf==NULL || len==0)
-		return base;
-	Play_ID orig=base;
-	while(playlist[base].next_id!=invalid_Play_ID)
-		base=playlist[base].next_id;
-	Play_ID nplay=playlist.new_front();
-	if(nplay==invalid_Play_ID)
-		return nplay;
-	Snd_ID nsnd=LoadBuffer(buf,len);
-	if(nsnd==invalid_Snd_ID) {
-		playlist.pop_front();
-		return invalid_Play_ID;
-	}
-	playlist[nplay].snd_id=nsnd;
-	playlist[base].next_id=nplay;
-	return orig;
-}
-
-SoundManager::Play_ID
-SoundManager::Chain(Play_ID base, Snd_ID next) {
-	if(base==invalid_Play_ID || next==invalid_Snd_ID)
-		return base;
-	Play_ID orig=base;
-	while(playlist[base].next_id!=invalid_Play_ID)
-		base=playlist[base].next_id;
-	Play_ID nplay=playlist.new_front();
-	if(nplay==invalid_Play_ID)
-		return nplay;
-	playlist[nplay].snd_id=next;
-	playlist[base].next_id=nplay;
-	return orig;
-}
-
-void
-SoundManager::StopPlay() {
-	while(!playlist.empty())
-		StopPlay(playlist.begin());
-}
-
-void
-SoundManager::StopPlay(Play_ID id) {
-	//	cout << "Stopping sound " << id << endl;
-	if(id==invalid_Play_ID)
-		return;
-	AutoLock autolock(lock,ProcessID::getID());
-	//we start at the back (oldest) since these are the most likely to be removed...
-	for(chanlist_t::index_t it=chanlist.prev(chanlist.end()); it!=chanlist.end(); it=chanlist.prev(it))
-		if(chanlist[it]==id) {
-			std::string name=sndlist[playlist[id].snd_id].name;
-			Release(playlist[id].snd_id);
-			playlist.erase(id);
-			chanlist.erase(it);
-			playlist[id].cumulative+=playlist[id].offset;
-			unsigned int ms=playlist[id].cumulative/(config->sound.sample_bits/8)/(config->sound.sample_rate/1000);
-			if(name.size()>0)
-				erouter->postEvent(EventBase::audioEGID,id,EventBase::deactivateETID,ms,name,0);
-			else
-				erouter->postEvent(EventBase::audioEGID,id,EventBase::deactivateETID,ms);
-			return;
-		}
-	cout << "SoundManager::StopPlay(): " << id << " does not seem to be playing" << endl;
-}
-
-void
-SoundManager::PausePlay(Play_ID id) {
-	if(id==invalid_Play_ID)
-		return;
-	AutoLock autolock(lock,ProcessID::getID());
-	for(chanlist_t::index_t it=chanlist.begin(); it!=chanlist.end(); it=chanlist.next(it))
-		if(chanlist[it]==id) {
-			chanlist.erase(it);
-			return;
-		}
-}
-	
-void
-SoundManager::ResumePlay(Play_ID id) {
-	if(id==invalid_Play_ID)
-		return;
-	AutoLock autolock(lock,ProcessID::getID());
-	for(chanlist_t::index_t it=chanlist.begin(); it!=chanlist.end(); it=chanlist.next(it))
-		if(chanlist[it]==id)
-			return;
-	chanlist.push_front(id);
-}
-	
-void
-SoundManager::SetMode(unsigned int max_channels, MixMode_t mixer_mode, QueueMode_t queuing_mode) {
-	AutoLock autolock(lock,ProcessID::getID());
-	max_chan=max_channels;
-	mix_mode=mixer_mode;
-	queue_mode=queuing_mode;
-}
-
-unsigned int
-SoundManager::GetRemainTime(Play_ID id) const {
-	AutoLock autolock(lock,ProcessID::getID());
-	unsigned int t=0;
-	while(id!=invalid_Play_ID) {
-		t+=sndlist[playlist[id].snd_id].len-playlist[id].offset;
-		id=playlist[id].next_id;
-	}
-	const unsigned int bytesPerMS=config->sound.sample_bits/8*config->sound.sample_rate/1000;
-	return t/bytesPerMS;
-}
-
-void
-SoundManager::MixChannel(Play_ID channelId, void* buf, size_t destSize) {
-	char *dest = (char*) buf;
-	
-	PlayState& channel = playlist[channelId];
-	while (destSize > 0) {
-		const SoundData& buffer = sndlist[channel.snd_id];
-		const char* samples = ((char*) (buffer.data)) + channel.offset;
-		const unsigned int samplesSize = buffer.len - channel.offset;
-		if (samplesSize > destSize) {
-			memcpy(dest, samples, destSize);
-			channel.offset += destSize;
-			dest += destSize;
-			destSize = 0;
-			return;
-		} else {
-			memcpy(dest, samples, samplesSize);
-			channel.offset += samplesSize;
-			dest += samplesSize;
-			destSize -= samplesSize;
-			if (endPlay(channelId)) {
-				break;
-			}
-		}
-	}
-	if (destSize > 0) {
-		memset(dest, 0, destSize);
-	}
-}
-
-void
-SoundManager::MixChannelAdditively(Play_ID channelId, int bitsPerSample, MixMode_t mode,
-                                   short scalingFactor, void* buf, size_t destSize)
-{
-	PlayState& channel = playlist[channelId];
-	while (destSize > 0) {
-		const SoundData& buffer = sndlist[channel.snd_id];
-		const unsigned int samplesSize = buffer.len - channel.offset;
-		const unsigned int mixedSamplesSize =
-			((mode == Fast)
-				? ((samplesSize > destSize) ? destSize : samplesSize)
-				: ((samplesSize > destSize / 2) ? destSize / 2 : samplesSize)); 
-		
-		if (bitsPerSample == 8) {
-			//  8-bit mode
-			const char* samples = (char*) (buffer.data + channel.offset);
-			if (mode == Fast) {
-				// 8-bit mixing
-				char *dest = (char*) buf;
-				for (size_t i = 0; i < mixedSamplesSize; i++) {
-					*dest += samples[i] / scalingFactor;
-					dest++;
-				}
-				destSize -= (char*) dest - (char*) buf;
-				buf = dest;
-			} else {
-				// 16-bit mixing
-				short* dest = (short*) buf;
-				for (size_t i = 0; i < mixedSamplesSize; i++) {
-					*dest += samples[i];
-					*dest++;
-				}
-				destSize -= (char*) dest - (char*) buf;
-				buf = dest;
-			}
-		} else {
-			// 16-bit mode
-			const short* samples = (short*) (buffer.data + channel.offset);
-			if (mode == Fast) {
-				// 16-bit mixing
-				short* dest = (short*) buf;
-				for (size_t i = 0; i < mixedSamplesSize / 2; i++) {
-					*dest += samples[i] / scalingFactor;
-					*dest++;
-				}
-				destSize -= (char*) dest - (char*) buf;
-				buf = dest;
-			} else {
-				// 32-bit mixing
-				int* dest = (int*) buf;
-				for (size_t i = 0; i < mixedSamplesSize / 2; i++) {
-					*dest += samples[i];
-					*dest++;
-				}
-				destSize -= (char*) dest - (char*) buf;
-				buf = dest;
-			}
-		}
-		channel.offset += mixedSamplesSize;
-		if (destSize == 0) {
-			return;
-		} else {
-			if (endPlay(channelId)) {
-				return;
-			}
-		}
-	}
-}
-
-unsigned int
-SoundManager::CopyTo(OSoundVectorData* data) {
-	AutoLock autolock(lock,ProcessID::getID());
-
-	size_t destSize = data->GetInfo(0)->dataSize;	
-	void* dest = data->GetData(0);
-	
-	if(chanlist.size() == 0) {
-		memset(dest, 0, destSize);
-		return 0;
-	}
-
-	std::vector<Play_ID> channels;
-	selectChannels(channels);
-
-	if (channels.size() == 0) {
-		// No channels to mix
-		memset(dest, 0, destSize); 
-	} else if (channels.size() == 1) {
-		// One channel to mix
-		MixChannel(channels.front(), dest, destSize);
-	} else {
-		// Several channels to mix	
-		const MixMode_t mode = mix_mode;
-		const int bitsPerSample = config->sound.sample_bits;
-		if (mode == Quality) {
-			// Quality mixing uses an intermediate buffer
-			if ((mixerBuffer == 0) || (mixerBufferSize < destSize * 2)) {
-				delete[] mixerBuffer;
-				mixerBuffer = 0;
-				mixerBufferSize = destSize * 2;
-				mixerBuffer = new int[(mixerBufferSize / 4) + 1]; // makes sure it's int-aligned
-			}
-			memset(mixerBuffer, 0,  mixerBufferSize);
-			dest = mixerBuffer;
-			destSize *= 2;
-		} else {
-			// Fast mixing does not use the intermeridate buffer
-			memset(dest, 0, destSize);
-		}
-		
-		const int channelCount = channels.size();
-		const short scalingFactor = (short) ((mode == Fast) ? channelCount : 1);  
-		for(std::vector<Play_ID>::iterator i = channels.begin(); i != channels.end(); i++)
-			MixChannelAdditively(*i, bitsPerSample, mode, scalingFactor, dest, destSize);
-		
-		if (mode == Quality) {
-			// Quality mixing uses an intermediate buffer
-			// Scale the buffer
-			destSize /= 2;
-			if (bitsPerSample == 8) {
-				//  8-bit mode
-				char* destChar = (char*) data->GetData(0);
-				short* mixerBufferShort = (short*) mixerBuffer;
-				for (size_t i = 0; i < destSize; i++) {
-					destChar[i] = (char) (mixerBufferShort[i] / channelCount);
-				} 
-			} else {
-				// 16-bit mode
-				short* destShort = (short*) data->GetData(0);
-				const size_t destSampleCount = destSize / 2; 
-				for (size_t i = 0; i < destSampleCount; i++) {
-					destShort[i] = (short) (mixerBuffer[i] / channelCount);
-				}
-			}
-		}
-	}
-	
-	updateChannels(channels, data->GetInfo(0)->dataSize);
-	return channels.size(); 
-}
-
-void
-SoundManager::ReceivedMsg(const ONotifyEvent& event) {
-	for(int x=0; x<event.NumOfData(); x++) {
-		RCRegion * rcr = event.RCData(x);
-		SoundManagerMsg * msg = reinterpret_cast<SoundManagerMsg*>(rcr->Base());
-		switch(msg->type) {
-		case SoundManagerMsg::add: {
-			rcr->AddReference();
-			sndlist[msg->id].rcr=rcr;
-			sndlist[msg->id].data=reinterpret_cast<byte*>(rcr->Base()+SoundManagerMsg::MSG_SIZE);
-			//look to see if there's any play's for the sound we just finished loading
-			for(playlist_t::index_t it=playlist.begin();it!=playlist.end();it=playlist.next(it))
-				if(playlist[it].snd_id==msg->id) {
-					//send an event if there are
-					const char * name=sndlist[playlist[it].snd_id].name;
-					if(name[0]!='\0')
-						erouter->postEvent(EventBase::audioEGID,it,EventBase::activateETID,0,name,1);
-					else
-						erouter->postEvent(EventBase::audioEGID,it,EventBase::activateETID,0);
-				}
-		} break;
-		case SoundManagerMsg::del: {
-			msg->region->RemoveReference();
-		} break;
-		case SoundManagerMsg::wakeup: {
-			//doesn't need to do anything, just causes SoundPlay to check activity
-		} break;
-		default:
-			printf("*** WARNING *** unknown SoundManager msg type received\n");
-		}
-	}
-}
-
-//protected:
-
-RCRegion*
-SoundManager::initRegion(unsigned int size) {
-	unsigned int pagesize=4096;
-	sError err=GetPageSize(&pagesize);
-	ASSERT(err==sSUCCESS,"Error "<<err<<" getting page size");
-	unsigned int pages=(size+pagesize-1)/pagesize;
-	return new RCRegion(pages*pagesize);
-}
-
-SoundManager::Snd_ID 
-SoundManager::lookupPath(std::string const &name) const {
-        std::string const path(config->sound.makePath(name));
-	for(sndlist_t::index_t it=sndlist.begin(); it!=sndlist.end(); it=sndlist.next(it))
-		if(strncasecmp(path.c_str(),sndlist[it].name,MAX_NAME_LEN)==0)
-			return it;
-	return invalid_Snd_ID;
-}
-
-void
-SoundManager::selectChannels(std::vector<Play_ID>& mix) {
-	unsigned int selected=0;
-	switch(queue_mode) {
-	case Enqueue: { //select the oldest channels
-		for(chanlist_t::index_t it=chanlist.prev(chanlist.end());it!=chanlist.end();it=chanlist.prev(it)) {
-			if(sndlist[playlist[chanlist[it]].snd_id].data!=NULL) {
-				mix.push_back(chanlist[it]);
-				selected++;
-				if(selected==max_chan)
-					return;
-			}
-		}
-	} break;
-	case Override:
-	case Pause: { //select the youngest channels (difference between these two is in the final update)
-		for(chanlist_t::index_t it=chanlist.begin(); it!=chanlist.end(); it=chanlist.next(it)) {
-			if(sndlist[playlist[chanlist[it]].snd_id].data!=NULL) {
-				mix.push_back(chanlist[it]);
-				selected++;
-				if(selected==max_chan)
-					return;
-			}
-		}
-	} break;
-	case Stop: { //select the youngest, stop anything that remains
-		unsigned int numkeep=0;
-		chanlist_t::index_t it=chanlist.begin();
-		for(;it!=chanlist.end(); it=chanlist.next(it), numkeep++) {
-			if(sndlist[playlist[chanlist[it]].snd_id].data!=NULL) {
-				mix.push_back(chanlist[it]);
-				selected++;
-				if(selected==max_chan) {
-					for(unsigned int i=chanlist.size()-numkeep-1; i>0; i--)
-						endPlay(chanlist.back());
-					return;
-				}
-			}
-		}
-	} break;
-	default:
-		cout << "SoundManager::selectChannels(): Illegal queue mode" << endl;
-	}
-}
-
-void
-SoundManager::updateChannels(const std::vector<Play_ID>& mixs,size_t used) {
-	switch(queue_mode) {
-	case Enqueue:
-	case Pause:
-	case Stop: 
-		break;
-	case Override: { //increase offset of everything that wasn't selected
-		//assumes mode hasn't changed since the mix list was created... (so order is same as chanlist)
-		chanlist_t::index_t it=chanlist.begin(); 
-		std::vector<Play_ID>::const_iterator mixit=mixs.begin();
-		for(;it!=chanlist.end(); it=chanlist.next(it)) {
-			for(;mixit!=mixs.end(); mixit++) //some mixs may have been stopped during play
-				if(*mixit==chanlist[it])
-					break;
-			if(mixit==mixs.end())
-				break;
-		}
-		for(;it!=chanlist.end(); it=chanlist.next(it)) {
-			const Play_ID channelId = chanlist[it];
-			PlayState &channel = playlist[channelId];
-			size_t skip = used;
-			while (skip > 0) {
-				SoundData &buffer = sndlist[channel.snd_id];
-				// FIXME: Don't know why the buffer.data != 0 check is done 
-				if (buffer.data != 0) {
-					size_t remain = buffer.len - channel.offset;
-					if (remain < skip) {
-						channel.offset = buffer.len;
-						skip -= buffer.len;
-						if (endPlay(channelId)) {
-							break;
-						}
-					} else {
-						channel.offset += skip;
-						skip = 0;
-					}
-				} else {
-					break;
-				}
-			}
-		}
-	} break;
-	default:
-		cout << "SoundManager::updateChannels(): Illegal queue mode" << endl;
-	}
-}
-
-bool
-SoundManager::endPlay(Play_ID id) {
-	if(playlist[id].next_id==invalid_Play_ID) {
-		StopPlay(id);
-		return true;
-	} else {
-		//copies the next one into current so that the Play_ID consistently refers to the same "sound"
-		Play_ID next=playlist[id].next_id;
-		//		cout << "play " << id << " moving from " << playlist[id].snd_id << " to " << playlist[next].snd_id << endl;
-		Release(playlist[id].snd_id);
-		playlist[id].snd_id=playlist[next].snd_id;
-		playlist[id].cumulative+=playlist[id].offset;
-		playlist[id].offset=0;
-		playlist[id].next_id=playlist[next].next_id;
-		playlist.erase(next);
-		unsigned int ms=playlist[id].cumulative/(config->sound.sample_bits/8)/(config->sound.sample_rate/1000);
-		const char * name=sndlist[playlist[id].snd_id].name;
-		if(name[0]!='\0')
-			erouter->postEvent(EventBase::audioEGID,id,EventBase::statusETID,ms,name,1);
-		else
-			erouter->postEvent(EventBase::audioEGID,id,EventBase::statusETID,ms);
-		return false;
-	}
-}
-
-SoundManager::SoundData::SoundData()
-	: rcr(NULL), data(NULL), len(0), ref(0)
-{
-	name[0]='\0';
-}
-
-SoundManager::PlayState::PlayState()
-	: snd_id(invalid_Snd_ID), offset(0), cumulative(0), next_id(invalid_Play_ID)
-{}
-
-
-/*! @file
- * @brief Implements SoundManager, which provides sound effects and caching services, as well as mixing buffers for the SoundPlay process
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.19 $
- * $State: Exp $
- * $Date: 2004/12/22 23:13:04 $
- */
-
-
-
-
-//This is a faster mix algo using bit shifting, but it doesn't work with
-// non power of two number of channels, despite my efforts... eh, maybe
-// i'll fix it later...
-		// NOT WORKING
-		/*
-		if(mixs.size()==2 || mix_mode==Fast) {
-			unsigned int shift=0;
-			unsigned int offset=0;
-			unsigned int tmp=mixs.size();
-			while(tmp>1) {
-				tmp>>=1;
-				shift++;
-			}
-			unsigned int mask;
-			if(config->sound.sample_bits==8) {
-				unsigned int c=(unsigned char)~0;
-				c>>=shift;
-				mask=(c<<24)|(c<<16)|(c<<8)|c;
-				offset=(1<<7)|(1<<15)|(1<<23)|(1<<31);
-			} else {
-				unsigned int c=(unsigned short)~0;
-				c>>=shift;
-				mask=(c<<16)|c;
-				offset=(1<<31)|(1<<15);
-			}
-			memset(dest,0,avail);
-			for(unsigned int c=0; c<mixs.size(); c++) {
-				if(ends[c]-srcs[c]>avail) {
-					for(unsigned int * beg=(unsigned int*)dest;beg<(unsigned int*)end;beg++) {
-						const unsigned int src=*(unsigned int*)srcs[c];
-						if(beg==(unsigned int*)dest) {
-							cout << src <<' '<< (void*)src << endl;
-							unsigned int x=((src^offset)>>shift)&mask;
-							cout << x <<' '<< (void*)x << endl;
-							cout << "****" << endl;
-						}
-						*beg+=((src^offset)>>shift)&mask;
-						if(beg==(unsigned int*)dest)
-							cout << *beg <<' '<< (void*)*beg << endl << "########" << endl;
-						srcs[c]+=sizeof(int);
-					}
-					playlist[mixs[c]].offset+=avail;
-				} else {
-					unsigned int * beg=(unsigned int*)dest;
-					for(;srcs[c]<ends[c];srcs[c]+=sizeof(int)) {
-						const unsigned int src=*(unsigned int*)srcs[c];
-						*beg+=((src^offset)>>shift)&mask;
-						beg++;
-					}
-					for(;beg<(unsigned int*)end; beg++)
-						*beg+=offset>>shift;
-					playlist[mixs[c]].offset=sndlist[playlist[mixs[c]].snd_id].len;
-					StopPlay(mixs[c]);
-				}
-			}
-			unsigned int leftover=(offset>>shift)*((1<<shift)-mixs.size());
-			for(unsigned int * beg=(unsigned int*)dest;beg<(unsigned int*)end;beg++)
-				*beg=*(beg+leftover)^offset;
-			updateChannels(avail);
-			return mixs.size();
-			} else*/
diff -urdN ../Tekkotsu_2.3/SoundPlay/SoundManager.h ./SoundPlay/SoundManager.h
--- ../Tekkotsu_2.3/SoundPlay/SoundManager.h	Thu Nov  4 00:24:03 2004
+++ ./SoundPlay/SoundManager.h	Wed Dec 31 19:00:00 1969
@@ -1,271 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_SoundManager_h_
-#define INCLUDED_SoundManager_h_
-
-#include <OPENR/RCRegion.h>
-#include <OPENR/ODataFormats.h>
-
-#include <string>
-#include <vector>
-#include "Shared/ListMemBuf.h"
-#include "Shared/MutexLock.h"
-#include "SoundManagerMsg.h"
-#include "Shared/ProcessID.h"
-
-class OSubject;
-class ONotifyEvent;
-
-//! Provides sound effects and caching services, as well as mixing buffers for the SoundPlay process
-/*! Provides easy methods for playing back sounds, either from files
- *  on the memory stick, or from dynamically generated buffers.  You
- *  can chain playback commands so that when one sound finishes,
- *  another picks up automatically.  This might be handy if, say,
- *  someone wants to write an MP3 player ;) The sounds would be too
- *  large to load into memory all at once, but you could load a block
- *  at a time and chain them so it seamlessly moves from one to the
- *  other.
- *  
- *  You can also preload sounds (LoadFile()) before playing them so
- *  there's no delay while loading after you request a sound to be
- *  played.  Just be sure to release the file (ReleaseFile()) again
- *  when you're done with it ;)
- *
- *  All functions will attempt to lock the SoundManager.  Remember,
- *  this is running in a shared memory region, accessible by the
- *  SoundPlay process and both the Main and Motion processes (so
- *  MotionCommands can play sounds!)
- *
- *  One could be tempted to draw parallels to the MotionManager, and
- *  envision a system with SoundCommands that are handed over and can
- *  dynamically compute sound buffers as needed.  If you have the time
- *  and inclination, the job's all yours... (Midi players, speech
- *  synthesizer, ...?)
- *
- *  @todo Volume control, variable playback speed, support more wav
- *  file formats (latter two are the same thing if you think about it
- *  - need to be able to resample on the fly)
- *  
- *  @todo Add functions to hand out regions to be filled out to avoid
- *  copying into the buffer.
- */
-class SoundManager {
-public:
-	//!constructor
-	SoundManager();
-	virtual ~SoundManager();
-
-	//!This is used for referring to sound data so you can start playing it or release it
-	typedef SoundManagerMsg::Snd_ID Snd_ID;
-	static const Snd_ID invalid_Snd_ID=(Snd_ID)-1; //!< for reporting errors
-	static const Snd_ID MAX_SND=50; //!< the number of sounds that can be loaded at any given time
-	
-	//!This is for referring to instances of the play command so you can stop, pause, or monitor progress (later versions will send events upon completion)
-	typedef unsigned short Play_ID;
-	static const Play_ID invalid_Play_ID=(Play_ID)-1; //!< for reporting errors
-	static const Play_ID MAX_PLAY=256; //!< the number of sounds that can be enqueued at the same time (see MixMode_t)
-
-	static const unsigned int MAX_NAME_LEN=64;   //!<maximum length of a path
-
-	//!Used to set the mode for mixing multiple sound channels
-	/*!Feel free to add a higher quality mixer if you're an audiophile - I'm pretty new to sound processing*/
-	enum MixMode_t {
-		// there's some prototype code for a bit-shifting 'Faster' quality level, but it hasn't been finished... 'Fast' is the default for now.
-		Fast,    //!< uses real division to maintain volume level, without increasing intermediary precision, which causes low-order bit error in exchange for less CPU usage
-		Quality  //!< uses real division to maintain volume level, using an intermediary higher precision buffer for mixing
-	};
-
-	enum QueueMode_t {
-		Enqueue,        //!< newer sounds are played when a channel opens up (when old sound finishes)
-		Pause,          //!< newer sounds pause oldest sound, which continues when a channel opens
-		Stop,           //!< newer sounds stop oldest sound
-		Override,       //!< older sounds have play heads advanced, but don't get mixed until a channel opens
-	};
-
-	//!Needed to send sounds to the SoundPlay process
-	void InitAccess(OSubject* subj);
-
-	//!loads a wav file (if it matches Config::sound_config settings - can't do resampling yet)
-	/*!Since the SoundManager does the loading, if the same file is being played more than once, only once copy is stored in memory 
-	 * @param name can be either a full path, or a partial path relative to Config::sound_config::root
-	 * @return ID number for future references (can also use name)
-	 * The sound data will be cached until ReleaseFile() or Release() is called a matching number of times*/
-	Snd_ID LoadFile(std::string const &name);
-
-	//!loads raw samples from a buffer (assumes matches Config::sound_config settings)
-	/*!The sound data will be cached until Release() is called a matching number of times.\n
-	 * This function is useful for dynamic sound sources.  A copy will be made. */
-	Snd_ID LoadBuffer(const char buf[], unsigned int len);
-	
-	//!Marks the sound buffer to be released after the last play command completes (or right now if not being played)
-	void ReleaseFile(std::string const &name);
-
-	//!Marks the sound buffer to be released after the last play command completes (or right now if not being played)
-	void Release(Snd_ID id);
-	
-	//!play a wav file (if it matches Config::sound_config settings - can't do resampling yet)
-	/*!Will do a call to LoadFile() first, and then automatically release the sound again when complete.
-	 * @param name can be either a full path, or a partial path relative to Config::sound_config::root
-	 * @return ID number for future references
-	 * The sound data will not be cached after done playing unless a call to LoadFile is made*/
-	Play_ID PlayFile(std::string const &name);
-
-	//!loads raw samples from a buffer (assumes buffer matches Config::sound_config settings)
-	/*!The sound data will be released after done playing*/
-	Play_ID PlayBuffer(const char buf[], unsigned int len);
-	
-	//!plays a previously loaded buffer or file
-	Play_ID Play(Snd_ID id);
-	
-	//!allows automatic queuing of sounds - good for dynamic sound sources!
-	/*!if you chain more than once to the same base, the new buffers are appended
-	 * to the end of the chain - the new buffer doesn't replace the current chain
-	 * @return @a base - just for convenience of multiple calls*/
-	Play_ID ChainFile(Play_ID base, std::string const &next);
-
-	//!allows automatic queuing of sounds - good for dynamic sound sources!
-	/*!if you chain more than once to the same base, the new buffers are appended
-	 * to the end of the chain - the new buffer doesn't replace the current chain
-	 * @return @a base - just for convenience of multiple calls*/
-	Play_ID ChainBuffer(Play_ID base, const char buf[], unsigned int len);
-
-	//!allows automatic queuing of sounds - good for dynamic sound sources!
-	/*!if you chain more than once to the same base, the new buffers are appended
-	 * to the end of the chain - the new buffer doesn't replace the current chain
-	 * @return @a base - just for convenience of multiple calls*/
-	Play_ID Chain(Play_ID base, Snd_ID next);
-	
-	//!Lets you stop playback of all sounds
-	void StopPlay();
-
-	//!Lets you stop playback of a sound
-	void StopPlay(Play_ID id);
-	
-	//!Lets you pause playback
-	void PausePlay(Play_ID id);
-	
-	//!Lets you resume playback
-	void ResumePlay(Play_ID id);
-	
-	//!Lets you control the maximum number of channels (currently playing sounds), method for mixing (applies when max_chan>1), and queuing method (for when overflow channels)
-	void SetMode(unsigned int max_channels, MixMode_t mixer_mode, QueueMode_t queuing_mode);
-
-	//!Gives the time until the sound finishes, in milliseconds.  Subtract 32 to get guarranteed valid time for this ID.
-	/*!You should be passing the beginning of a chain to get proper results...\n
-	 * May be slightly conservative (will report too small a time) because this
-	 * does not account for delay until SoundPlay picks up the message that a
-	 * sound has been added.\n
-	 * However, it is slighly optimistic (will report too large a time) because
-	 * it processes a buffer all at one go, so it could mark the sound as finished
-	 * (and cause the ID to go invalid) up to RobotInfo::SoundBufferTime (32 ms)
-	 * before the sound finishes.  So subtract SoundBufferTime if you want to be
-	 * absolutely sure the ID will still valid. */
-	unsigned int GetRemainTime(Play_ID id) const;
-	
-	//!Copies the sound data to the OPENR buffer, ready to be passed to the system, only called by SoundPlay
-	/*!@return the number of active sounds */
-	unsigned int CopyTo(OSoundVectorData* data);
-
-	//!updates internal data structures on the SoundPlay side - you shouldn't be calling this
-	void ReceivedMsg(const ONotifyEvent& event);
-	
-	//! returns number of sounds currently playing
-	unsigned int GetNumPlaying() { return chanlist.size(); }
-	
-protected:
-	//!Mixes the channel into the buffer
-	void MixChannel(Play_ID channelId, void* buf, size_t size);
-	
-	//!Mixes the channel into the buffer additively
-	/*!If mode is Quality, then the size of the buffer should be double the normal
-	* size. */
-	void MixChannelAdditively(Play_ID channelId, int bitsPerSample, MixMode_t mode, short scalingFactor, void* buf, size_t size);
-	
-	//!The intermediate mixer buffer used for Quality mode mixing
-	int* mixerBuffer;
-	
-	//!Size (in bytes) of the intermediate mixer buffer
-	size_t mixerBufferSize;
-
-	//!Sets up a shared region to hold a sound - rounds to nearest page size
-	static RCRegion* initRegion(unsigned int size);
-
-	//!Looks to see if @a name matches any of the sounds in sndlist (converts to absolute path if not already)
-	Snd_ID lookupPath(std::string const &name) const;
-
-	//!selects which of the channels are actually to be mixed together, depending on queue_mode
-	void selectChannels(std::vector<Play_ID>& mix);
-
-	//!update the offsets of sounds which weren't mixed (when needed depending on queue_mode)
-	void updateChannels(const std::vector<Play_ID>& mixs,size_t used);
-
-	//!called when a buffer end is reached, may reset buffer to next in chain, or just StopPlay()
-	bool endPlay(Play_ID id);
-
-	//!Holds data about the loaded sounds
-	struct SoundData {
-		SoundData();                             //!<constructor
-		RCRegion * rcr;                          //!<shared region - don't need to share among processes, just collect in SoundPlay
-		byte* data;                              //!<point to data in region (for convenience, only valid in SoundPlay)
-		unsigned int len;                        //!<size of the sound
-		unsigned int ref;                        //!<reference counter
-		char name[SoundManager::MAX_NAME_LEN];   //!<stores the path to the file, empty if from a buffer
-	private:
-		SoundData(const SoundData&);             //!< don't call
-		SoundData operator=(const SoundData&);   //!< don't call
-	};
-	//!For convenience
-	typedef ListMemBuf<SoundData,MAX_SND,Snd_ID> sndlist_t;
-	//!Holds a list of all currently loaded sounds
-	sndlist_t sndlist;
-	
-	//!Holds data about sounds currently being played
-	struct PlayState {
-		PlayState();            //!<constructor
-		Snd_ID snd_id;          //!<index of sound
-		unsigned int offset;    //!<position in the sound
-		unsigned int cumulative;//!<total time of playing (over queued sounds)
-		Play_ID next_id;        //!<lets you queue for continuous sound, or loop
-	};
-	//!For convenience
-	typedef ListMemBuf<PlayState,MAX_PLAY,Play_ID> playlist_t;
-	//!Holds a list of all sounds currently enqueued
-	playlist_t playlist;
-	//!For convenience
-	typedef ListMemBuf<Play_ID,MAX_PLAY,Play_ID> chanlist_t;
-	//!Holds a list of all currently playing sounds, ordered newest (front) to oldest(back)
-	chanlist_t chanlist;
-	
-	//!Current mixing mode, set by SetMode();
-	MixMode_t mix_mode;
-
-	//!Current queuing mode, set by SetMode();
-	QueueMode_t queue_mode;
-
-	//!Current maximum number of sounds to mix together
-	unsigned int max_chan;
-
-	//!Prevents multiple processes from accessing at the same time
-	mutable MutexLock<ProcessID::NumProcesses> lock;
-	
-	//!For automatic transmission of shared regions to SoundPlay
-	OSubject * subjs[ProcessID::NumProcesses];
-
-	SoundManager(const SoundManager&);           //!< don't call
-	SoundManager operator=(const SoundManager&); //!< don't call
-};
-
-//! lets you play a sound from anywhere in your code - just a one liner!
-extern SoundManager * sndman;
-
-/*! @file
- * @brief Describes SoundManager, which provides sound effects and caching services, as well as mixing buffers for the SoundPlay process
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
- * $State: Exp $
- * $Date: 2004/11/04 05:24:03 $
- */
-
-#endif
diff -urdN ../Tekkotsu_2.3/SoundPlay/SoundManagerMsg.h ./SoundPlay/SoundManagerMsg.h
--- ../Tekkotsu_2.3/SoundPlay/SoundManagerMsg.h	Thu Sep 25 11:32:08 2003
+++ ./SoundPlay/SoundManagerMsg.h	Wed Dec 31 19:00:00 1969
@@ -1,68 +0,0 @@
-//-*-c++-*-
-#ifndef INCLUDED_SoundManagerMsg_h
-#define INCLUDED_SoundManagerMsg_h
-
-class RCRegion;
-
-//! A small header that preceeds data sent by SoundManager between processes
-struct SoundManagerMsg {
-	//! the type to use when referring to Sounds
-	typedef unsigned short Snd_ID;
-	//! maintains even word alignment
-	static const unsigned int MSG_SIZE=16;
-
-	//! constructor
-	SoundManagerMsg() : type(unknown), id(static_cast<Snd_ID>(-1)), region(NULL) {}
-
-	//! virtual destructor
-	/*! doesn't do anything, but don't remove it, otherwise this would no longer be a virtual base class */
-	virtual ~SoundManagerMsg() {}
-
-	//! Accessor for the id number, set by SoundManager
-	Snd_ID getID() const { return id; }
-
-private:
-	friend class SoundManager;
-
-	//! Denotes what type of message this is
-	enum MsgType { add, del, wakeup, unknown } type;
-	
-	//! The id of the sound this is in reference to
-	Snd_ID id;
-
-	//! The RCRegion to free, if it's a deletion
-	RCRegion * region;
-
-	//! Sets up the header as an add message
-	void setAdd(Snd_ID sndid) {
-		type=add;
-		id=sndid;
-	}
-
-	//! Sets up the header as an erase message
-	void setDelete(RCRegion* rcregion) {
-		type=del;
-		region=rcregion;
-	}
-
-	//! Sets up the header as a wakeup message
-	void setWakeup() {
-		type=wakeup;
-	}
-
-	SoundManagerMsg(const SoundManagerMsg&); //!< don't call
-	SoundManagerMsg operator=(const SoundManagerMsg&); //!< don't call
-};
-
-/*! @file
- * @brief Defines SoundManagerMsg, a small header used by SoundManager for sending messages between processes
- * @author ejt (Creator)
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
- * $State: Rel $
- * $Date: 2003/09/25 15:32:08 $
- */
-
-#endif // INCLUDED_SoundManagerMsg_h
diff -urdN ../Tekkotsu_2.3/SoundPlay/SoundPlay.cc ./SoundPlay/SoundPlay.cc
--- ../Tekkotsu_2.3/SoundPlay/SoundPlay.cc	Tue Jan 11 18:10:44 2005
+++ ./SoundPlay/SoundPlay.cc	Wed Dec 31 19:00:00 1969
@@ -1,279 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-// Additional modifications for Tekkotsu framework
-
-#include "SoundPlay/entry.h"
-#include <OPENR/OPENRAPI.h>
-#include <OPENR/OSyslog.h>
-#include <OPENR/core_macro.h>
-#include "SoundPlay.h"
-
-#include <iostream>
-#include "SoundPlay/SoundManager.h"
-#include "Shared/RobotInfo.h"
-#include "Shared/Config.h"
-#include "Shared/debuget.h"
-#include "Events/EventRouter.h"
-
-SoundPlay::SoundPlay()
-	: active(0), soundManagerMemRgn(NULL), eventTranslatorQueueMemRgn(NULL), etrans(), speakerID(oprimitiveID_UNDEF)
-{
-	for (unsigned int i = 0; i < SOUND_NUM_BUFFER; i++)
-		region[i] = 0;
-}
-
-OStatus
-SoundPlay::DoInit(const OSystemEvent&)
-{
-	//OSYSDEBUG(("SoundPlay::DoInit()\n"));
-
-	NEW_ALL_SUBJECT_AND_OBSERVER;
-	REGISTER_ALL_ENTRY;
-	SET_ALL_READY_AND_NOTIFY_ENTRY;
-
-	observer[obsSoundManagerComm]->SetBufCtrlParam(0,1,SoundManager::MAX_SND+1);
-	//+1 to MAX_SND so that we can still get a delete message after we've filled up
-
-	//Set process ID
-	ProcessID::setID(ProcessID::SoundProcess);
-
-	//Read config file
-	config=new Config("/ms/config/tekkotsu.cfg");
-
-	erouter = new EventRouter;
-
-	//soundManagerMemRgn -> sndman setup
-	soundManagerMemRgn = InitRegion(sizeof(SoundManager));
-	sndman=new ((SoundManager*)soundManagerMemRgn->Base()) SoundManager;
-	sndman->InitAccess(subject[sbjSoundManagerComm]);
-	for(unsigned int i=0; i<config->sound.preload.size(); i++)
-		sndman->LoadFile(config->sound.preload[i]);
-
-	OpenSpeaker();
-	NewSoundVectorData();
-	SetPowerAndVolume();
-	return oSUCCESS;
-}
-
-OStatus
-SoundPlay::DoStart(const OSystemEvent&)
-{
-  //OSYSDEBUG(("SoundPlay::DoStart()\n"));
-
-	ENABLE_ALL_SUBJECT;
-	ASSERT_READY_TO_ALL_OBSERVER;
-	return oSUCCESS;
-}
-
-OStatus
-SoundPlay::DoStop(const OSystemEvent&)
-{
-	//OSYSDEBUG(("SoundPlay::DoStop()\n"));
-
-	sndman->StopPlay();
-
-	DISABLE_ALL_SUBJECT;
-	DEASSERT_READY_TO_ALL_OBSERVER;
-
-	return oSUCCESS;
-}
-
-OStatus
-SoundPlay::DoDestroy(const OSystemEvent&)
-{
-	for(unsigned int i=0; i<config->sound.preload.size(); i++)
-		sndman->ReleaseFile(config->sound.preload[i]);
-	delete erouter;
-	eventTranslatorQueueMemRgn->RemoveReference();
-	DELETE_ALL_SUBJECT_AND_OBSERVER;
-	return oSUCCESS;
-}
-
-void
-SoundPlay::ReadySendSound(const OReadyEvent&)
-{
-	//	OSYSDEBUG(("SoundPlay::Ready()\n"));
-	doSendSound();
-}
-
-void
-SoundPlay::ReadyRegisterSoundManager(const OReadyEvent&) {
-	static bool is_init=true;
-	if(is_init) {
-		is_init=false;
-		cout << objectName << " Registering SoundManager" << endl;
-		subject[sbjRegisterSoundManager]->SetData(soundManagerMemRgn);
-		subject[sbjRegisterSoundManager]->NotifyObservers();
-	}
-}
-
-void
-SoundPlay::GotEventTranslatorQueue(const ONotifyEvent& event){
-	std::cout << "SoundPlay-GOTEventTranslatorQueue..." << std::flush;
-	ASSERT(event.NumOfData()==1,"Too many EventTranslatorQueue");
-	eventTranslatorQueueMemRgn = event.RCData(0);
-	eventTranslatorQueueMemRgn->AddReference();
-	etrans.setQueue(reinterpret_cast<EventTranslator::Queue_t*>(eventTranslatorQueueMemRgn->Base()));
-	//SoundPlay should only be generator audioEGIDs
-	//but just in case, subscribe to everything except erouterEGID
-	for(unsigned int i=0; i<EventBase::numEGIDs; i++)
-		if(i!=EventBase::erouterEGID)
-			erouter->addTrapper(&etrans,static_cast<EventBase::EventGeneratorID_t>(i));
-	observer[obsReceiveEventTranslatorQueue]->AssertReady();
-	cout << "done" << endl;
-}
-
-void
-SoundPlay::GotSoundMsg(const ONotifyEvent& event) {
-	//	OSYSDEBUG(("SoundPlay::GotSoundMsg()\n"));
-	sndman->ReceivedMsg(event);
-	unsigned int curact=sndman->GetNumPlaying();
-	//	std::cout << "got-active=" << active << " cur=" << curact << std::endl;
-	if(active==0 && curact>0) {
-		active=curact;
-		doSendSound();
-	}
-	observer[obsSoundManagerComm]->AssertReady();
-}
-
-void
-SoundPlay::doSendSound() {
-	//	std::cout << "do-active=" << active << std::endl;
-	static unsigned int bufInUse=0;
-
-	active=sndman->GetNumPlaying();
-	if(active==0) { //if we don't have any active channels, don't send a buffer
-		if(bufInUse>0)
-			bufInUse--;
-		return;
-	}
-
-	RCRegion* rgn = FindFreeRegion();
-	if(rgn==NULL) //this can happen if a wakeup message comes in right after a sound stopped
-		return;
-	active=sndman->CopyTo(reinterpret_cast<OSoundVectorData*>(rgn->Base()));
-	subject[sbjSpeaker]->SetData(rgn);
-
-	if(bufInUse<SOUND_NUM_BUFFER-1) {
-		bufInUse++;
-		doSendSound();
-	} else //recursive base case
-		subject[sbjSpeaker]->NotifyObservers();
-}
-
-void
-SoundPlay::OpenSpeaker()
-{
-	OStatus result = OPENR::OpenPrimitive(SpeakerLocator, &speakerID);
-	if (result != oSUCCESS)
-		OSYSLOG1((osyslogERROR, "%s : %s %d","SoundPlay::OpenSpeaker()","OPENR::OpenPrimitive() FAILED", result));
-}
-
-void
-SoundPlay::NewSoundVectorData()
-{
-	OStatus result;
-	MemoryRegionID    soundVecDataID;
-	OSoundVectorData* soundVecData;
-
-	/*soundUnitSize (bytes/buffer) = sample_rate (samples/sec)
-	 *                               * sample_bits (bits/sample)
-	 *                               * [1/8] (bytes/bit)
-	 *                               * SoundBufferTime (ms/buffer)
-	 *                               * [1/1000] (sec/ms)
-	 */
-	size_t soundUnitSize = config->sound.sample_rate*config->sound.sample_bits/8*SoundBufferTime/1000;
-
-	for (unsigned int i = 0; i < SOUND_NUM_BUFFER; i++) {
-		result = OPENR::NewSoundVectorData(1, soundUnitSize,&soundVecDataID, &soundVecData);
-		if (result != oSUCCESS) {
-			OSYSLOG1((osyslogERROR, "%s : %s %d","SoundPlay::NewSoundVectorData()","OPENR::NewSoundVectorData() FAILED", result));
-			return;
-		}
-
-		soundVecData->SetNumData(1);
-		OSoundInfo* sinfo = soundVecData->GetInfo(0);
-		sinfo->Set(odataSOUND_VECTOR,speakerID,soundUnitSize);
-		sinfo->dataSize      = soundUnitSize;
-		sinfo->format        = osoundformatPCM;
-		sinfo->channel       = osoundchannelMONO;
-		sinfo->samplingRate  = config->sound.sample_rate;
-		sinfo->bitsPerSample = config->sound.sample_bits;
-
-		region[i] = new RCRegion(soundVecData->vectorInfo.memRegionID,soundVecData->vectorInfo.offset,(void*)soundVecData,soundVecData->vectorInfo.totalSize);
-	}
-}
-
-void
-SoundPlay::SetPowerAndVolume()
-{
-	OStatus result;
-
-	result = OPENR::ControlPrimitive(speakerID,oprmreqSPEAKER_MUTE_OFF, 0, 0, 0, 0);
-	if (result != oSUCCESS)
-		OSYSLOG1((osyslogERROR, "%s : %s %d","SoundPlay::SetPowerAndVolume()","OPENR::ControlPrimitive(SPEAKER_MUTE_OFF) FAILED", result));
-
-	OPrimitiveControl_SpeakerVolume volume(config->sound.volume);
-	result = OPENR::ControlPrimitive(speakerID,oprmreqSPEAKER_SET_VOLUME,&volume, sizeof(volume), 0, 0);
-	if (result != oSUCCESS)
-		OSYSLOG1((osyslogERROR, "%s : %s %d","SoundPlay::SetPowerAndVolume()","OPENR::ControlPrimitive(SPEAKER_SET_VOLUME) FAILED",result));
-
-	if (config->sound.sample_rate == 16000 && config->sound.sample_bits == 16) {
-		OPrimitiveControl_SpeakerSoundType soundType(ospksndMONO16K16B);
-		result = OPENR::ControlPrimitive(speakerID,oprmreqSPEAKER_SET_SOUND_TYPE,&soundType, sizeof(soundType), 0, 0);
-		if (result != oSUCCESS)
-			OSYSLOG1((osyslogERROR, "%s : %s %d","SoundPlay::SetPowerAndVolume()","OPENR::ControlPrimitive(SPEAKER_SET_SOUND_TYPE) FAILED",result));
-	}
-}
-
-/*! Will round up size to the nearest page */
-RCRegion*
-SoundPlay::InitRegion(unsigned int size) {
-	unsigned int pagesize=4096;
-	sError err=GetPageSize(&pagesize);
-	ASSERT(err==sSUCCESS,"Error "<<err<<" getting page size");
-	unsigned int pages=(size+pagesize-1)/pagesize;
-	return new RCRegion(pages*pagesize);
-}
-
-RCRegion*
-SoundPlay::FindFreeRegion()
-{
-	for (unsigned int i = 0; i < SOUND_NUM_BUFFER; i++)
-		if (region[i]->NumberOfReference() == 1)
-			return region[i];
-	return 0;
-}
-
-/*! @file
- * @brief Implements the SoundPlay process (a.k.a. OObject), which is responsible for sending sound buffers to the system to play
- * @author Sony (Creator)
- *
- * This is basically the SoundPlay example from the Sony code, with a few modifications.
- * Here's the license Sony provided with it:
- *
- * Copyright 2002,2003 Sony Corporation 
- *
- * Permission to use, copy, modify, and redistribute this software for
- * non-commercial use is hereby granted.
- *
- * This software is provided "as is" without warranty of any kind,
- * either expressed or implied, including but not limited to the
- * implied warranties of fitness for a particular purpose.
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.15 $
- * $State: Exp $
- * $Date: 2005/01/11 23:10:44 $
- */
-
diff -urdN ../Tekkotsu_2.3/SoundPlay/SoundPlay.h ./SoundPlay/SoundPlay.h
--- ../Tekkotsu_2.3/SoundPlay/SoundPlay.h	Tue Dec 23 01:33:44 2003
+++ ./SoundPlay/SoundPlay.h	Wed Dec 31 19:00:00 1969
@@ -1,93 +0,0 @@
-#ifndef INCLUDED_SoundPlay_h_
-#define INCLUDED_SoundPlay_h_
-
-#include <OPENR/OObject.h>
-#include <OPENR/OSubject.h>
-#include <OPENR/OObserver.h>
-#include "def.h"
-
-#include "Events/EventTranslator.h"
-
-//! The process (a.k.a. OObject), which is responsible for sending sound buffers to the system to play
-/*! This sound process will purposely starve the system of sound buffers when nothing is
- *  playing, both to eliminate needless zeroing of entire buffers, as well as to reduce system
- *  overhead of playing empty buffers.
- *
- *  If you want to know how to play sounds, you should be looking at SoundManager's documentation.
- *  
- *  Basically a slightly modified version of the SoundPlay example code from Sony.  Here's their license:
- *  Copyright 2002,2003 Sony Corporation 
- *
- *  Permission to use, copy, modify, and redistribute this software for
- *  non-commercial use is hereby granted.
- *
- *  This software is provided "as is" without warranty of any kind,
- *  either expressed or implied, including but not limited to the
- *  implied warranties of fitness for a particular purpose.
- */
-class SoundPlay : public OObject {
- public:
-	SoundPlay();            //!< constructor
-	virtual ~SoundPlay() {} //!< destructor
-
-	virtual OStatus DoInit   (const OSystemEvent& event); //!< called by system when time to do init
-	virtual OStatus DoStart  (const OSystemEvent& event); //!< called by system when time to start running
-	virtual OStatus DoStop   (const OSystemEvent& event); //!< called by system when time to stop running
-	virtual OStatus DoDestroy(const OSystemEvent& event); //!< called by system when time to free
-
-	void ReadySendSound(const OReadyEvent& event);            //!< called by system when it's ready for another sound buffer
-	void ReadyRegisterSoundManager(const OReadyEvent& event); //!< called by system when observers are ready to receive the SoundManager
-	void GotEventTranslatorQueue(const ONotifyEvent& event);  //!< called by system when the queue for sending events to Main is being published
-
-	void GotSoundMsg(const ONotifyEvent& event); //!< called by system when SoundManager has sent itself a message on a different process (either to add or remove sounds from memory)
-
-	OSubject*  subject[numOfSubject];   //!< array of subject IDs, used to identify outgoing data
-	OObserver* observer[numOfObserver]; //!< array of observer IDs, used to identify what's ready
-
- private:
-	void      doSendSound();                 //!< called to send sound buffer(s) to system
-	void      OpenSpeaker();                 //!< initializes speaker
-	void      NewSoundVectorData();          //!< sets up sound buffers
-	void      SetPowerAndVolume();           //!< sets volume to max
-	RCRegion* InitRegion(unsigned int size); //!< inits each buffer
-	RCRegion* FindFreeRegion();              //!< finds the first sound buffer which system isn't using (buffers are recycled)
-		
-	static const size_t SOUND_NUM_BUFFER = 2;                                    //!< number of buffers to use
-	
-	unsigned int active; //!< number of active sound channels - if it's 0, we'll purposely starve system of sound buffers
-
-	RCRegion*      soundManagerMemRgn; //!< SoundPlay creates, Main & Motion receive - Shared region used by SoundManager
-	RCRegion*      eventTranslatorQueueMemRgn; //!< Main creates, Motion (& SoundPlay) receive
-	EventTranslator etrans; //!< will be given all events created by SoundManager to be forwarded to Main
-
-	OPrimitiveID   speakerID;  //!< ID returned to system after opening SPEAKER_LOCATOR
-	RCRegion*      region[SOUND_NUM_BUFFER]; //!< holds references to shared regions holding sound clips
-
-	SoundPlay(const SoundPlay&); //!< don't call
-	SoundPlay& operator=(const SoundPlay&); //!< don't call
-};
-
-/*! @file
- * @brief Describes the SoundPlay process (a.k.a. OObject), which is responsible for sending sound buffers to the system to play
- * @author Sony (Creator)
- *
- * This is basically the SoundPlay example from the Sony code, with a few modifications.
- * Here's the license Sony provided with it:
- *
- * Copyright 2002,2003 Sony Corporation 
- *
- * Permission to use, copy, modify, and redistribute this software for
- * non-commercial use is hereby granted.
- *
- * This software is provided "as is" without warranty of any kind,
- * either expressed or implied, including but not limited to the
- * implied warranties of fitness for a particular purpose.
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
- * $State: Exp $
- * $Date: 2003/12/23 06:33:44 $
- */
-
-#endif // SoundPlay_h_DEFINED
diff -urdN ../Tekkotsu_2.3/SoundPlay/SoundPlay.ocf ./SoundPlay/SoundPlay.ocf
--- ../Tekkotsu_2.3/SoundPlay/SoundPlay.ocf	Sat Mar  8 21:45:25 2003
+++ ./SoundPlay/SoundPlay.ocf	Wed Dec 31 19:00:00 1969
@@ -1 +0,0 @@
-object SoundPlay 3072 16384 128 cache notlb kernel
diff -urdN ../Tekkotsu_2.3/SoundPlay/WAV.cc ./SoundPlay/WAV.cc
--- ../Tekkotsu_2.3/SoundPlay/WAV.cc	Fri Jul 25 16:18:08 2003
+++ ./SoundPlay/WAV.cc	Wed Dec 31 19:00:00 1969
@@ -1,247 +0,0 @@
-/*! @file
- * @brief Allows you to load WAV files from the memory stick
- * @author Sony (Creator)
- *
- * This file is from the SoundPlay example from the Sony sample code, with a few if any modifications.
- * Here's the license Sony provided with it:
- *
- * Copyright 2002,2003 Sony Corporation 
- *
- * Permission to use, copy, modify, and redistribute this software for
- * non-commercial use is hereby granted.
- *
- * This software is provided "as is" without warranty of any kind,
- * either expressed or implied, including but not limited to the
- * implied warranties of fitness for a particular purpose.
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.4 $
- * $State: Rel $
- * $Date: 2003/07/25 20:18:08 $
- */
-
-#include <OPENR/OPENR.h>
-#include <OPENR/OSyslog.h>
-#include "WAV.h"
-
-WAV::WAV() : soundInfo(), dataStart(0), dataEnd(0), dataCurrent(0)
-{
-}
-
-WAV::WAV(byte* addr) : dataStart(0), dataEnd(0), dataCurrent(0)
-{
-    Set(addr);
-}
-
-WAVError
-WAV::Set(byte *addr)
-{
-    //
-    // Check Wav Header
-    //
-    if (strncmp((char *)addr, "RIFF", 4)) return WAV_NOT_RIFF;
-    addr += 4;
-
-    longword length = get_longword(addr);
-    addr += sizeof(longword);
-		//    OSYSDEBUG(( "length = %x\n", length));
-
-    if (strncmp((char *)addr, "WAVE", 4)) return WAV_NOT_WAV;
-    length -= 4;
-    addr += 4;
-
-    //
-    // Check Chunk
-    //
-    while (length > 8) {
-
-        size_t chunksize;
-        char *buf = (char *)addr;
-    
-        addr += 4;
-
-        chunksize = get_longword(addr);
-        addr += sizeof(longword);
-        length -= chunksize + 8;
-
-        if (!strncmp(buf, "fmt ", 4)) {
-
-            //
-            // Format Chunk
-            //
-
-            //
-            // Check WAV Type
-            //
-            soundInfo.format = (OSoundFormat)get_word(addr);
-            addr += sizeof(word);
-            if (soundInfo.format != osoundformatPCM) {
-                OSYSDEBUG(("WAV_FORMAT_NOT_SUPPORTED\n"));
-                return WAV_FORMAT_NOT_SUPPORTED;
-            }
-
-            //
-            // Channel
-            //
-            soundInfo.channel = (OSoundChannel)get_word(addr);
-            addr += sizeof(word);
-            if (soundInfo.channel != osoundchannelMONO) {
-                OSYSDEBUG(("WAV_CHANNEL_NOT_SUPPORTED\n"));
-                return WAV_CHANNEL_NOT_SUPPORTED;
-            }
-
-            //
-            // Sampling Rate
-            //
-            longword frq = get_longword(addr);
-            addr += sizeof(longword);
-            soundInfo.samplingRate = (word)frq;
-            if (soundInfo.samplingRate != 8000 &&
-                soundInfo.samplingRate != 16000) {
-                OSYSDEBUG(("WAV_SAMPLINGRATE_NOT_SUPPORTED\n"));
-                return WAV_SAMPLINGRATE_NOT_SUPPORTED;
-            }
-
-            //
-            // DataSize Per sec
-            //
-            addr += sizeof(longword);
-
-            //
-            // Block Size
-            //
-            addr += sizeof(word);
-
-            //
-            // Bits Of Sample
-            //
-            soundInfo.bitsPerSample = get_word(addr);
-            addr += sizeof(word);
-            soundInfo.bitsPerSample *= soundInfo.channel;
-            if (soundInfo.bitsPerSample != 8 &&
-                soundInfo.bitsPerSample != 16) {
-                OSYSDEBUG(("WAV_BITSPERSAMPLE_NOT_SUPPORTED\n"));
-                return WAV_BITSPERSAMPLE_NOT_SUPPORTED;
-            }
-
-            //
-            // Skip Extentded Infomation
-            //
-            addr += chunksize - FMTSIZE_WITHOUT_EXTINFO;
-            
-						//            OSYSDEBUG(( "fmt chunksize = %d\n", chunksize));
-						//            OSYSDEBUG(( "samplingRate  = %d\n", soundInfo.samplingRate));
-						//            OSYSDEBUG(( "bitsPerSample = %d\n", soundInfo.bitsPerSample));
-            
-        } else if (!strncmp(buf, "data", 4)) {
-
-            //
-            // Data Chunk
-            //
-					//            OSYSDEBUG(( "data chunksize = %d\n", chunksize));
-            soundInfo.dataSize = chunksize;
-            dataStart = dataCurrent = addr;
-            dataEnd = dataStart + soundInfo.dataSize;
-            break;
-
-        } else {
-
-            //
-            // Fact Chunk
-            //
-            addr += chunksize;
-        }
-    }
-
-    int rate = soundInfo.samplingRate;
-    int bits = soundInfo.bitsPerSample;
-    if (rate == 8000 & bits == 8) {
-        soundUnitSize = MONO8K8B_UNIT_SIZE;
-    } else if (rate == 16000 & bits == 16) {
-        soundUnitSize = MONO16K16B_UNIT_SIZE;
-    }
-    
-    return WAV_SUCCESS;
-}
-
-WAVError
-WAV::CopyTo(OSoundVectorData* data)
-{
-    if (dataCurrent >= dataEnd) return WAV_FAIL;
-    
-    OSoundInfo* sinfo = data->GetInfo(0);
-    if (soundUnitSize > sinfo->maxDataSize) {
-        OSYSDEBUG(("WAV_SIZE_NOT_ENOUGH "));
-        return WAV_SIZE_NOT_ENOUGH;
-    }
-
-    sinfo->dataSize      = soundUnitSize;
-    sinfo->format        = soundInfo.format;
-    sinfo->channel       = soundInfo.channel;
-    sinfo->samplingRate  = soundInfo.samplingRate;
-    sinfo->bitsPerSample = soundInfo.bitsPerSample;
-
-    byte* src  = dataCurrent;
-    byte* dest = data->GetData(0);
-    byte* end;
-    int num = (int)(dataEnd - dataCurrent);
-
-    if (soundUnitSize <= (unsigned int)num) {
-    
-        end = dest + soundUnitSize;
-        if (soundUnitSize == MONO8K8B_UNIT_SIZE) {
-            while (dest < end) {
-                *dest++ = *src++ ^ 0x80; // offset binary -> signed char
-            }
-        } else { // MONO16K16B_UNIT_SIZE
-            while (dest < end) {
-                *dest++ = *src++;
-            }
-        }
-        dataCurrent += soundUnitSize;
-
-    } else {
-
-        end = dest + num;
-        if (soundUnitSize == MONO8K8B_UNIT_SIZE) {
-            while (dest < end) {
-                *dest++ = *src++ ^ 0x80; // offset binary -> signed char
-            }
-        } else { // MONO16K16B_UNIT_SIZE
-            while (dest < end) {
-                *dest++ = *src++;
-            }
-        }
-        memset(dest, 0x0, soundUnitSize - num);
-        dataCurrent = dataEnd;
-
-    }
-
-    return WAV_SUCCESS;
-}
-
-WAVError
-WAV::Rewind()
-{
-    dataCurrent = dataStart;
-    return WAV_SUCCESS;
-}
-
-longword
-WAV::get_longword(byte* ptr)
-{
-    longword lw0 = (longword)ptr[0];
-    longword lw1 = (longword)ptr[1] << 8;
-    longword lw2 = (longword)ptr[2] << 16;
-    longword lw3 = (longword)ptr[3] << 24;
-    return lw0 + lw1 + lw2 + lw3;
-}
-
-word
-WAV::get_word(byte* ptr)
-{
-    word w0 = (word)ptr[0];
-    word w1 = (word)ptr[1] << 8;
-    return w0 + w1;
-}
diff -urdN ../Tekkotsu_2.3/SoundPlay/WAV.h ./SoundPlay/WAV.h
--- ../Tekkotsu_2.3/SoundPlay/WAV.h	Fri Jul 25 16:18:08 2003
+++ ./SoundPlay/WAV.h	Wed Dec 31 19:00:00 1969
@@ -1,80 +0,0 @@
-/*! @file
- * @brief Allows you to load WAV files from the memory stick
- * @author Sony (Creator)
- *
- * This file is from the SoundPlay example from the Sony sample code, with a few if any modifications.
- * Here's the license Sony provided with it:
- *
- * Copyright 2002,2003 Sony Corporation 
- *
- * Permission to use, copy, modify, and redistribute this software for
- * non-commercial use is hereby granted.
- *
- * This software is provided "as is" without warranty of any kind,
- * either expressed or implied, including but not limited to the
- * implied warranties of fitness for a particular purpose.
- *
- * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
- * $State: Rel $
- * $Date: 2003/07/25 20:18:08 $
- */
-
-#ifndef WAV_h_DEFINED
-#define WAV_h_DEFINED
-
-#include <OPENR/ODataFormats.h>
-
-enum WAVError {
-    WAV_SUCCESS,
-    WAV_FAIL,
-    WAV_NOT_RIFF,
-    WAV_NOT_WAV,
-    WAV_FORMAT_NOT_SUPPORTED,
-    WAV_CHANNEL_NOT_SUPPORTED,
-    WAV_SAMPLINGRATE_NOT_SUPPORTED,
-    WAV_BITSPERSAMPLE_NOT_SUPPORTED,
-    WAV_SIZE_NOT_ENOUGH,
-};
-
-class WAV {
-public:
-    WAV();
-    WAV(byte* addr);
-    ~WAV() {}
-
-    WAVError Set(byte *addr);
-    WAVError CopyTo(OSoundVectorData* data);
-    WAVError Rewind();
-
-    unsigned int    GetSamplingRate()  { return soundInfo.samplingRate;  }
-    unsigned int    GetBitsPerSample() { return soundInfo.bitsPerSample; }
-    size_t GetSoundUnitSize() { return soundUnitSize;           }
-		
-		byte*  GetDataStart()     { return dataStart;               }
-		byte*  GetDataEnd()       { return dataEnd;                 }
-
-private:
-    longword get_longword(byte* addr);
-    word     get_word(byte* addr);
-
-    // 8KHz 8bits MONO (8 * 1 * 1 * 32ms = 256)
-    static const size_t MONO8K8B_UNIT_SIZE  = 256;
-
-    // 16KHz 16bits MONO (16 * 2 * 1 * 32ms = 1024)
-    static const size_t MONO16K16B_UNIT_SIZE  = 1024;
-
-    static const size_t FMTSIZE_WITHOUT_EXTINFO = 16;
-
-    OSoundInfo soundInfo;
-    size_t     soundUnitSize;
-    byte*      dataStart;
-    byte*      dataEnd;
-    byte*      dataCurrent;
-
-		WAV(const WAV&); //!< don't call
-		WAV& operator=(const WAV&); //!< don't call
-};
-
-#endif // WAV_h_DEFINED
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/3barks.wav and ./SoundPlay/clips/converted/16 bit-Hz/3barks.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/3yips.wav and ./SoundPlay/clips/converted/16 bit-Hz/3yips.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/barkhigh.wav and ./SoundPlay/clips/converted/16 bit-Hz/barkhigh.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/barklow.wav and ./SoundPlay/clips/converted/16 bit-Hz/barklow.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/barkmed.wav and ./SoundPlay/clips/converted/16 bit-Hz/barkmed.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/barkreal.wav and ./SoundPlay/clips/converted/16 bit-Hz/barkreal.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/camera.wav and ./SoundPlay/clips/converted/16 bit-Hz/camera.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/catcry.wav and ./SoundPlay/clips/converted/16 bit-Hz/catcry.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/catyowl.wav and ./SoundPlay/clips/converted/16 bit-Hz/catyowl.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/crash.wav and ./SoundPlay/clips/converted/16 bit-Hz/crash.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/cutey.wav and ./SoundPlay/clips/converted/16 bit-Hz/cutey.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/donkey.wav and ./SoundPlay/clips/converted/16 bit-Hz/donkey.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/fart.wav and ./SoundPlay/clips/converted/16 bit-Hz/fart.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/glass.wav and ./SoundPlay/clips/converted/16 bit-Hz/glass.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/growl.wav and ./SoundPlay/clips/converted/16 bit-Hz/growl.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/growl2.wav and ./SoundPlay/clips/converted/16 bit-Hz/growl2.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/grrr.wav and ./SoundPlay/clips/converted/16 bit-Hz/grrr.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/howl.wav and ./SoundPlay/clips/converted/16 bit-Hz/howl.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/mew.wav and ./SoundPlay/clips/converted/16 bit-Hz/mew.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/0.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/0.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/1.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/1.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/2.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/2.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/3.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/3.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/4.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/4.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/5.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/5.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/6.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/6.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/7.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/7.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/8.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/8.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/9.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/9.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/dot.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/dot.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/numbers/point.wav and ./SoundPlay/clips/converted/16 bit-Hz/numbers/point.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/ping.wav and ./SoundPlay/clips/converted/16 bit-Hz/ping.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/roar.wav and ./SoundPlay/clips/converted/16 bit-Hz/roar.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/skid.wav and ./SoundPlay/clips/converted/16 bit-Hz/skid.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/sniff.wav and ./SoundPlay/clips/converted/16 bit-Hz/sniff.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/tick.wav and ./SoundPlay/clips/converted/16 bit-Hz/tick.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/toc.wav and ./SoundPlay/clips/converted/16 bit-Hz/toc.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/whiip.wav and ./SoundPlay/clips/converted/16 bit-Hz/whiip.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/whimper.wav and ./SoundPlay/clips/converted/16 bit-Hz/whimper.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/whoop.wav and ./SoundPlay/clips/converted/16 bit-Hz/whoop.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/yap.wav and ./SoundPlay/clips/converted/16 bit-Hz/yap.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/16 bit-Hz/yipper.wav and ./SoundPlay/clips/converted/16 bit-Hz/yipper.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/3barks.wav and ./SoundPlay/clips/converted/8 bit-Hz/3barks.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/3yips.wav and ./SoundPlay/clips/converted/8 bit-Hz/3yips.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/barkhigh.wav and ./SoundPlay/clips/converted/8 bit-Hz/barkhigh.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/barklow.wav and ./SoundPlay/clips/converted/8 bit-Hz/barklow.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/barkmed.wav and ./SoundPlay/clips/converted/8 bit-Hz/barkmed.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/barkreal.wav and ./SoundPlay/clips/converted/8 bit-Hz/barkreal.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/camera.wav and ./SoundPlay/clips/converted/8 bit-Hz/camera.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/catcry.wav and ./SoundPlay/clips/converted/8 bit-Hz/catcry.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/catyowl.wav and ./SoundPlay/clips/converted/8 bit-Hz/catyowl.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/crash.wav and ./SoundPlay/clips/converted/8 bit-Hz/crash.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/cutey.wav and ./SoundPlay/clips/converted/8 bit-Hz/cutey.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/donkey.wav and ./SoundPlay/clips/converted/8 bit-Hz/donkey.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/fart.wav and ./SoundPlay/clips/converted/8 bit-Hz/fart.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/glass.wav and ./SoundPlay/clips/converted/8 bit-Hz/glass.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/growl.wav and ./SoundPlay/clips/converted/8 bit-Hz/growl.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/growl2.wav and ./SoundPlay/clips/converted/8 bit-Hz/growl2.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/grrr.wav and ./SoundPlay/clips/converted/8 bit-Hz/grrr.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/howl.wav and ./SoundPlay/clips/converted/8 bit-Hz/howl.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/mew.wav and ./SoundPlay/clips/converted/8 bit-Hz/mew.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/0.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/0.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/1.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/1.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/2.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/2.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/3.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/3.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/4.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/4.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/5.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/5.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/6.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/6.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/7.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/7.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/8.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/8.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/9.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/9.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/dot.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/dot.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/numbers/point.wav and ./SoundPlay/clips/converted/8 bit-Hz/numbers/point.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/ping.wav and ./SoundPlay/clips/converted/8 bit-Hz/ping.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/roar.wav and ./SoundPlay/clips/converted/8 bit-Hz/roar.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/skid.wav and ./SoundPlay/clips/converted/8 bit-Hz/skid.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/sniff.wav and ./SoundPlay/clips/converted/8 bit-Hz/sniff.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/tick.wav and ./SoundPlay/clips/converted/8 bit-Hz/tick.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/toc.wav and ./SoundPlay/clips/converted/8 bit-Hz/toc.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/whiip.wav and ./SoundPlay/clips/converted/8 bit-Hz/whiip.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/whimper.wav and ./SoundPlay/clips/converted/8 bit-Hz/whimper.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/whoop.wav and ./SoundPlay/clips/converted/8 bit-Hz/whoop.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/yap.wav and ./SoundPlay/clips/converted/8 bit-Hz/yap.wav differ
Binary files ../Tekkotsu_2.3/SoundPlay/clips/converted/8 bit-Hz/yipper.wav and ./SoundPlay/clips/converted/8 bit-Hz/yipper.wav differ
diff -urdN ../Tekkotsu_2.3/SoundPlay/stub.cfg ./SoundPlay/stub.cfg
--- ../Tekkotsu_2.3/SoundPlay/stub.cfg	Sun Apr  6 16:57:46 2003
+++ ./SoundPlay/stub.cfg	Wed Dec 31 19:00:00 1969
@@ -1,8 +0,0 @@
-ObjectName : SoundPlay
-NumOfOSubject   : 3
-NumOfOObserver  : 2
-Service : "SoundPlay.Speaker.OSoundVectorData.S", null, ReadySendSound()
-Service : "SoundPlay.RegisterSoundManager.SoundManager.S", null, ReadyRegisterSoundManager()
-Service : "SoundPlay.SoundManagerComm.SoundManagerMsg.O", null, GotSoundMsg()
-Service : "SoundPlay.SoundManagerComm.SoundManagerMsg.S", null, null
-Service : "SoundPlay.ReceiveEventTranslatorQueue.EventTranslatorQueue.O"     , null, GotEventTranslatorQueue()
diff -urdN ../Tekkotsu_2.3/TinyFTPD/FtpConfig.h ./TinyFTPD/FtpConfig.h
--- ../Tekkotsu_2.3/TinyFTPD/FtpConfig.h	Tue Jul  6 18:30:57 2004
+++ ./TinyFTPD/FtpConfig.h	Wed Dec 31 19:00:00 1969
@@ -1,132 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#ifndef _FtpConfig_h_DEFINED
-#define _FtpConfig_h_DEFINED
-
-#define FTP_LISTEN_PORT    21
-#define FTP_DATA_PORT      20
-#define FTP_PASV_DATA_PORT 3000
-#define FTP_CONNECTION_MAX 4
-#define FTP_BUFFER_SIZE    8192
-#define FTP_PASSWD_PATH    "/MS/OPEN-R/MW/CONF/PASSWD"
-#define MAX_STRING_LENGTH  128
-#define MAX_LOGIN          8
-
-// some character constants
-// ---------------------------------------
-
-#define CR 13   // carriage return
-#define LF 10   // line feed
-#define HT 9    // horizontal tab
-#define SP 32   // space
-
-struct Passwd {
-    char user[MAX_STRING_LENGTH];
-    char pass[MAX_STRING_LENGTH];
-    char home[MAX_STRING_LENGTH];
-
-    Passwd() {
-        user[0] = '\0';
-        pass[0] = '\0';
-        home[0] = '\0';
-    }
-};
-
-enum FTPLoginState {
-    FTP_NOT_LOGIN,
-    FTP_LOGIN,
-    FTP_GET_REQUEST,
-    FTP_UNDEF
-};
-
-enum FTPDataType {
-    FTP_DATA_I,
-    FTP_DATA_A
-};
-
-// FTP Method
-// --------------------------------------------------------
-enum FTPMethod {
-    FTP_METHOD_USER,
-    FTP_METHOD_PASS,
-    FTP_METHOD_PORT,
-    FTP_METHOD_PASV,
-    FTP_METHOD_TYPE,
-    FTP_METHOD_MODE,
-    FTP_METHOD_STRU,
-    FTP_METHOD_RETR,
-    FTP_METHOD_STOR,
-    FTP_METHOD_APPE,
-    FTP_METHOD_RNFR,
-    FTP_METHOD_RNTO,
-    FTP_METHOD_DELE,
-    FTP_METHOD_CWD,
-    FTP_METHOD_CDUP,
-    FTP_METHOD_RMD,
-    FTP_METHOD_MKD,
-    FTP_METHOD_PWD,
-    FTP_METHOD_LIST,
-    FTP_METHOD_NLST,
-    FTP_METHOD_SYST,
-    FTP_METHOD_STAT,
-    FTP_METHOD_HELP,
-    FTP_METHOD_NOOP,
-    FTP_METHOD_QUIT,
-    FTP_METHOD_UNSUPPORTED
-};
-
-// FTP Status
-// --------------------------------------------------------
-enum FTPReplyCode
-{
-    // Positive Preliminary reply
-    FTP_REPLY_RESTART_MARKER  = 110,
-    FTP_REPLY_SERVER_READY    = 120,
-    FTP_REPLY_TRANSFER_START  = 125,
-    FTP_REPLY_OPEN_CONNECTION = 150,
-
-    // Positive Completion reply
-    FTP_REPLY_COMMAND_OK      = 200,
-    FTP_REPLY_SUPERFLUOUS     = 202,
-    FTP_REPLY_SYSTEM_STATUS   = 211,
-    FTP_REPLY_HELP_MESSAGE    = 214,
-    FTP_REPLY_SYSTEM_TYPE     = 215,
-    FTP_REPLY_SERVICE_READY   = 220,
-    FTP_REPLY_SERVICE_CLOSE   = 221,
-    FTP_REPLY_CLOSE_DATA      = 226,
-    FTP_REPLY_ENTER_PASSIVE   = 227,
-    FTP_REPLY_USER_LOGIN      = 230,
-    FTP_REPLY_FILE_ACTION_OK  = 250,
-    FTP_REPLY_PATH_CREATED    = 257,
-
-    // Positive Intermediate reply
-    FTP_REPLY_NEED_PASSWD     = 331,
-    FTP_REPLY_REQUESTED_FILE  = 350,
-
-    // Transient Negative Completion reply
-    FTP_REPLY_NOT_AVAILABLE   = 421,
-    FTP_REPLY_TRANSFER_ABORT  = 426,
-    FTP_REPLY_NOT_TAKEN       = 450,
-
-    // Permanent Negative Completion reply
-    FTP_REPLY_UNKNOWN_COMMAND = 500,
-    FTP_REPLY_NOT_IMPLEMENT   = 502,
-    FTP_REPLY_BAD_SEQUENCE    = 503,
-    FTP_REPLY_NOT_LOGIN       = 530,
-    FTP_REPLY_NO_FILE         = 550,
-    FTP_REPLY_NOT_TOKEN       = 553,
-
-    // Undefined Reply
-    FTP_REPLY_NONE = 999
-};
-
-#endif /* _FtpConfig_h_DEFINED*/
diff -urdN ../Tekkotsu_2.3/TinyFTPD/FtpDTP.cc ./TinyFTPD/FtpDTP.cc
--- ../Tekkotsu_2.3/TinyFTPD/FtpDTP.cc	Tue Jul  6 18:43:45 2004
+++ ./TinyFTPD/FtpDTP.cc	Wed Dec 31 19:00:00 1969
@@ -1,382 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#include <OPENR/OSyslog.h>
-#include <OPENR/ODebug.h>
-#include "FtpDTP.h"
-
-FtpDTP::FtpDTP()
-{
-}
-
-OStatus
-FtpDTP::Initialize(const OID& myoid, const antStackRef& ipstack, void* index)
-{
-    OSYSDEBUG(("FtpDTP::Initialize()\n"));
-
-    myOID        = myoid;
-    ipstackRef   = ipstack;
-    continuation = index;
-
-    // initialize FTP connection
-    method   = FTP_METHOD_NOOP;
-    dataType = FTP_DATA_A;
-    passive  = false;
-    connectPort = FTP_DATA_PORT;
-
-    // initialize File System
-    ResetFilename();
-    strcpy(ftpDir, "/MS/");
-
-    connection.state = CONNECTION_CLOSED;
-
-    // 
-    // Allocate send buffer
-    //
-    antEnvCreateSharedBufferMsg sendBufferMsg(FTP_BUFFER_SIZE);
-
-    sendBufferMsg.Call(ipstackRef, sizeof(sendBufferMsg));
-    if (sendBufferMsg.error != ANT_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
-                  "FtpDTP::Initialize()",
-                  "Can't allocate send buffer",
-                  index, sendBufferMsg.error));
-        return oFAIL;
-    }
-
-    connection.sendBuffer = sendBufferMsg.buffer;
-    connection.sendBuffer.Map();
-    connection.sendData = (byte*)(connection.sendBuffer.GetAddress());
-
-    //
-    // Allocate receive buffer
-    //
-    antEnvCreateSharedBufferMsg recvBufferMsg(FTP_BUFFER_SIZE);
-
-    recvBufferMsg.Call(ipstackRef, sizeof(recvBufferMsg));
-    if (recvBufferMsg.error != ANT_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
-                  "FtpDTP::Initialize()",
-                  "Can't allocate receive buffer",
-                  index, recvBufferMsg.error));
-        return oFAIL;
-    }
-
-    connection.recvBuffer = recvBufferMsg.buffer;
-    connection.recvBuffer.Map();
-    connection.recvData = (byte*)(connection.recvBuffer.GetAddress());
-
-    return oSUCCESS;
-}
-
-OStatus
-FtpDTP::Listen()
-{
-    OSYSDEBUG(("FtpDTP::Listen()\n"));
-
-    if (connection.state != CONNECTION_CLOSED) return oFAIL;
-
-    //
-    // Create endpoint
-    //
-    antEnvCreateEndpointMsg tcpCreateMsg(EndpointType_TCP,
-                                         FTP_BUFFER_SIZE * 2);
-
-    tcpCreateMsg.Call(ipstackRef, sizeof(tcpCreateMsg));
-    if (tcpCreateMsg.error != ANT_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
-                  "FtpDTP::Listen()",
-                  "Can't create endpoint",
-                  (int)continuation, tcpCreateMsg.error));
-        return oFAIL;
-    }
-    connection.endpoint = tcpCreateMsg.moduleRef;
-
-    //
-    // Listen
-    //
-    TCPEndpointListenMsg listenMsg(connection.endpoint,
-                                   IP_ADDR_ANY, connectPort);
-    listenMsg.continuation = continuation;
-
-    listenMsg.Send(ipstackRef, myOID,
-                   Extra_Entry[entryListenContforDTP], sizeof(listenMsg));
-    
-    connection.state = CONNECTION_LISTENING;
-
-    return oSUCCESS;
-}
-
-OStatus
-FtpDTP::Connect()
-{
-    OSYSDEBUG(("FtpDTP::Connect()\n"));
-
-    if (connection.state != CONNECTION_CLOSED) return oFAIL;
-
-    //
-    // Create endpoint
-    //
-    antEnvCreateEndpointMsg tcpCreateMsg(EndpointType_TCP,
-                                         FTP_BUFFER_SIZE * 2);
-
-    tcpCreateMsg.Call(ipstackRef, sizeof(tcpCreateMsg));
-    if (tcpCreateMsg.error != ANT_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
-                  "FtpDTP::Connect()",
-                  "Can't create endpoint",
-                  (int)continuation, tcpCreateMsg.error));
-        return oFAIL;
-    }
-    connection.endpoint = tcpCreateMsg.moduleRef;
-
-    //
-    // Connect
-    //
-    TCPEndpointConnectMsg connectMsg(connection.endpoint,
-                                     0, FTP_DATA_PORT,
-                                     connectIP, connectPort);
-    connectMsg.continuation = continuation;
-
-    connectMsg.Send(ipstackRef, myOID,
-                    Extra_Entry[entryConnectContforDTP], sizeof(connectMsg));
-    
-    connection.state = CONNECTION_CONNECTING;
-
-    return oSUCCESS;
-}
-
-bool
-FtpDTP::ListenCont(TCPEndpointListenMsg* listenMsg)
-{
-    OSYSDEBUG(("FtpDTP::ListenCont() %x %d - %x %d\n",
-               listenMsg->lAddress,
-               listenMsg->lPort,
-               listenMsg->fAddress,
-               listenMsg->fPort
-               ));
-
-    if (listenMsg->error != TCP_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s %d",
-                  "FtpDTP::ListenCont()",
-                  "FAILED. listenMsg->error", listenMsg->error));
-        Close();
-        return false;
-    }
-
-    connection.state = CONNECTION_CONNECTED;
-
-    switch (method) {
-    case FTP_METHOD_RETR:
-        RetrieveSend();
-        break;
-
-    case FTP_METHOD_STOR:
-        connection.recvSize = 0;
-        Receive();
-        break;
-
-    case FTP_METHOD_LIST:
-        if (!ListSend()) {
-            Close();
-        }
-        break;
-    default:
-        OSYSDEBUG(("not yet\n"));
-        break;
-    }
-
-    return true;
-}
-
-bool
-FtpDTP::ConnectCont(TCPEndpointConnectMsg* connectMsg)
-{
-    OSYSDEBUG(("FtpDTP::ConnectCont()\n"));
-
-    if (connectMsg->error != TCP_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s %d",
-                  "FtpDTP::ConnectCont()",
-                  "FAILED. connectMsg->error", connectMsg->error));
-        Close();
-        return false;
-    }
-
-    connection.state = CONNECTION_CONNECTED;
-
-    switch (method) {
-    case FTP_METHOD_RETR:
-        RetrieveSend();
-        break;
-
-    case FTP_METHOD_STOR:
-        connection.recvSize = 0;
-        Receive();
-        break;
-
-    case FTP_METHOD_LIST:
-        if (!ListSend()) {
-            Close();
-        }
-        break;
-    default:;//CHANGE_ET added default case to avoid unhandled enumeration warnings
-    }
-    return true;
-}
-
-OStatus
-FtpDTP::Send()
-{
-    OSYSDEBUG(("FtpDTP::Send() "));
-
-    if (connection.state != CONNECTION_CONNECTED) return oFAIL;
-
-    OSYSDEBUG(("%d\n", connection.sendSize));
-
-    TCPEndpointSendMsg sendMsg(connection.endpoint,
-                               connection.sendData,
-                               connection.sendSize);
-    sendMsg.continuation = continuation;
-
-    sendMsg.Send(ipstackRef, myOID,
-                 Extra_Entry[entrySendContforDTP],
-                 sizeof(TCPEndpointSendMsg));
-
-    connection.state = CONNECTION_SENDING;
-    connection.sendSize = 0;
-    return oSUCCESS;
-}
-
-bool
-FtpDTP::SendCont(TCPEndpointSendMsg* sendMsg)
-{
-    OSYSDEBUG(("FtpDTP::SendCont()\n"));
-
-    if (sendMsg->error != TCP_SUCCESS) {
-        if (sendMsg->error == TCP_BUFFER_INVALID
-            && method == FTP_METHOD_NOOP) {
-            Close();
-            return true;
-        } else {
-            OSYSLOG1((osyslogERROR, "%s : %s %d",
-                      "FtpDTP::SendCont()",
-                      "FAILED. sendMsg->error", sendMsg->error));
-            Close();
-            return false;
-        }
-    }
-
-    connection.state = CONNECTION_CONNECTED;
-
-    switch (method) {
-    case FTP_METHOD_RETR:
-        if (!RetrieveSend()) {
-            Close();
-            return true;
-        }
-        break;
-
-    case FTP_METHOD_LIST:
-        if (!ListSend()) {
-            Close();
-            return true;
-        }
-        break;
-
-    default :
-        Close();
-        return true;
-    }
-    return false;
-}
-
-OStatus
-FtpDTP::Receive()
-{
-
-    if (connection.state != CONNECTION_CONNECTED
-        && connection.state != CONNECTION_SENDING) return oFAIL;
-
-    OSYSDEBUG(("FtpDTP::Receive()\n"));
-
-    TCPEndpointReceiveMsg receiveMsg(connection.endpoint,
-                                     connection.recvData,
-                                     1, FTP_BUFFER_SIZE);
-    receiveMsg.continuation = continuation;
-
-    receiveMsg.Send(ipstackRef, myOID,
-                    Extra_Entry[entryReceiveContforDTP], sizeof(receiveMsg));
-
-    connection.state = CONNECTION_RECEIVING;
-    return oSUCCESS;
-}
-
-bool
-FtpDTP::ReceiveCont(TCPEndpointReceiveMsg* receiveMsg)
-{
-    OSYSDEBUG(("FtpDTP::ReceiveCont()\n"));
-
-    connection.recvSize = receiveMsg->sizeMin;
-    if (receiveMsg->error == TCP_CONNECTION_CLOSED) {
-        Save(connection.recvData, 0);
-        Close();
-        return true;
-    }
-
-    if (receiveMsg->error != TCP_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s %d",
-                  "FtpDTP::ReceiveCont()",
-                  "FAILED. receiveMsg->error", receiveMsg->error));
-        Close();
-        return false;
-    }
-
-    // receive some more
-    Save(connection.recvData, receiveMsg->sizeMin, false);
-    connection.state = CONNECTION_CONNECTED;
-    connection.recvSize = 0;
-    Receive();
-
-    return false;
-}
-
-OStatus
-FtpDTP::Close()
-{
-    OSYSDEBUG(("FtpDTP::Close() %d\n", connection.state));
-
-    if (connection.state == CONNECTION_CLOSED
-        || connection.state == CONNECTION_CLOSING) return oFAIL;
-
-    TCPEndpointCloseMsg closeMsg(connection.endpoint);
-    closeMsg.continuation = continuation;
-
-    closeMsg.Send(ipstackRef, myOID,
-                  Extra_Entry[entryCloseContforDTP], sizeof(closeMsg));
-
-    connection.state = CONNECTION_CLOSING;
-    ResetFilename();
-    method   = FTP_METHOD_NOOP;
-    dataType = FTP_DATA_A;
-    passive  = false;
-    connectPort = FTP_DATA_PORT;
-
-    return oSUCCESS;
-}
-
-void
-FtpDTP::CloseCont(TCPEndpointCloseMsg* /*closeMsg*/) //CHANGE_ET unused parameter
-{
-    OSYSDEBUG(("FtpDTP::CloseCont()\n"));
-    
-    connection.state = CONNECTION_CLOSED;
-}
-
diff -urdN ../Tekkotsu_2.3/TinyFTPD/FtpDTP.h ./TinyFTPD/FtpDTP.h
--- ../Tekkotsu_2.3/TinyFTPD/FtpDTP.h	Tue Jul  6 18:43:45 2004
+++ ./TinyFTPD/FtpDTP.h	Wed Dec 31 19:00:00 1969
@@ -1,106 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#ifndef _FtpDTP_h_DEFINED
-#define _FtpDTP_h_DEFINED
-
-#include <stdio.h>
-#include <dirent.h>
-#include <EndpointTypes.h>
-#include <TCPEndpointMsg.h>
-#include "TCPConnection.h"
-#include "FtpConfig.h"
-
-#include "entry.h"
-#include "def.h"
-
-class FtpDTP
-{
-public:
-    FtpDTP();
-    virtual ~FtpDTP() {}
-
-    OStatus Initialize(const OID& myoid,
-                       const antStackRef& ipstack, void* index);
-    bool ListenCont (TCPEndpointListenMsg*  listenMsg);
-    bool ConnectCont(TCPEndpointConnectMsg* connectMsg);
-    bool SendCont   (TCPEndpointSendMsg*    sendMsg);
-    bool ReceiveCont(TCPEndpointReceiveMsg* receiveMsg);
-    void CloseCont  (TCPEndpointCloseMsg*   closeMsg);
-
-    OStatus Close  ();
-
-    // Set
-    void SetType(FTPDataType type) {dataType = type;};
-    void SetUser(char *user);
-    void SetHome(char *home);
-
-    // Get
-    ConnectionState GetState() {return connection.state;};
-    FTPDataType GetType() {return dataType;};
-    char * GetFilename() {return ftpFile;};
-    char * GetDirectry() {return ftpDir;};
-    size_t GetFileSize(char *name);
-    char * GetUser() {return ftpUser;};
-
-    // Method
-    Port SetIP   (IPAddress ip);
-    bool SetPort (char* ipport);
-    bool Retrieve(char* filename);
-    bool Store   (char* filename);
-    bool ChangeDir(char* dir);
-    bool MakeDir(char* dir);
-    bool RemoveDir(char* dir);
-    bool Delete(char* filename);
-    bool List    (char* dir);
-    bool RenameFrom(char *file);
-    bool RenameTo(char *file);
-    void ResetFilename();
-
-private:
-    OStatus Listen ();
-    OStatus Connect();
-    OStatus Send   ();
-    OStatus Receive();
-
-    void Save(byte *data, int length, bool end = true);
-    void DirNorm(char *dir);
-    bool RetrieveSend();
-    bool ListSend();
-
-    OID myOID;
-    antStackRef ipstackRef;
-
-    // connection info
-    IPAddress connectIP;
-    Port      connectPort;
-    FTPMethod method;
-    bool passive;
-
-    // File Info
-    FTPDataType dataType;
-    char ftpUser[MAX_STRING_LENGTH];
-    char ftpHome[MAX_STRING_LENGTH];
-    char ftpDir[MAX_STRING_LENGTH];
-    char ftpFile[MAX_STRING_LENGTH];
-    bool listLong;
-    bool total;
-    FILE* fp;
-    DIR*  dirp;
-
-    void* continuation;
-    TCPConnection connection;
-
-		FtpDTP(const FtpDTP&); //CHANGE_ET copy constructor, don't call
-		FtpDTP operator=(const FtpDTP&); //CHANGE_ET assignment operator, don't call
-};
-
-#endif /* _FtpDTP_h_DEFINED */
diff -urdN ../Tekkotsu_2.3/TinyFTPD/FtpMethod.cc ./TinyFTPD/FtpMethod.cc
--- ../Tekkotsu_2.3/TinyFTPD/FtpMethod.cc	Tue Nov 16 18:52:10 2004
+++ ./TinyFTPD/FtpMethod.cc	Wed Dec 31 19:00:00 1969
@@ -1,525 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#include <sys/stat.h>
-#include <sys/unistd.h>
-#include <OPENR/OSyslog.h>
-#include <OPENR/ODebug.h>
-#include <OPENR/OCalendarTime.h>
-#include <stdlib.h>
-#include "FtpDTP.h"
-#include <stdio.h>
-
-Port 
-FtpDTP::SetIP(IPAddress ip)
-{
-    connectIP = ip;
-    connectPort = FTP_PASV_DATA_PORT + (int)continuation;
-    passive = true;
-    Listen();
-    return connectPort;
-}
-
-bool
-FtpDTP::SetPort(char* ipport)
-{
-    longword buf;
-    uint32 ip = 0;
-    uint16 port = 0;
-
-    buf = atoi(ipport);
-    ip |= (buf << 24);
-    while (*ipport++ != ',') {
-        ;
-    }
-    buf = atoi(ipport);
-    ip |= (buf << 16);
-    while (*ipport++ != ',') {
-        ;
-    }
-    buf = atoi(ipport);
-    ip |= (buf << 8);
-    while (*ipport++ != ',') {
-        ;
-    }
-    buf = atoi(ipport);
-    ip |= buf;
-    while (*ipport++ != ',') {
-        ;
-    }
-
-    buf = atoi(ipport);
-    port |= (buf << 8);
-    while (*ipport++ != ',') {
-        ;
-    }
-    buf = atoi(ipport);
-    port |= buf;
-
-    OSYSDEBUG(("FtpDTP::Port():Set IP:%x Port:%d\n", ip, port));
-    connectIP   = (IPAddress)ip;
-    connectPort = (Port)port;
-    passive = false;
-    return true;
-}
-
-bool
-FtpDTP::Store(char* filename)
-{
-    char file[MAX_STRING_LENGTH * 2];
-    method = FTP_METHOD_STOR;
-
-    if (filename[0] == '/') {
-        sprintf(file, "%s", filename);
-    } else {
-        sprintf(file, "%s%s", ftpDir, filename);
-    }
-
-    DirNorm(file);
-
-    if (!strncmp(file, ftpHome, strlen(ftpHome))) {
-        if((fp = fopen(file, "wb")) == NULL) {
-            OSYSLOG1((osyslogERROR, "Ftpd::File Open Failed %s. errno=%d", file,errno));
-            return false;
-        }
-    } else {
-        return false;
-    }
-
-    strncpy(ftpFile, filename, MAX_STRING_LENGTH);
-
-    if (passive) {
-        if (connection.state == CONNECTION_CONNECTED) {
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else {
-        Connect();
-    }
-    return true;
-}
-
-bool
-FtpDTP::Retrieve(char* filename)
-{
-    char file[MAX_STRING_LENGTH * 2];
-    method = FTP_METHOD_RETR;
-
-    if (filename[0] == '/') {
-        sprintf(file, "%s", filename);
-    } else {
-        sprintf(file, "%s%s", ftpDir, filename);
-    }
-
-    DirNorm(file);
-
-    if (!strncmp(file, ftpHome, strlen(ftpHome))) {
-        if((fp = fopen(file, "rb")) == NULL) {
-            OSYSLOG1((osyslogERROR, "FtpDTP::File Open Failed %s.", file));
-            return false;
-        }
-    } else {
-        return false;
-    }
-
-    strncpy(ftpFile, filename, MAX_STRING_LENGTH);
-
-    if (passive) {
-        if (connection.state == CONNECTION_CONNECTED) {
-            RetrieveSend();
-        }
-    } else {
-        Connect();
-    }
-    return true;
-}
-
-bool
-FtpDTP::RetrieveSend()
-{
-    if (dataType == FTP_DATA_A) {
-       connection.recvSize
-           = fread(connection.recvData, 1, FTP_BUFFER_SIZE / 2, fp);
-       if (FTP_BUFFER_SIZE / 2 > connection.recvSize) {
-            byte *cur_r = connection.recvData;
-            byte *cur_s = connection.sendData;
-            connection.sendSize = connection.recvSize;
-            for (int i = 0; i < connection.recvSize; i++, cur_r++) {
-                if (*cur_r == LF) {
-                    if ((cur_r != connection.recvData)
-                        && (*(cur_r - 1) != CR)) {
-                        *cur_s++ = CR;
-                        connection.sendSize++;
-                    }
-                    *cur_s++ = *cur_r;
-                } else {
-                    *cur_s++ = *cur_r;
-                }
-            }
-            fclose(fp);
-            method = FTP_METHOD_NOOP;
-            Send();
-        } else {
-            byte *cur_r = connection.recvData;
-            byte *cur_s = connection.sendData;
-            connection.sendSize = connection.recvSize;
-            for (int i = 0; i < connection.recvSize; i++, cur_r++) {
-                if (*cur_r == LF) {
-                    if ((cur_r != connection.recvData)
-                        && (*(cur_r - 1) != CR)) {
-                        *cur_s++ = CR;
-                        connection.sendSize++;
-                    }
-                    *cur_s++ = *cur_r;
-                } else {
-                    *cur_s++ = *cur_r;
-                }
-            }
-            Send();
-        }
-    } else {
-        connection.sendSize
-            = fread(connection.sendData, 1, FTP_BUFFER_SIZE, fp);
-        if (FTP_BUFFER_SIZE > connection.sendSize) {
-            fclose(fp);
-            method = FTP_METHOD_NOOP;
-            Send();
-        } else {
-            Send();
-        }
-    }
-    return true;
-}
-
-bool
-FtpDTP::RenameFrom(char *file)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-
-    if (file[0] == '/') {
-        sprintf(tmp, "%s", file);
-    } else {
-        sprintf(tmp, "%s%s", ftpDir, file);
-    }
-
-    DirNorm(tmp);
-
-    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
-			FILE *tfp = fopen(tmp, "r"); //CHANGE_ET rename fp to tfp to avoid shadowed variable
-        if (tfp != NULL) {
-            strncpy(ftpFile, tmp, MAX_STRING_LENGTH);
-            fclose(tfp);
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool
-FtpDTP::RenameTo(char *file)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-
-    if (file[0] == '/') {
-        sprintf(tmp, "%s", file);
-    } else {
-        sprintf(tmp, "%s%s", ftpDir, file);
-    }
-
-    DirNorm(tmp);
-
-    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
-        int ret = rename(ftpFile, tmp);
-        if (ret == 0) {
-            strcpy(ftpFile, "");
-            return true;
-        }
-    }
-
-    strcpy(ftpFile, "");
-    return false;
-}
-
-bool
-FtpDTP::List(char* dir)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-    total = true;
-
-    if ((dir[0] != '\0') && (dir[0] == '/')) {
-        sprintf(tmp, "%s/", dir);
-        listLong = false;
-    } else if ((dir[0] != '\0') && (dir[0] == '-')) {
-        sprintf(tmp, "%s", ftpDir);
-        listLong = true;
-    } else {
-        sprintf(tmp, "%s%s", ftpDir, dir);
-        listLong = false;
-    }
-
-    listLong = true;
-
-    DirNorm(tmp);
-
-    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
-			if ((dirp = opendir(tmp))) { //CHANGE_ET extra parenthesis to clarify assignment used as truth value
-            method = FTP_METHOD_LIST;
-            strcpy(ftpFile, tmp);
-            if (passive) {
-                if (connection.state == CONNECTION_CONNECTED) {
-                    if (!ListSend()) {
-                        Close();
-                    }
-                }
-            } else {
-                Connect();
-            }
-            return true;
-        }
-    }
-    return false;
-}
-
-bool
-FtpDTP::ListSend()
-{
-    dirent *entry;
-    char tmp[MAX_STRING_LENGTH];
-
-    if (total) {
-        sprintf((char *)connection.sendData,
-                "total %d\r\n", 0);
-        connection.sendSize = strlen((char *)connection.sendData);
-        Send();
-        total = false;
-        return true;
-    }
-
-    entry = readdir(dirp);
-    if (entry) {
-        struct stat statbuf;
-        sprintf(tmp, "%s/%s", ftpFile, entry->d_name);
-        DirNorm(tmp);
-        
-        stat(tmp, &statbuf); //CHANGE_ET unused variable 'ret'
-        if (listLong) {
-            sprintf((char *)connection.sendData,
-                    "%c%c%c%c%c%c%c%c%c%c %x %s %s %-d %s %d %d %s\r\n",
-                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'd' : '-',
-                    (statbuf.st_mode & S_IRUSR) ? 'r' : '-',
-                    (statbuf.st_mode & S_IWUSR) ? 'w' : '-',
-                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'x' : '-',
-                    (statbuf.st_mode & S_IRUSR) ? 'r' : '-',
-                    (statbuf.st_mode & S_IWUSR) ? 'w' : '-',
-                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'x' : '-',
-                    (statbuf.st_mode & S_IRUSR) ? 'r' : '-',
-                    (statbuf.st_mode & S_IWUSR) ? 'w' : '-',
-                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'x' : '-',
-                    0,
-                    "AIBO",
-                    "AIBO",
-                    statbuf.st_size,
-                    "May",
-                    11,
-                    1999,
-                    entry->d_name
-                );
-        } else {
-            if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
-                sprintf((char *)connection.sendData,
-                        "%s/\r\n",
-                        entry->d_name);
-            } else {
-                sprintf((char *)connection.sendData,
-                        "%s\r\n",
-                        entry->d_name);
-            }
-        }
-        connection.sendSize = strlen((char *)connection.sendData);
-        Send();
-    } else {
-        method = FTP_METHOD_NOOP;
-        closedir(dirp);
-        return false;
-    }
-
-    return true;
-}
-
-bool
-FtpDTP::ChangeDir(char* dir)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-
-    if (dir[0] == '/') {
-        sprintf(tmp, "%s/", dir);
-    } else {
-        sprintf(tmp, "%s%s/", ftpDir, dir);
-    }
-
-    DirNorm(tmp);
-
-    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
-        DIR* tmpdirp;
-        if ((tmpdirp = opendir(tmp))) { //CHANGE_ET extra parenthesis to clarify assignment used as truth value
-            closedir(tmpdirp);
-            strcpy(ftpDir, tmp);
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool
-FtpDTP::MakeDir(char* dir)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-
-    if (dir[0] == '/') {
-        sprintf(tmp, "%s", dir);
-    } else {
-        sprintf(tmp, "%s%s", ftpDir, dir);
-    }
-
-    DirNorm(tmp);
-
-    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
-        if (!mkdir(tmp, 0777)) {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool
-FtpDTP::RemoveDir(char* dir)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-
-    if (dir[0] == '/') {
-        sprintf(tmp, "%s", dir);
-    } else {
-        sprintf(tmp, "%s%s", ftpDir, dir);
-    }
-
-    DirNorm(tmp);
-
-    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
-        if (!rmdir(tmp)) {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool
-FtpDTP::Delete(char* filename)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-
-    if (filename[0] == '/') {
-        sprintf(tmp, "%s", filename);
-    } else {
-        sprintf(tmp, "%s%s", ftpDir, filename);
-    }
-
-    DirNorm(tmp);
-
-    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
-        if (!remove(tmp)) {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-void
-FtpDTP::Save(byte *data, int length, bool end)
-{
-    OSYSDEBUG(("FtpDTP::Save %d %d\n", length, end));
-    if (length) fwrite(data, length, 1, fp);
-    if (end) {
-        fclose(fp);
-        strcpy(ftpFile, "");
-    }
-}
-
-size_t
-FtpDTP::GetFileSize(char *name)
-{
-    struct stat statbuf;
-    int ret = stat(name, &statbuf);
-    if (ret == 0) {
-        return statbuf.st_size;
-    } else {
-        return 0;
-    }
-}
-
-void
-FtpDTP::ResetFilename()
-{
-    strcpy(ftpFile, "");
-}
-
-void
-FtpDTP::SetUser(char *user)
-{
-    strncpy(ftpUser, user, MAX_STRING_LENGTH);
-}
-
-void
-FtpDTP::SetHome(char *home)
-{
-    sprintf(ftpHome, "%s/", home);
-
-    DirNorm(ftpHome);
-    strcpy(ftpDir, ftpHome);
-}
-
-void
-FtpDTP::DirNorm(char *dir)
-{
-    char tmp[MAX_STRING_LENGTH * 2];
-    int length = strlen(dir);
-    int cur = 0;
-
-    for (int i = 0; i < length + 1; i++) {
-        OSYSDEBUG(("DirNorm %c\n", dir[i]));
-        if (dir[i] == '.') {
-            if ((dir[i + 1] == '.') && (dir[i + 2] == '/')) {
-                cur -= 2;
-                while(tmp[cur] != '/') {
-                    cur--;
-                }
-                cur++;
-            } else if (dir[i + 1] == '/') {
-                i++;
-            } else {
-                tmp[cur++] = toupper(dir[i]);
-            }
-        } else if (dir[i] == '/') {
-            if ((cur == 0) || ((cur != 0) && (tmp[cur - 1] != '/'))) {
-                tmp[cur++] = toupper(dir[i]);
-            }
-        } else {
-            tmp[cur++] = toupper(dir[i]);
-        }
-    }
-        
-    strncpy(dir, tmp, MAX_STRING_LENGTH);
-    dir[MAX_STRING_LENGTH] = '0';
-}
diff -urdN ../Tekkotsu_2.3/TinyFTPD/FtpPI.cc ./TinyFTPD/FtpPI.cc
--- ../Tekkotsu_2.3/TinyFTPD/FtpPI.cc	Tue Jul  6 18:43:45 2004
+++ ./TinyFTPD/FtpPI.cc	Wed Dec 31 19:00:00 1969
@@ -1,346 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#include <stdarg.h>
-#include <OPENR/OSyslog.h>
-#include <EndpointTypes.h>
-#include <TCPEndpointMsg.h>
-#include "FtpPI.h"
-
-FtpPI::FtpPI()
-{
-}
-
-OStatus
-FtpPI::Initialize(const OID& myoid, const antStackRef& ipstack,
-                  void* index, OList<Passwd, MAX_LOGIN> *pass)
-{
-    OSYSDEBUG(("FtpPI::Initialize()\n"));
-
-    myOID        = myoid;
-    ipstackRef   = ipstack;
-    continuation = index;
-    passwd       = pass;
- 
-    state = FTP_NOT_LOGIN;
-    connection.state = CONNECTION_CLOSED;
-
-    // 
-    // Allocate send buffer
-    //
-    antEnvCreateSharedBufferMsg sendBufferMsg(FTP_BUFFER_SIZE);
-
-    sendBufferMsg.Call(ipstackRef, sizeof(sendBufferMsg));
-    if (sendBufferMsg.error != ANT_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
-                  "FtpPI::Initialize()",
-                  "Can't allocate send buffer",
-                  index, sendBufferMsg.error));
-        return oFAIL;
-    }
-
-    connection.sendBuffer = sendBufferMsg.buffer;
-    connection.sendBuffer.Map();
-    connection.sendData = (byte*)(connection.sendBuffer.GetAddress());
-
-    //
-    // Allocate receive buffer
-    //
-    antEnvCreateSharedBufferMsg recvBufferMsg(FTP_BUFFER_SIZE);
-
-    recvBufferMsg.Call(ipstackRef, sizeof(recvBufferMsg));
-    if (recvBufferMsg.error != ANT_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
-                  "FtpPI::Initialize()",
-                  "Can't allocate receive buffer",
-                  index, recvBufferMsg.error));
-        return oFAIL;
-    }
-
-    connection.recvBuffer = recvBufferMsg.buffer;
-    connection.recvBuffer.Map();
-    connection.recvData = (byte*)(connection.recvBuffer.GetAddress());
-    
-    ftpDTP.Initialize(myOID, ipstackRef, index);
-    Listen();
-
-    return oSUCCESS;
-}
-
-OStatus
-FtpPI::Listen()
-{
-    OSYSDEBUG(("FtpPI::Listen()\n"));
-
-    if (connection.state != CONNECTION_CLOSED) return oFAIL;
-
-    //
-    // Create endpoint
-    //
-    antEnvCreateEndpointMsg tcpCreateMsg(EndpointType_TCP,
-                                         FTP_BUFFER_SIZE * 2);
-
-    tcpCreateMsg.Call(ipstackRef, sizeof(tcpCreateMsg));
-    if (tcpCreateMsg.error != ANT_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
-                  "FtpPI::Listen()",
-                  "Can't create endpoint",
-                  (int)continuation, tcpCreateMsg.error));
-        return oFAIL;
-    }
-    connection.endpoint = tcpCreateMsg.moduleRef;
-
-    //
-    // Listen
-    //
-    TCPEndpointListenMsg listenMsg(connection.endpoint,
-                                   IP_ADDR_ANY, FTP_LISTEN_PORT);
-    listenMsg.continuation = continuation;
-
-    listenMsg.Send(ipstackRef, myOID,
-                   Extra_Entry[entryListenContforPI], sizeof(listenMsg));
-    
-    connection.state = CONNECTION_LISTENING;
-
-    return oSUCCESS;
-}
-
-void
-FtpPI::ListenCont(TCPEndpointListenMsg* listenMsg)
-{
-    OSYSDEBUG(("FtpPI::ListenCont() %x %d - %x %d\n",
-               listenMsg->lAddress,
-               listenMsg->lPort,
-               listenMsg->fAddress,
-               listenMsg->fPort));
-
-    if (listenMsg->error != TCP_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s %d",
-                  "FtpPI::ListenCont()",
-                  "FAILED. listenMsg->error", listenMsg->error));
-        Close();
-        return;
-    }
-
-    ipaddr = listenMsg->lAddress;
-
-    connection.state = CONNECTION_CONNECTED;
-    Send(FTP_REPLY_SERVICE_READY, "AIBO FTP Server ready");
-    connection.recvSize = 0;
-    Receive();
-}
-
-OStatus
-FtpPI::Send(FTPReplyCode code, char *format, ...)
-{
-    OSYSDEBUG(("FtpPI::Send()\n"));
-    
-    if (connection.state != CONNECTION_CONNECTED) return oFAIL;
-
-    char buf[MAX_STRING_LENGTH];
-    va_list ap;
-    va_start(ap, format);
-    vsprintf(buf, format, ap);
-    va_end(ap);
-
-    sprintf((char *)connection.sendData, "%03d %s\r\n", code, buf);
-
-    TCPEndpointSendMsg sendMsg(connection.endpoint,
-                               connection.sendData,
-                               strlen((char *)connection.sendData));
-    sendMsg.continuation = continuation;
-
-    sendMsg.Send(ipstackRef, myOID,
-                 Extra_Entry[entrySendContforPI], sizeof(sendMsg));
-
-    connection.state = CONNECTION_SENDING;
-    connection.sendSize = 0;
-    return oSUCCESS;
-}
-
-void
-FtpPI::SendCont(TCPEndpointSendMsg* sendMsg)
-{
-    OSYSDEBUG(("FtpPI::SendCont()\n"));
-
-    if (sendMsg->error != TCP_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s %d",
-                  "FtpPI::SendCont()",
-                  "FAILED. sendMsg->error", sendMsg->error));
-        Close();
-        return;
-    }
-
-    connection.state = CONNECTION_CONNECTED;
-}
-
-OStatus
-FtpPI::Receive()
-{
-    OSYSDEBUG(("FtpPI::Receive()\n"));
-
-    if (connection.state != CONNECTION_CONNECTED
-        && connection.state != CONNECTION_SENDING) return oFAIL;
-
-    TCPEndpointReceiveMsg receiveMsg(connection.endpoint,
-                                     connection.recvData,
-                                     1,
-                                     FTP_BUFFER_SIZE);
-    receiveMsg.continuation = continuation;
-    receiveMsg.Send(ipstackRef, myOID,
-                    Extra_Entry[entryReceiveContforPI], sizeof(receiveMsg));
-    return oSUCCESS;
-}
-
-void
-FtpPI::ReceiveCont(TCPEndpointReceiveMsg* receiveMsg)
-{
-    bool doReceive = false;
-
-    if (receiveMsg->error == TCP_CONNECTION_CLOSED) {
-        Close();
-        return;
-    }
-
-    if (receiveMsg->error != TCP_SUCCESS) {
-        OSYSLOG1((osyslogERROR, "%s : %s %d",
-                  "FtpPI::ReceiveCont()",
-                  "FAILED. receiveMsg->error", receiveMsg->error));
-        Close();
-        return;
-    }
-
-    connection.recvSize += receiveMsg->sizeMin;
-    
-    if (RequestComplete()) {
-        RequestProcess();
-    } else {
-        OSYSDEBUG(("FtpPI::Request not complete\n"));
-        doReceive = true;
-    }
-    
-    // receive some more
-    if (doReceive) {
-        if (connection.recvSize < FTP_BUFFER_SIZE) {
-            Receive();
-        } else {
-            Close();
-        }
-    }
-}
-
-OStatus
-FtpPI::Close()
-{
-    OSYSDEBUG(("FtpPI::Close()\n"));
-
-    if (connection.state == CONNECTION_CLOSED
-        || connection.state == CONNECTION_CLOSING) return oFAIL;
-
-    TCPEndpointCloseMsg closeMsg(connection.endpoint);
-    closeMsg.continuation = continuation;
-
-    closeMsg.Send(ipstackRef, myOID,
-                  Extra_Entry[entryCloseContforPI], sizeof(closeMsg));
-
-    connection.state = CONNECTION_CLOSING;
-    ftpDTP.Close();
-
-    return oSUCCESS;
-}
-
-void
-FtpPI::CloseCont(TCPEndpointCloseMsg* /*closeMsg*/) //CHANGE_ET unused variable
-{
-    OSYSDEBUG(("FtpPI::CloseCont()\n"));
-    
-    connection.state = CONNECTION_CLOSED;
-    Listen();
-}
-
-void
-FtpPI::ListenContforDTP(TCPEndpointListenMsg* listenMsg)
-{
-    if (listenMsg->error == TCP_SUCCESS) {
-        switch(ftpDTP.GetType()) {
-        case FTP_DATA_I:
-            Send(FTP_REPLY_OPEN_CONNECTION,
-                 "Binary data connection for %s.",
-                 ftpDTP.GetFilename());
-            break;
-
-        case FTP_DATA_A:
-            Send(FTP_REPLY_OPEN_CONNECTION,
-                 "ASCII data connection for %s.",
-                 ftpDTP.GetFilename());
-            break;
-        }
-    }
-    ftpDTP.ListenCont(listenMsg);
-    return;
-}
-
-void
-FtpPI::ConnectContforDTP(TCPEndpointConnectMsg* connectMsg)
-{
-    if (connectMsg->error == TCP_SUCCESS) {
-        switch(ftpDTP.GetType()) {
-        case FTP_DATA_I:
-            Send(FTP_REPLY_OPEN_CONNECTION,
-                 "Binary data connection for %s.",
-                 ftpDTP.GetFilename());
-            break;
-
-        case FTP_DATA_A:
-            Send(FTP_REPLY_OPEN_CONNECTION,
-                 "ASCII data connection for %s.",
-                 ftpDTP.GetFilename());
-            break;
-        }
-    }
-
-    ftpDTP.ConnectCont(connectMsg);
-    return;
-}
-
-void
-FtpPI::SendContforDTP(TCPEndpointSendMsg* sendMsg)
-{
-    if(ftpDTP.SendCont(sendMsg)) {
-        Send(FTP_REPLY_CLOSE_DATA, "Transfer complete.");
-        connection.recvSize = 0;
-        Receive();
-    } else if (ftpDTP.GetState() != CONNECTION_SENDING) {
-        Send(FTP_REPLY_TRANSFER_ABORT, "Transfer abort.");
-        connection.recvSize = 0;
-        Receive();
-    }
-}
-
-void
-FtpPI::ReceiveContforDTP(TCPEndpointReceiveMsg* receiveMsg)
-{
-    if (ftpDTP.ReceiveCont(receiveMsg)) {
-        Send(FTP_REPLY_CLOSE_DATA, "Transfer complete.");
-        connection.recvSize = 0;
-        Receive();
-    } else if (ftpDTP.GetState() != CONNECTION_RECEIVING) {
-        Send(FTP_REPLY_TRANSFER_ABORT, "Transfer abort.");
-        connection.recvSize = 0;
-        Receive();
-    }
-}
-
-void
-FtpPI::CloseContforDTP(TCPEndpointCloseMsg* closeMsg)
-{
-    ftpDTP.CloseCont(closeMsg);
-}
diff -urdN ../Tekkotsu_2.3/TinyFTPD/FtpPI.h ./TinyFTPD/FtpPI.h
--- ../Tekkotsu_2.3/TinyFTPD/FtpPI.h	Tue Jul  6 18:43:45 2004
+++ ./TinyFTPD/FtpPI.h	Wed Dec 31 19:00:00 1969
@@ -1,67 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#ifndef _FtpPI_h_DEFINED
-#define _FtpPI_h_DEFINED
-
-#include <OPENR/OList.h>
-#include "TCPConnection.h"
-#include "FtpConfig.h"
-#include "FtpDTP.h"
-#include "def.h"
-#include "entry.h"
-
-class FtpPI
-{
-public:
-    FtpPI();
-    virtual ~FtpPI() {}
-
-    OStatus Initialize(const OID& myoid, const antStackRef& ipstack,
-                       void* index, OList<Passwd, MAX_LOGIN> *pass);
-
-    void ListenCont  (TCPEndpointListenMsg*  listenMsg);
-    void SendCont    (TCPEndpointSendMsg*    sendMsg);
-    void ReceiveCont (TCPEndpointReceiveMsg* receiveMsg);
-    void CloseCont   (TCPEndpointCloseMsg*   closeMsg);
-
-    void ListenContforDTP (TCPEndpointListenMsg*  listenMsg);
-    void ConnectContforDTP(TCPEndpointConnectMsg* connectMsg);
-    void SendContforDTP   (TCPEndpointSendMsg*    sendMsg);
-    void ReceiveContforDTP(TCPEndpointReceiveMsg* receiveMsg);
-    void CloseContforDTP  (TCPEndpointCloseMsg*   closeMsg);
-
-    OStatus Close  ();
-
-private:
-    OStatus Listen ();
-    OStatus Send   (FTPReplyCode, char *format, ...);
-    OStatus Receive();
-
-    bool RequestComplete();
-    bool RequestProcess ();
-    bool CommandParser  (char **cmd, char **param);
-
-    OID myOID;
-    antStackRef ipstackRef;
-    void* continuation;
-    TCPConnection connection;
-    FTPLoginState state;
-    FtpDTP ftpDTP;
-    IPAddress ipaddr;
-
-    OList<Passwd, MAX_LOGIN> *passwd;
-
-		FtpPI(const FtpPI&); //CHANGE_ET copy constructor, don't call
-		FtpPI operator=(const FtpPI&); //CHANGE_ET assignment operator, don't call
-};
-#endif /* _FtpPI_h_DEFINED */
-
diff -urdN ../Tekkotsu_2.3/TinyFTPD/FtpRequest.cc ./TinyFTPD/FtpRequest.cc
--- ../Tekkotsu_2.3/TinyFTPD/FtpRequest.cc	Tue Jul  6 18:30:57 2004
+++ ./TinyFTPD/FtpRequest.cc	Wed Dec 31 19:00:00 1969
@@ -1,427 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#include <OPENR/OPENRAPI.h>
-#include <OPENR/OSyslog.h>
-#include "FtpPI.h"
-
-bool
-FtpPI::RequestComplete()
-{
-    char* c = (char*)connection.recvData;
-
-    for (int i = 0; i < connection.recvSize - 1; i++) {
-        if ((c[i] == CR) && (c[i + 1] == LF)) {
-            c[i] = '\0';
-            return true;
-        }
-    }
-    
-    return false;
-}
-
-bool
-FtpPI::CommandParser(char **cmd, char **param)
-{
-    char *cur = (char *)connection.recvData;
-    *cmd = cur;
-
-    while (isalpha(*cur)) {
-        *cur = toupper(*cur);
-        cur++;
-    }
-
-    while (*cur == SP) {
-        *cur = '\0';
-        cur++;
-    }
-
-    *param = cur;
-    return true;
-}
-
-bool
-FtpPI::RequestProcess()
-{
-    //
-    // process all lines
-    //
-    char *cmd;
-    char *param;
-    CommandParser(&cmd, &param);
-    if (strlen(cmd) >= MAX_STRING_LENGTH) {
-        cmd[MAX_STRING_LENGTH - 1] = '\0';
-    }
-
-    if (strlen(param) >= MAX_STRING_LENGTH) {
-        param[MAX_STRING_LENGTH - 1] = '\0';
-    }
-
-    OSYSDEBUG(("FtpPI::RequestProcess() cmd %s : %s\n", cmd, param));
-
-    // process command
-    if (!strcmp(cmd, "USER")) {
-        state = FTP_LOGIN;
-        ftpDTP.SetUser(param);
-        Send(FTP_REPLY_NEED_PASSWD, "Password required for %s.", param);
-        connection.recvSize = 0;
-        Receive();
-    } else if (!strcmp(cmd, "PASS")) {
-        if (state == FTP_LOGIN) {
-            OList<Passwd, MAX_LOGIN>::Iterator iter = passwd->Begin();
-            OList<Passwd, MAX_LOGIN>::Iterator last = passwd->End();
-            while (iter != last) {
-                if (!strcmp((*iter).user, ftpDTP.GetUser())) {
-                    if (!strcmp((*iter).pass, param) ||
-                        !strcmp((*iter).pass, "*")) {
-                        ftpDTP.SetHome((*iter).home);
-                        state = FTP_GET_REQUEST;
-                        Send(FTP_REPLY_USER_LOGIN, "User %s logged in.",
-                             (*iter).user);
-                        connection.recvSize = 0;
-                        Receive();
-                    } else {
-                        state = FTP_NOT_LOGIN;
-                        Send(FTP_REPLY_NOT_LOGIN, "Login incorrect.");
-                        connection.recvSize = 0;
-                        Receive();
-                    }
-                    break;
-                }
-                ++iter;
-            }
-
-            if (iter == last) {
-                state = FTP_NOT_LOGIN;
-                Send(FTP_REPLY_NOT_LOGIN, "Login incorrect.");
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_BAD_SEQUENCE, "Login with USER first.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "TYPE")) {
-        switch(*param) {
-        case 'I':
-            ftpDTP.SetType(FTP_DATA_I);
-            Send(FTP_REPLY_COMMAND_OK, "TYPE set to %s.", param);
-            break;
-
-        case 'A':
-            ftpDTP.SetType(FTP_DATA_A);
-            Send(FTP_REPLY_COMMAND_OK, "TYPE set to %s.", param);
-            break;
-
-        default:
-            Send(FTP_REPLY_NOT_IMPLEMENT, "TYPE set to %s.", param);
-            break;
-        }
-        connection.recvSize = 0;
-        Receive();
-    } else if (!strcmp(cmd, "PORT")) {
-        if (state == FTP_GET_REQUEST) {
-            if (ftpDTP.SetPort(param)) {
-                Send(FTP_REPLY_COMMAND_OK, "PORT command successful.");
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "PASV")) {
-        if (state == FTP_GET_REQUEST) {
-            Port port = ftpDTP.SetIP(ipaddr);
-            if (port){
-                Send(FTP_REPLY_ENTER_PASSIVE,
-                     "Entering Passive Mode. %d,%d,%d,%d,%d,%d",
-                     (ipaddr.Address() & 0xff000000) >> 24,
-                     (ipaddr.Address() & 0x00ff0000) >> 16,
-                     (ipaddr.Address() & 0x0000ff00) >>  8,
-                     (ipaddr.Address() & 0x000000ff),
-                     (port & 0xff00) >>  8,
-                     (port & 0x00ff));
-                connection.recvSize = 0;
-                Receive();
-            }else {
-                Send(FTP_REPLY_NOT_AVAILABLE, "Passive Mode Fail.");
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "RETR")) {
-        if (state == FTP_GET_REQUEST) {
-            if (!ftpDTP.Retrieve(param)) {
-                Send(FTP_REPLY_NO_FILE, "No such file.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                return true;
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "STOR")) {
-        if (state == FTP_GET_REQUEST) {
-            if (!ftpDTP.Store(param)) {
-                Send(FTP_REPLY_NOT_TOKEN, "error.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                return true;
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "RNFR")) {
-        if (state == FTP_GET_REQUEST) {
-            if (ftpDTP.RenameFrom(param)) {
-                Send(FTP_REPLY_REQUESTED_FILE,
-                     "File exists, ready for destination name");
-                connection.recvSize = 0;
-                Receive();
-                return true;
-            } else {
-                Send(FTP_REPLY_NO_FILE, "%s : No such file or directory",
-                     param);
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "RNTO")) {
-        if (state == FTP_GET_REQUEST) {
-            char *tmp = ftpDTP.GetFilename();
-            if (*tmp) {
-                if (ftpDTP.RenameTo(param)) {
-                    Send(FTP_REPLY_FILE_ACTION_OK, "RNTO command successful.");
-                    connection.recvSize = 0;
-                    Receive();
-                } else {
-                    Send(FTP_REPLY_NO_FILE, "%s : No such file or directory",
-                         param);
-                    connection.recvSize = 0;
-                    Receive();
-                }
-            } else {
-                Send(FTP_REPLY_BAD_SEQUENCE, "Bad sequence of commands.");
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "LIST")) {
-        if (state == FTP_GET_REQUEST) {
-            if (!ftpDTP.List(param)) {
-                Send(FTP_REPLY_NOT_TAKEN, "Not taken.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                return true;
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "NLST")) {
-        if (state == FTP_GET_REQUEST) {
-            if (!ftpDTP.List(param)) {
-                Send(FTP_REPLY_NOT_TAKEN, "Not taken.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                return true;
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "CWD")) {
-        if (state == FTP_GET_REQUEST) {
-            if (ftpDTP.ChangeDir(param)) {
-                Send(FTP_REPLY_FILE_ACTION_OK, "CWD command successful.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                Send(FTP_REPLY_NO_FILE, "%s: No such file or directory.",
-                     param);
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "CDUP")) {
-        if (state == FTP_GET_REQUEST) {
-            if (ftpDTP.ChangeDir("../")) {
-                Send(FTP_REPLY_FILE_ACTION_OK, "CWD command successful.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                Send(FTP_REPLY_NO_FILE, "%s: No such file or directory.",
-                     param);
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "PWD")) {
-        if (state == FTP_GET_REQUEST) {
-            Send(FTP_REPLY_PATH_CREATED, "\"%s\" is current directory.",
-                 ftpDTP.GetDirectry());
-            connection.recvSize = 0;
-            Receive();
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "MKD")) {
-        if (state == FTP_GET_REQUEST) {
-             if (ftpDTP.MakeDir(param)) {
-                Send(FTP_REPLY_PATH_CREATED, "MKD command successful.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                Send(FTP_REPLY_NO_FILE, "MKD command Failed.");
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "RMD")) {
-        if (state == FTP_GET_REQUEST) {
-             if (ftpDTP.RemoveDir(param)) {
-                Send(FTP_REPLY_FILE_ACTION_OK, "RMD command successful.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                Send(FTP_REPLY_NO_FILE, "RMD command Failed.");
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "DELE")) {
-        if (state == FTP_GET_REQUEST) {
-            if (ftpDTP.Delete(param)) {
-                Send(FTP_REPLY_FILE_ACTION_OK, "DELE command successful.");
-                connection.recvSize = 0;
-                Receive();
-            } else {
-                Send(FTP_REPLY_NO_FILE, "DELE command Failed.");
-                connection.recvSize = 0;
-                Receive();
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "REBT")) {
-        if (state == FTP_GET_REQUEST) {
-            Send(FTP_REPLY_COMMAND_OK, "REBT command successful.");
-            Close();
-            OBootCondition bootCond(obcbBOOT_TIMER, 0, obcbttRELATIVE);
-            OStatus result = OPENR::Shutdown(bootCond);
-            if (result != oSUCCESS) {
-                OSYSLOG1((osyslogWARNING, "System shutdown... failed" ));
-                return false;
-            }
-        } else {
-            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
-            connection.recvSize = 0;
-            Receive();
-        }
-    } else if (!strcmp(cmd, "SYST")) {
-        sprintf((char *)connection.sendData,
-                "%03d Aperios system type.\r\n",
-                FTP_REPLY_SYSTEM_TYPE);
-        TCPEndpointSendMsg sendMsg(connection.endpoint,
-                                   connection.sendData,
-                                   strlen((char *)connection.sendData));
-            
-        sendMsg.continuation = continuation;
-        sendMsg.Send(ipstackRef,
-                     myOID, Extra_Entry[entrySendContforPI],
-                     sizeof(TCPEndpointSendMsg));
-        connection.recvSize = 0;
-        Receive();
-    } else if (!strcmp(cmd, "HELP")) {
-        sprintf((char *)connection.sendData,
-                "%03d-%s\r\n%s\r\n%s\r\n%s\r\n%s\r\n%s\r\n%03d %s\r\n",
-                FTP_REPLY_HELP_MESSAGE,
-                "The following commands are recognized:",
-                "   USER    PORT    RETR    MSND*   ALLO*   DELE    SITE*   XMKD*   CDUP",
-                "   PASS    PASV    STOR    MSOM*   REST*   CWD     STAT*   RMD     XCUP*",
-                "   ACCT*   TYPE    APPE*   MSAM*   RNFR*   XCWD*   HELP    XRMD*   STOU*",
-                "   REIN*   STRU*   MLFL*   MRSQ*   RNTO*   LIST    NOOP    PWD ",
-                "   QUIT    MODE*   MAIL*   MRCP*   ABOR*   NLST*   MKD     XPWD*   REBT",
-                FTP_REPLY_HELP_MESSAGE,
-                "(*'s => unimplemented)");
-        
-        TCPEndpointSendMsg sendMsg(connection.endpoint,
-                                   connection.sendData,
-                                   strlen((char *)connection.sendData));
-        
-        sendMsg.continuation = continuation;
-        sendMsg.Send(ipstackRef,
-                     myOID, Extra_Entry[entrySendContforPI],
-                     sizeof(TCPEndpointSendMsg));
-        connection.recvSize = 0;
-        Receive();
-    } else if (!strcmp(cmd, "NOOP")) {
-        Send(FTP_REPLY_COMMAND_OK, "NOOP command successful.");
-        Receive();
-    } else if (!strcmp(cmd, "QUIT")) {
-        Send(FTP_REPLY_SERVICE_CLOSE,
-             "Goodbye. Thanks for using the AIBO FTP Server.");
-        Close();
-    } else {
-        Send(FTP_REPLY_UNKNOWN_COMMAND,
-             "'%s %s': command not understood.", cmd, param);
-        connection.recvSize = 0;
-        Receive();
-    }
-
-    ftpDTP.ResetFilename();    
-    return true;
-}
diff -urdN ../Tekkotsu_2.3/TinyFTPD/TCPConnection.h ./TinyFTPD/TCPConnection.h
--- ../Tekkotsu_2.3/TinyFTPD/TCPConnection.h	Mon Sep 30 14:19:49 2002
+++ ./TinyFTPD/TCPConnection.h	Wed Dec 31 19:00:00 1969
@@ -1,42 +0,0 @@
-//
-// Copyright 2002 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#ifndef TCPConnection_h_DEFINED
-#define TCPConnection_h_DEFINED
-
-#include <ant.h>
-
-enum ConnectionState {
-    CONNECTION_CLOSED,
-    CONNECTION_CONNECTING,
-    CONNECTION_CONNECTED,
-    CONNECTION_LISTENING,
-    CONNECTION_SENDING,
-    CONNECTION_RECEIVING,
-    CONNECTION_CLOSING
-};
-
-struct TCPConnection {
-    antModuleRef     endpoint;
-    ConnectionState  state;
-
-    // send buffer
-    antSharedBuffer  sendBuffer;
-    byte*            sendData;
-    int              sendSize;
-    
-    // receive buffer
-    antSharedBuffer  recvBuffer;
-    byte*            recvData;
-    int              recvSize;
-};
-
-#endif // TCPConnection_h_DEFINED
diff -urdN ../Tekkotsu_2.3/TinyFTPD/TinyFTPD.cc ./TinyFTPD/TinyFTPD.cc
--- ../Tekkotsu_2.3/TinyFTPD/TinyFTPD.cc	Tue Jul  6 19:25:45 2004
+++ ./TinyFTPD/TinyFTPD.cc	Wed Dec 31 19:00:00 1969
@@ -1,251 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#include <sys/stat.h>
-#include <OPENR/OSyslog.h>
-#include <EndpointTypes.h>
-#include <TCPEndpointMsg.h>
-#include "TinyFTPD.h"
-
-TinyFTPD::TinyFTPD() : passwd()
-{
-}
-
-OStatus
-TinyFTPD::DoInit(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
-{
-    OSYSDEBUG(("TinyFTPD::DoInit()\n"));
-    return oSUCCESS;
-}
-
-OStatus
-TinyFTPD::DoStart(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
-{
-    OSYSDEBUG(("TinyFTPD::DoStart()\n"));
-
-    ipstackRef = antStackRef("IPStack");
-
-    // Get Passwd
-    OStatus status = LoadPasswd();
-    if (oSUCCESS != status) {
-        OSYSLOG1((osyslogERROR, "TinyFTPD::Load Fail %d", status));
-        return oFAIL;
-    }
-
-    // initialize connection
-    for(int index = 0; index < FTP_CONNECTION_MAX; index++) {
-        ftpPI[index].Initialize(myOID_, ipstackRef, (void*)index, &passwd);
-    }
-
-    return oSUCCESS;
-}
-
-OStatus
-TinyFTPD::DoStop(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
-{
-    OSYSDEBUG(("TinyFTPD::DoStop()\n"));
-    for(int index = 0; index < FTP_CONNECTION_MAX; index++) {
-        ftpPI[index].Close();
-    }
-    return oSUCCESS;
-}
-
-OStatus
-TinyFTPD::DoDestroy(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
-{
-    OSYSDEBUG(("TinyFTPD::DoDestroy()\n"));
-    return oSUCCESS;
-}
-
-void
-TinyFTPD::ListenContforPI(ANTENVMSG msg)
-{
-    TCPEndpointListenMsg* listenMsg
-        = (TCPEndpointListenMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(listenMsg->continuation);
-
-    ftpPI[index].ListenCont(listenMsg);
-}
-
-void
-TinyFTPD::SendContforPI(ANTENVMSG msg)
-{
-    TCPEndpointSendMsg* sendMsg = (TCPEndpointSendMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(sendMsg->continuation);
-
-    ftpPI[index].SendCont(sendMsg);
-}
-
-void
-TinyFTPD::ReceiveContforPI(ANTENVMSG msg)
-{
-    TCPEndpointReceiveMsg* receiveMsg
-        = (TCPEndpointReceiveMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(receiveMsg->continuation);
-
-    ftpPI[index].ReceiveCont(receiveMsg);
-}
-
-void
-TinyFTPD::CloseContforPI(ANTENVMSG msg)
-{
-    TCPEndpointCloseMsg* closeMsg
-        = (TCPEndpointCloseMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(closeMsg->continuation);
-   
-    ftpPI[index].CloseCont(closeMsg);
-}
-
-void
-TinyFTPD::ListenContforDTP(ANTENVMSG msg)
-{
-    TCPEndpointListenMsg* listenMsg
-        = (TCPEndpointListenMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(listenMsg->continuation);
-
-    ftpPI[index].ListenContforDTP(listenMsg);
-}
-
-void
-TinyFTPD::ConnectContforDTP(ANTENVMSG msg)
-{
-    TCPEndpointConnectMsg* connectMsg
-        = (TCPEndpointConnectMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(connectMsg->continuation);
-
-    ftpPI[index].ConnectContforDTP(connectMsg);
-}
-
-void
-TinyFTPD::SendContforDTP(ANTENVMSG msg)
-{
-    TCPEndpointSendMsg* sendMsg
-        = (TCPEndpointSendMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(sendMsg->continuation);
-
-    ftpPI[index].SendContforDTP(sendMsg);
-}
-
-void
-TinyFTPD::ReceiveContforDTP(ANTENVMSG msg)
-{
-    TCPEndpointReceiveMsg* receiveMsg
-        = (TCPEndpointReceiveMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(receiveMsg->continuation);
-
-    ftpPI[index].ReceiveContforDTP(receiveMsg);
-}
-
-void
-TinyFTPD::CloseContforDTP(ANTENVMSG msg)
-{
-    TCPEndpointCloseMsg* closeMsg
-        = (TCPEndpointCloseMsg*)antEnvMsg::Receive(msg);
-    int index = (int)(closeMsg->continuation);
-
-    ftpPI[index].CloseContforDTP(closeMsg);
-}
-
-OStatus
-TinyFTPD::LoadPasswd()
-{
-    OSYSDEBUG(("TinyFTPD::LoadPasswd()\n"));
-
-    size_t bufsize;
-    char* buf;
-
-    OStatus result = Load(FTP_PASSWD_PATH, (byte**)&buf, &bufsize);
-    if (result != oSUCCESS) {
-        return result;
-    }
-
-    char* end = buf + bufsize;
-    char* cur = buf;
-    char* head = buf;
-    Passwd pass;
-
-    while (cur < end) {
-        if(*cur=='#') { // CHANGE_ET lets us put commented lines in the passwd file
-					while(*cur!='\n' && *cur!='\r' && cur<end)
-						cur++;
-					while((*cur=='\n' || *cur=='\r') && cur<end)
-						cur++;
-					continue;
-				}
-        while (isspace(*cur)) cur++;
-        head = cur;
-        while (!isspace(*cur) && (cur < end)) cur++;
-        if (cur >= end) break;
-        *cur++ = '\0';
-        strcpy(pass.user, head);
-
-        while (isspace(*cur)) cur++;
-        head = cur;
-        while (!isspace(*cur) && (cur < end)) cur++;
-        if (cur >= end) break;
-        *cur++ = '\0';
-        strcpy(pass.pass, head);
-
-        while (isspace(*cur)) cur++;
-        head = cur;
-        while (!isspace(*cur) && (cur < end)) cur++;
-        if (cur >= end) break;
-        *cur++ = '\0';
-        strcpy(pass.home, head);
-
-        if (passwd.PushBack(pass)) break;
-    }
-
-    DeleteRegion(buf);
-    return oSUCCESS;
-}
-
-OStatus
-TinyFTPD::Load(char* path, byte** data, size_t* size)
-{
-    FILE* fp;
-    byte* readBuf = 0;
-    int readBufSize;
-    
-    *data = 0;
-    *size = 0;
-
-    struct stat statbuf;
-    int ret = stat(path, &statbuf);
-    if (ret != 0) return oNOT_FOUND;
-
-    readBufSize = statbuf.st_size;
-
-    OSYSDEBUG(("%s size %d readBufSize %d\n",
-               path, statbuf.st_size, readBufSize));
-
-    readBuf = (byte*)malloc(readBufSize);
-    if (readBuf == NULL) return oNO_MEMORY;
-
-    fp = fopen(path, "r");
-    if (fp == 0) {
-        free(readBuf);
-        return oFAIL;
-    }
-
-    ret = fread(readBuf, 1, statbuf.st_size, fp);    
-    fclose(fp);
-
-    if (ret != statbuf.st_size) {
-        free(readBuf);
-        return oFAIL;
-    }
-    
-	*data = readBuf;
-	*size = statbuf.st_size;
-
-    return oSUCCESS;
-}
diff -urdN ../Tekkotsu_2.3/TinyFTPD/TinyFTPD.h ./TinyFTPD/TinyFTPD.h
--- ../Tekkotsu_2.3/TinyFTPD/TinyFTPD.h	Tue Jul  6 18:43:45 2004
+++ ./TinyFTPD/TinyFTPD.h	Wed Dec 31 19:00:00 1969
@@ -1,60 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-#ifndef _TinyFTPD_h_DEFINED
-#define _TinyFTPD_h_DEFINED
-
-#include <OPENR/OObject.h>
-#include <OPENR/OSubject.h>
-#include <OPENR/OObserver.h>
-#include <OPENR/OList.h>
-#include "FtpConfig.h"
-#include "FtpPI.h"
-#include "def.h"
-
-class TinyFTPD : public OObject
-{
-public:
-    TinyFTPD();
-    virtual ~TinyFTPD() {}
-
-    OSubject*   subject[numOfSubject];
-    OObserver*  observer[numOfObserver];     
-
-    virtual OStatus DoInit   (const OSystemEvent& event);
-    virtual OStatus DoStart  (const OSystemEvent& event);
-    virtual OStatus DoStop   (const OSystemEvent& event);
-    virtual OStatus DoDestroy(const OSystemEvent& event);
-
-    void ListenContforPI  (ANTENVMSG msg);
-    void SendContforPI    (ANTENVMSG msg);
-    void ReceiveContforPI (ANTENVMSG msg);
-    void CloseContforPI   (ANTENVMSG msg);
-    void ListenContforDTP (ANTENVMSG msg);
-    void ConnectContforDTP(ANTENVMSG msg);
-    void SendContforDTP   (ANTENVMSG msg);
-    void ReceiveContforDTP(ANTENVMSG msg);
-    void CloseContforDTP  (ANTENVMSG msg);
-
-private:
-    OStatus LoadPasswd();
-    OStatus Load(char* path, byte** data, size_t* size);
-
-    antStackRef ipstackRef;
-    FtpPI ftpPI[FTP_CONNECTION_MAX];
-
-    OList<Passwd, MAX_LOGIN> passwd;
-
-		TinyFTPD(const TinyFTPD&); //CHANGE_ET copy constructor, don't call
-		TinyFTPD operator=(const TinyFTPD&); //CHANGE_ET assignment operator, don't call
-};
-
-#endif /* _TinyFTPD_h_DEFINED */
diff -urdN ../Tekkotsu_2.3/TinyFTPD/TinyFTPD.ocf ./TinyFTPD/TinyFTPD.ocf
--- ../Tekkotsu_2.3/TinyFTPD/TinyFTPD.ocf	Mon Jul 12 16:22:29 2004
+++ ./TinyFTPD/TinyFTPD.ocf	Wed Dec 31 19:00:00 1969
@@ -1 +0,0 @@
-object TinyFTPD 3072 16386 128 cache notlb kernel
diff -urdN ../Tekkotsu_2.3/TinyFTPD/stub.cfg ./TinyFTPD/stub.cfg
--- ../Tekkotsu_2.3/TinyFTPD/stub.cfg	Tue Jul  6 18:30:57 2004
+++ ./TinyFTPD/stub.cfg	Wed Dec 31 19:00:00 1969
@@ -1,26 +0,0 @@
-//
-// Copyright 2002,2003 Sony Corporation 
-//
-// Permission to use, copy, modify, and redistribute this software for
-// non-commercial use is hereby granted.
-//
-// This software is provided "as is" without warranty of any kind,
-// either expressed or implied, including but not limited to the
-// implied warranties of fitness for a particular purpose.
-//
-
-ObjectName : TinyFTPD
-NumOfOSubject   : 1
-NumOfOObserver  : 1
-Service : "TinyFTPD.DummySubject.DoNotConnect.S", null, null
-Service : "TinyFTPD.DummyObserver.DoNotConnect.O", null, null
-
-Extra : ListenContforPI()
-Extra : SendContforPI()
-Extra : ReceiveContforPI()
-Extra : CloseContforPI()
-Extra : ListenContforDTP()
-Extra : ConnectContforDTP()
-Extra : SendContforDTP()
-Extra : ReceiveContforDTP()
-Extra : CloseContforDTP()
diff -urdN ../Tekkotsu_2.3/Vision/BallDetectionGenerator.cc ./Vision/BallDetectionGenerator.cc
--- ../Tekkotsu_2.3/Vision/BallDetectionGenerator.cc	Fri Jan 14 17:24:51 2005
+++ ./Vision/BallDetectionGenerator.cc	Wed Jul  6 18:49:22 2005
@@ -11,8 +11,8 @@
 typedef RegionGenerator::region region; //!< shorthand - using CMVision regions
 typedef SegmentedColorGenerator::color_class_state color_class_state; //!< shorthand - using CMVision color structs
 
-BallDetectionGenerator::BallDetectionGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, unsigned int colorIdx, unsigned int threshmapChan, unsigned int noiseFiltering, float confidence)
-	: EventGeneratorBase("BallDetectionGenerator",EventBase::visObjEGID,mysid,gid,sid), clrIdx(colorIdx), tmIdx(threshmapChan), ball(), present(false), count(0), noiseThreshold(noiseFiltering), confidenceThreshold(confidence)
+BallDetectionGenerator::BallDetectionGenerator(unsigned int mysid, const RegionGenerator * rg, unsigned int colorIdx, unsigned int threshmapChan, unsigned int noiseFiltering, float confidence)
+	: EventGeneratorBase("BallDetectionGenerator","BallDetectionGenerator",EventBase::visObjEGID,mysid,rg->getGeneratorID(),rg->getSourceID(),EventBase::statusETID), clrIdx(colorIdx), tmIdx(threshmapChan), ball(), present(false), count(0), noiseThreshold(noiseFiltering), confidenceThreshold(confidence)
 {}
 
 void
@@ -38,13 +38,44 @@
     frame_cnt = (frame_cnt + 1) % print_period;
 
 	unsigned int layer=segev->getNumLayers()-config->vision.resolution-1;
+	if(segev->getNumColors()<=clrIdx) {
+		serr->printf("BallDetectionGenerator::clrIdx %d is invalid (only %d available)\n",clrIdx,segev->getNumColors());
+		return;
+	}
+	if(segev->getNumChannels()<=tmIdx) {
+		serr->printf("BallDetectionGenerator::tmIdx %d is invalid (only %d available)\n",tmIdx,segev->getNumChannels());
+		return;
+	}
+	if(segev->getNumLayers()<=layer) {
+		serr->printf("BallDetectionGenerator's selected layer %d is invalid (only %d available)\n",layer,segev->getNumLayers());
+		return;
+	}
+	if(segev->getImage(layer,tmIdx)==NULL) {
+		serr->printf("BallDetectionGenerator source's getImage returned NULL!\n");
+		return;
+	}
   const color_class_state& ballCCS=reinterpret_cast<const color_class_state*>(segev->getImage(layer,tmIdx))[clrIdx];
 
   ball.confidence = 0;
 	region * ball_region=NULL;
 
   region * or_reg=ballCCS.list; //head of linked list of regions of target color. or_reg= original region (without noise removal)
-  if(!or_reg) return;
+  if(!or_reg){
+		count++;
+		// The next 3 lines could be cleared if no dimensions are sent with the deactivation events
+		float dim=segev->getWidth(layer)>segev->getHeight(layer) ? segev->getWidth(layer) : segev->getHeight(layer);	
+		//the max width and height of scaled dimensions
+		float cw=segev->getWidth(layer)/dim;
+		float ch=segev->getHeight(layer)/dim;	
+		unsigned int frame_number=segev->getFrameNumber();
+		if (present && count>noiseThreshold) {  // If there are no regions a number of frames and ball was present
+			count=0;
+			present=false; // Ball is not present
+			createEvent(EventBase::deactivateETID,0,0,0,0,0,cw,ch,frame_number); // Deactivation Events
+		}
+		return;
+  }
+  
   unsigned int n = 0;
   while(or_reg && n<NUM_CHECK) {
     //float conf,conf0,conf_square_bbox,conf_area,conf_green,conf_area_bonus;
@@ -210,36 +241,37 @@
   }
   //return (ball_color==getColor("red"))?generateEvent (VisionObjectEvent::RedBallSID, ball->confidence, ball_region->cen_x, ball_region->cen_y):generateEvent(VisionObjectEvent::PinkBallSID,ball->confidence,ball_region->cen_x,ball_region->cen_y);
   
-	testSendEvent(*segev,ball.confidence,(int)ball_region->x1,(int)ball_region->x2,(int)ball_region->y1,(int)ball_region->y2); 
+	testSendEvent(*segev,ball.confidence,(int)ball_region->x1,(int)ball_region->x2,(int)ball_region->y1,(int)ball_region->y2,(int)ball_region->area); 
 }
 
 void
-BallDetectionGenerator::testSendEvent(const FilterBankEvent& ev, float conf, int regX1,int regX2,int regY1,int regY2) {
+BallDetectionGenerator::testSendEvent(const FilterBankEvent& ev, float conf, int regX1,int regX2,int regY1,int regY2, int area) {
 	unsigned int layer=ev.getNumLayers()-config->vision.resolution-1;
 
 	//pick the larger dimension for scaling, one dimension will be [-1,1], the other will depend on aspect ratio
 	float dim=ev.getWidth(layer)>ev.getHeight(layer) ? ev.getWidth(layer) : ev.getHeight(layer);
 
 	//the max width and height of scaled dimensions
-	float cw=ev.getWidth(layer)/dim;
-	float ch=ev.getHeight(layer)/dim;
+	float cw=config->vision.x_range; //ev.getWidth(layer)/dim;
+	float ch=config->vision.y_range; //ev.getHeight(layer)/dim;
 
 	//scale the dimensions
 	float cx1=2.0f*regX1/dim - cw;
 	float cx2=2.0f*(regX2+1)/dim - cw;
 	float cy1=2.0f*regY1/dim - ch;
 	float cy2=2.0f*(regY2+1)/dim - ch;
+	unsigned int frame_number=ev.getFrameNumber();	
 
 	if (conf>confidenceThreshold) {
 		if (present) {
 			count=0;
-			createEvent(EventBase::statusETID,cx1,cx2,cy1,cy2,cw,ch);
+			createEvent(EventBase::statusETID,cx1,cx2,cy1,cy2,area,cw,ch,frame_number);
 		} else {
 			count++;
 			if (count>noiseThreshold) {
 				count=0;
 				present=true;
-				createEvent(EventBase::activateETID,cx1,cx2,cy1,cy2,cw,ch);
+				createEvent(EventBase::activateETID,cx1,cx2,cy1,cy2,area,cw,ch,frame_number);
 			}
 		}
 	} else {
@@ -250,17 +282,17 @@
 			if (count>noiseThreshold) {
 				count=0;
 				present=false;
-				createEvent(EventBase::deactivateETID,0,0,0,0,cw,ch);
+				createEvent(EventBase::deactivateETID,0,0,0,0,area,cw,ch,frame_number);
 			} else {
-				createEvent(EventBase::statusETID,cx1,cx2,cy1,cy2,cw,ch);
+				createEvent(EventBase::statusETID,cx1,cx2,cy1,cy2,area,cw,ch,frame_number);
 			}
 		}
 	}
 }
 
 void
-BallDetectionGenerator::createEvent(EventBase::EventTypeID_t etid, float bbX1,float bbX2,float bbY1,float bbY2,float rx,float ry) const {
-	VisionObjectEvent * vo=new VisionObjectEvent(etid,mySourceID,bbX1,bbX2,bbY1,bbY2,rx,ry);
+BallDetectionGenerator::createEvent(EventBase::EventTypeID_t etid, float bbX1,float bbX2,float bbY1,float bbY2,float area,float rx,float ry,unsigned int frame) const {
+	VisionObjectEvent * vo=new VisionObjectEvent(mySourceID,etid,bbX1,bbX2,bbY1,bbY2,area,rx,ry,frame);
 	vo->setName(getName());
 	erouter->postEvent(vo);
 }
@@ -292,8 +324,8 @@
  * reviewed the code, so I guess it's all ours...
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.15 $
  * $State: Exp $
- * $Date: 2005/01/14 22:24:51 $
+ * $Date: 2005/07/06 22:49:22 $
  */
diff -urdN ../Tekkotsu_2.3/Vision/BallDetectionGenerator.h ./Vision/BallDetectionGenerator.h
--- ../Tekkotsu_2.3/Vision/BallDetectionGenerator.h	Fri Jan 14 17:24:51 2005
+++ ./Vision/BallDetectionGenerator.h	Thu Jun 23 14:46:15 2005
@@ -5,6 +5,7 @@
 #include "Events/EventGeneratorBase.h"
 
 class FilterBankEvent;
+class RegionGenerator;
 
 //! Uses segmented color region information to detect round objects
 /*! This expects its events to come from a RegionGenerator (or a
@@ -23,7 +24,7 @@
 class BallDetectionGenerator : public EventGeneratorBase {
 public:
 	//! constructor
-	BallDetectionGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, unsigned int colorIdx, unsigned int threshmapChan, unsigned int noiseFiltering, float confidence);
+	BallDetectionGenerator(unsigned int mysid, const RegionGenerator * rg, unsigned int colorIdx, unsigned int threshmapChan, unsigned int noiseFiltering, float confidence);
 
 	static std::string getClassDescription() { return "Detects round-ish regions"; }
 
@@ -52,9 +53,9 @@
 	};
 
 	//! decides wether to actually send the event based on confidence threshold.
-	void testSendEvent(const FilterBankEvent& ev, float conf, int regX1,int regX2,int regY1, int regY2);
+	void testSendEvent(const FilterBankEvent& ev, float conf, int regX1,int regX2,int regY1, int regY2, int area);
 	//! does the actual event sending
-	void createEvent(EventBase::EventTypeID_t etid, float bbX1,float bbX2,float bbY1,float bbY2,float rx,float ry ) const;
+	void createEvent(EventBase::EventTypeID_t etid, float bbX1,float bbX2,float bbY1,float bbY2,float area,float rx,float ry ,unsigned int frame) const;
 	//! returns a bit mask corresponding to edges touched by the coordinates passed
 	static int calcEdgeMask(int x1,int x2,int y1,int y2, int width, int height);
 	//! returns @f[ \left|\frac{a-b}{a+b}\right| @f]
@@ -90,10 +91,10 @@
  * reviewed the code, so I guess it's all ours...
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.6 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
  * $State: Exp $
- * $Date: 2005/01/14 22:24:51 $
+ * $Date: 2005/06/23 18:46:15 $
  * $ Modified: 2005/12/01 $
  * @ Functions to create VisionObjectEvents include now BB and area info. 
  */
diff -urdN ../Tekkotsu_2.3/Vision/BufferedImageGenerator.cc ./Vision/BufferedImageGenerator.cc
--- ../Tekkotsu_2.3/Vision/BufferedImageGenerator.cc	Wed Dec 31 19:00:00 1969
+++ ./Vision/BufferedImageGenerator.cc	Fri Aug  5 17:56:21 2005
@@ -0,0 +1,375 @@
+#include "BufferedImageGenerator.h"
+#include "Events/DataEvent.h"
+#include "Events/FilterBankEvent.h"
+#include "Wireless/Socket.h"
+#include "Events/EventRouter.h"
+#include "Shared/debuget.h"
+#ifndef PLATFORM_APERIOS
+#  include "IPC/MessageReceiver.h"
+#endif
+
+using namespace std;
+
+void BufferedImageGenerator::processEvent(const EventBase & event) {
+	EventGeneratorBase::processEvent(event);
+	if(event.getGeneratorID()!=getListenGeneratorID() || event.getSourceID()!=getListenSourceID())
+		return;
+	if(event.getTypeID()==EventBase::activateETID) {
+		accessed=false;
+		const DataEvent<ImageSource>* data=dynamic_cast<const DataEvent<ImageSource>*>(&event);
+		if(data==NULL) {
+			serr->printf("Error: %s(%s) received event of the wrong type",getClassName().c_str(),getName().c_str());
+			return;
+		}
+		if(imgsrc.layer!=data->getData().layer || imgsrc.channels!=data->getData().channels) {
+			//can "quietly" switch the layer of transmission as long as the width and height were scaled properly
+			//just need to reset the increments if a different layer is being used.
+			for(unsigned int i=0; i<=data->getData().layer; i++) {
+				increments[i] = (1<<(data->getData().layer-i))*data->getData().channels;
+				strides[i]=(1<<(data->getData().layer-i))*data->getData().width*data->getData().channels;
+				skips[i]=strides[i]-data->getData().width*data->getData().channels;
+			}
+			for(unsigned int i=data->getData().layer+1; i<numLayers; i++) {
+				increments[i] = 1;
+				strides[i]=data->getData().width*(1<<(i-data->getData().layer));
+				skips[i]=0;
+			}
+		}
+		imgsrc=data->getData();
+		sysFrameNumber=frameNumber=imgsrc.frameIndex;
+		// -- invalidate dependant images: --
+		//images in every channel beyond the received channels is invalid
+		for(unsigned int i=0; i<numLayers; i++)
+			for(unsigned int j=imgsrc.channels; j<numChannels; j++) {
+				if(!isAllocated[i][j]) //in case the imgsrc layer changes
+					images[i][j]=NULL;
+				imageValids[i][j]=false;
+			}
+		//images in every layer above the received layer is invalid
+		for(unsigned int i=imgsrc.layer+1; i<numLayers; i++)
+			for(unsigned int j=0; j<imgsrc.channels; j++) { //already covered src.channels to numChannels in previous loop
+				if(!isAllocated[i][j]) //in case the imgsrc layer changes
+					images[i][j]=NULL;
+				imageValids[i][j]=false;
+			}
+		// -- check if the size has changed: --
+		if(numLayers>0) {
+			if(imgsrc.width!=getWidth(imgsrc.layer) || imgsrc.height!=getHeight(imgsrc.layer)) {
+				freeCaches();
+				setDimensions();
+				serr->printf("WARNING: the image dimensions don't match values predicted by RobotInfo consts, now %dx%d\n",widths[numLayers-1],heights[numLayers-1]);
+			} else if(strides[numLayers-1]==0) {
+				// first frame, set it anyway
+				setDimensions();
+			}
+		}
+		// -- reassign to the new buffer: --
+		for(unsigned int i=imgsrc.layer; i!=-1U; i--) {
+			for(unsigned int j=0; j<imgsrc.channels; j++) {
+				if(isAllocated[i][j]) { //in case the imgsrc layer changes
+					delete [] images[i][j];
+					images[i][j]=NULL;
+					isAllocated[i][j]=false;
+				}
+				imageValids[i][j]=true;
+			}
+			images[i][RawCameraGenerator::CHAN_Y]=imgsrc.img+0;
+			images[i][RawCameraGenerator::CHAN_U]=imgsrc.img+2; //note U is *third*
+			images[i][RawCameraGenerator::CHAN_V]=imgsrc.img+1; //note V is *second*
+		}
+		framesProcessed++;
+	}
+	erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),event.getTypeID()));
+}
+
+unsigned int
+BufferedImageGenerator::getBinSize() const {
+	unsigned int used=FilterBankGenerator::getBinSize();
+	used+=strlen("RawImage")+LoadSave::stringpad;
+	used+=widths[selectedSaveLayer]*heights[selectedSaveLayer];
+	return used;
+}
+
+unsigned int
+BufferedImageGenerator::LoadBuffer(const char buf[], unsigned int len) {
+	unsigned int origlen=len;
+	unsigned int used;
+	std::string tmp;
+	if(0==(used=FilterBankGenerator::LoadBuffer(buf,len))) return 0;
+	len-=used; buf+=used;
+	if(0==(used=decode(tmp,buf,len))) return 0;
+	len-=used; buf+=used;
+	if(tmp!="RawImage") {
+		serr->printf("Unhandled image type for BufferedImageGenerator: %s",tmp.c_str());
+		return 0;
+	} else if(selectedSaveLayer!=numLayers-1) {
+		serr->printf("Can't load into BufferedImageGenerator layer %d!=%d",selectedSaveLayer,numLayers-1);
+		return 0;
+	} else {
+		if(images[selectedSaveLayer][selectedSaveChannel]==NULL)
+			images[selectedSaveLayer][selectedSaveChannel]=createImageCache(selectedSaveLayer,selectedSaveChannel);
+		unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
+		used=widths[selectedSaveLayer]*heights[selectedSaveLayer];
+		ASSERTRETVAL(used<=len,"buffer too small",0);
+		memcpy(img,buf,used);
+		len-=used; buf+=used;
+		imageValids[selectedSaveLayer][selectedSaveChannel]=true;
+		return origlen-len;	
+	}
+}
+
+unsigned int
+BufferedImageGenerator::SaveBuffer(char buf[], unsigned int len) const {
+	unsigned int origlen=len;
+	unsigned int used;
+	if(0==(used=FilterBankGenerator::SaveBuffer(buf,len))) return 0;
+	len-=used; buf+=used;
+	if(0==(used=encode("RawImage",buf,len))) return 0;
+	len-=used; buf+=used;
+	
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("BufferedImageGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("BufferedImageGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
+	used=widths[selectedSaveLayer]*heights[selectedSaveLayer];
+	ASSERTRETVAL(used<=len,"buffer too small",0);
+	unsigned int inc=getIncrement(selectedSaveLayer);
+	if(inc==1) {
+		//special case, straight copy
+		for(unsigned int y=0; y<heights[selectedSaveLayer]; y++) {
+			memcpy(buf,img,widths[selectedSaveLayer]);
+			buf+=widths[selectedSaveLayer];
+			img+=getStride(selectedSaveLayer);
+		}
+	} else {
+		//otherwise, interleaved or subsampling
+		for(unsigned int y=0; y<heights[selectedSaveLayer]; y++) {
+			unsigned char* const rowend=img+widths[selectedSaveLayer]*inc;
+			while(img!=rowend) {
+				*buf++=*img;
+				img+=inc;
+			}
+			img+=getSkip(selectedSaveLayer);
+		}
+	}
+	len-=used;
+	
+	return origlen-len;
+}
+
+unsigned int
+BufferedImageGenerator::SaveFileStream(FILE * f) const {
+	unsigned int totalused=0;
+	unsigned int used;
+	{ //sigh, inheritance has failed me (I wouldn't want FilterBankGenerator::SaveFileStream() to call the virtuals...)
+		unsigned int sz=FilterBankGenerator::getBinSize();
+		char * buf = new char[sz];
+		memset(buf,0xF0,sz);
+		if(buf==NULL) {
+			std::cout << "*** WARNING could not allocate " << sz << " bytes for LoadFile";
+			return 0;
+		}
+		unsigned int resp=FilterBankGenerator::SaveBuffer(buf,sz);
+		if(resp==0) {
+			std::cout << "*** WARNING SaveBuffer didn't write any data (possibly due to overflow or other error)" << std::endl;
+			fwrite(buf,1,sz,f);
+		}	else {
+			unsigned int wrote=fwrite(buf,1,resp,f);
+			if(wrote!=resp)
+				std::cout << "*** WARNING short write (wrote " << wrote << ", expected " << resp << ")" << std::endl;
+		}
+		delete [] buf;
+		used=resp;
+	}
+	if(0==used) return 0;
+	totalused+=used;
+	if(0==(used=encode("RawImage",f))) return 0;
+	totalused+=used;
+	
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("BufferedImageGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("BufferedImageGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
+	used=widths[selectedSaveLayer]*heights[selectedSaveLayer];
+	unsigned int inc=getIncrement(selectedSaveLayer);
+	if(inc==1) {
+		//special case, straight copy
+		sout->printf("Saving %d by %d\n",widths[selectedSaveLayer],heights[selectedSaveLayer]);
+		for(unsigned int y=0; y<heights[selectedSaveLayer]; y++) {
+			if(fwrite(img,widths[selectedSaveLayer],1,f)==0) {
+				serr->printf("short write on image data - ran out of space?\n");
+				return 0;
+			}
+			img+=getStride(selectedSaveLayer);
+		}
+	} else {
+		//otherwise, interleaved or subsampling
+		for(unsigned int y=0; y<heights[selectedSaveLayer]; y++) {
+			unsigned char* const rowend=img+widths[selectedSaveLayer]*inc;
+			while(img!=rowend) {
+				if(fputc(*img,f)==EOF) {
+					serr->printf("short write on image data - ran out of space?\n");
+					return 0;
+				}
+				img+=inc;
+			}
+			img+=getSkip(selectedSaveLayer);
+		}
+	}
+	totalused+=used;
+	
+	return totalused;
+}
+
+unsigned char * BufferedImageGenerator::getImage(unsigned int layer, unsigned int channel) {
+	if(!accessed && imgsrc.receiver!=NULL) {
+		accessed=true;
+#ifndef PLATFORM_APERIOS
+		imgsrc.receiver->markRead();
+#endif
+	}
+	return FilterBankGenerator::getImage(layer,channel);
+}
+
+void BufferedImageGenerator::freeCaches() {
+	FilterBankGenerator::freeCaches();
+	for(unsigned int i=0; i<numChannels; i++)
+		for(unsigned int j=0; j<numLayers; j++)
+			isAllocated[i][j]=false;
+}
+
+void BufferedImageGenerator::invalidateCaches() {
+	for(unsigned int i=0; i<numLayers; i++)
+		for(unsigned int j=0; j<numChannels; j++) {
+			if(!isAllocated[i][j])
+				images[i][j]=NULL;
+			imageValids[i][j]=false;
+		}
+}
+
+unsigned char * BufferedImageGenerator::createImageCache(unsigned int layer, unsigned int channel) const {
+	isAllocated[layer][channel]=true;
+	return new unsigned char[widths[layer]*heights[layer]];
+}
+void BufferedImageGenerator::calcImage(unsigned int layer, unsigned int channel) {
+	//cout << "BufferedImageGenerator::calcImage(" << layer << ',' << channel << ')' << endl;
+	switch(channel) {
+		case RawCameraGenerator::CHAN_Y:
+			upsampleImage(imgsrc.layer,channel,layer); break;
+		case RawCameraGenerator::CHAN_U:
+		case RawCameraGenerator::CHAN_V:
+			if(imgsrc.channels>1)
+				upsampleImage(imgsrc.layer,channel,layer);
+			else
+				memset(images[layer][channel],128,widths[layer]*heights[layer]);
+			break;
+		case RawCameraGenerator::CHAN_Y_DY:
+		case RawCameraGenerator::CHAN_Y_DX:
+		case RawCameraGenerator::CHAN_Y_DXDY:
+			if(layer<=imgsrc.layer) {
+				//todo
+				memset(images[layer][channel],128,widths[layer]*heights[layer]);
+			} else if(layer>imgsrc.layer) {
+				getImage(imgsrc.layer,channel);
+				upsampleImage(imgsrc.layer,channel,layer);
+			}
+			break;
+		default:
+			cerr << "Bad layer selection!" << endl;
+	}
+}
+void BufferedImageGenerator::setDimensions() {
+	if(imgsrc.img==NULL) //don't have an image to set from
+		return;
+	// set dimensions of layers below and including the input layer
+	for(unsigned int i=0; i<=imgsrc.layer; i++) {
+		//s is the scaling factor -- 2 means *half* size
+		unsigned int s=(1<<(imgsrc.layer-i));
+		//width and height are scaled down (divide by s)
+		widths[i]=imgsrc.width/s;
+		heights[i]=imgsrc.height/s;
+		//need to skip rows to make good on promised height (multiply by s)
+		strides[i]=imgsrc.width*imgsrc.channels*s;
+		skips[i]=strides[i]-imgsrc.width*imgsrc.channels;
+		cout << "setDimensions() " << widths[i] << ' ' << skips[i] << ' ' << strides[i] << endl;
+	}
+	//set dimensions for layers above the input layer, these are not interleaved
+	for(unsigned int i=imgsrc.layer+1; i<numLayers; i++) {
+		//s is the scaling factor -- 2 means *double* size
+		unsigned int s=(1<<(i-imgsrc.layer));
+		//multiply by s
+		widths[i]=strides[i]=imgsrc.width*s;
+		heights[i]=imgsrc.height*s;
+		//stride is same as width (set above) -- we allocate these layers, don't skip rows
+		skips[i]=0;
+	}
+}
+void BufferedImageGenerator::destruct() {
+	FilterBankGenerator::destruct();
+	for(unsigned int i=0; i<numLayers; i++)
+		delete [] isAllocated[i];
+	delete [] isAllocated;
+	isAllocated=NULL;
+}
+void BufferedImageGenerator::setNumImages(unsigned int nLayers, unsigned int nChannels) {
+	if(nLayers==numLayers && nChannels==numChannels)
+		return;
+	FilterBankGenerator::setNumImages(nLayers,nChannels);
+	isAllocated=new bool*[numLayers];
+	for(unsigned int i=0; i<numLayers; i++)
+		isAllocated[i]=new bool[numChannels];
+	setDimensions();
+}
+
+void BufferedImageGenerator::upsampleImage(unsigned int srcLayer, unsigned int chan, unsigned int destLayer) {
+	unsigned char * cur=images[destLayer][chan];
+	ASSERTRET(cur!=NULL,"destination layer is NULL");
+	unsigned char * orig=getImage(srcLayer,chan);
+	ASSERTRET(orig!=NULL,"source layer is NULL");
+	unsigned int width=widths[destLayer];
+	unsigned int height=heights[destLayer];
+	unsigned int inc=getIncrement(srcLayer);
+	int power=destLayer-srcLayer;
+	ASSERTRET(power>0,"upsampleImage attempting to downsample")
+	
+	unsigned char * const imgend=cur+width*height;
+	while(cur!=imgend) {
+		unsigned char * const row=cur;
+		unsigned char * const rowend=cur+width;
+		//upsample pixels within one row
+		while(cur!=rowend) {
+			for(int p=power; p>=0; p--)
+				*cur++=*orig;
+			orig+=inc;
+		}
+		//now replicate that row 1<<power times, doubling each time
+		for(int p=0; p<power; p++) {
+			unsigned int avail=width*(1<<p);
+			memcpy(cur,row,avail);
+			cur+=avail;
+		}
+		orig+=getSkip(srcLayer);
+	}
+}
+
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
+ * $State: Exp $
+ * $Date: 2005/08/05 21:56:21 $
+ */
diff -urdN ../Tekkotsu_2.3/Vision/BufferedImageGenerator.h ./Vision/BufferedImageGenerator.h
--- ../Tekkotsu_2.3/Vision/BufferedImageGenerator.h	Wed Dec 31 19:00:00 1969
+++ ./Vision/BufferedImageGenerator.h	Sun Aug  7 00:11:04 2005
@@ -0,0 +1,108 @@
+//-*-c++-*-
+#ifndef INCLUDED_BufferedImageGenerator_h_
+#define INCLUDED_BufferedImageGenerator_h_
+
+#include "FilterBankGenerator.h"
+#include "RawCameraGenerator.h"
+
+class MessageReceiver;
+
+//! description of BufferedImageGenerator
+class BufferedImageGenerator : public FilterBankGenerator {
+public:
+	//!Stores information about the current frame, (not the image itself, but meta data a pointer to it)
+	struct ImageSource {
+		//!constructor
+		ImageSource() : width(0), height(0), channels(0), frameIndex(0), layer(0), receiver(NULL), img(NULL) {}
+		//!copy constructor
+		ImageSource(const ImageSource& src) : width(src.width), height(src.height), channels(src.channels), frameIndex(src.frameIndex), layer(src.layer), receiver(src.receiver), img(src.img) {}
+		//!assignment operator
+		ImageSource& operator=(const ImageSource& src) { width=src.width; height=src.height; channels=src.channels; frameIndex=src.frameIndex; layer=src.layer; receiver=src.receiver; img=src.img; return *this; } 
+		unsigned int width; //!< the width of #img
+		unsigned int height; //!< the height of #img
+		unsigned int channels; //!< the number of color channels in #img
+		unsigned int frameIndex; //!< the serial number of the current frame (should be a unique, increasing ID)
+
+		//! indicates what resolution layer of the pipeline this should be used at
+		/*! Negative values are interpreted as "from the top", so -1 is the topmost layer, -2 is next-to-top, and so on.\n
+		 *  Non-negative values are interpreted as direct layer values, so 0 indicates bottommost layer, 1 indicates next-to-bottom, and so on. */
+		unsigned int layer; 
+
+		//! a pointer back to the MessageReceiver which got the image
+		/*! If this value is non-NULL, when getImage is called, MessageReceiver::markRead() will be called on the receiver */
+		MessageReceiver * receiver;
+
+		//! pointer to the first byte of the image buffer
+		/*! img should be stored in a channel-interleaved format, e.g. RGBRGBRGB... */
+		unsigned char * img;
+	};
+
+	//! constructor
+	BufferedImageGenerator(const std::string& name,EventBase::EventGeneratorID_t mgid, unsigned int msid, unsigned int nLayers, EventBase::EventGeneratorID_t srcgid, unsigned int srcsid)
+		: FilterBankGenerator("BufferedImageGenerator",name,mgid,msid,srcgid,srcsid), imgsrc(), isAllocated(NULL), accessed(true)
+	{ 
+		/* As a root stage, we need to listen to all incoming image
+		 * events, even if we don't currently have listeners of our own --
+		 * This is just in case user code directly accesses a generator
+		 * and we have to retroactively go back and dig up the previous
+		 * frame */
+		unsetAutoListen();
+		
+		setNumImages(nLayers,RawCameraGenerator::NUM_CHANNELS);
+	}
+	virtual ~BufferedImageGenerator() { destruct(); }
+	
+	//! need to override EventGeneratorBase's lazy listening -- as a root stage, need to remember each frame, just in case it might be used
+	virtual void DoStart() { FilterBankGenerator::DoStart(); addSrcListener(); }
+
+	virtual void processEvent(const EventBase & event);
+	
+	virtual unsigned int getBinSize() const;
+	
+	virtual unsigned int LoadBuffer(const char buf[], unsigned int len);
+	
+	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
+	
+	virtual unsigned int SaveFileStream(FILE* f) const; //!< overrridden to allow saving direct to file without an extra buffer copy
+
+	virtual unsigned char * getImage(unsigned int layer, unsigned int channel);
+	virtual void freeCaches();
+	virtual void invalidateCaches();
+	
+protected:
+	//! constructor for subclasses
+	BufferedImageGenerator(const std::string& classname,const std::string& instancename,EventBase::EventGeneratorID_t mgid, unsigned int msid, unsigned int nLayers,EventBase::EventGeneratorID_t srcgid, unsigned int srcsid)
+		: FilterBankGenerator(classname,instancename,mgid,msid,srcgid,srcsid), imgsrc(), isAllocated(NULL), accessed(true)
+	{setNumImages(nLayers,RawCameraGenerator::NUM_CHANNELS);}
+	
+	virtual unsigned char * createImageCache(unsigned int layer, unsigned int channel) const;
+	virtual void calcImage(unsigned int layer, unsigned int channel) ;
+	virtual void setDimensions();
+	virtual void destruct();
+	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
+
+	//! duplicates pixels to make a higher resolution version of @a srcLayer, @a chan into @a destLayer, @a chan
+	/*! Doesn't do anything fancy like blurring or smoothing */
+	virtual void upsampleImage(unsigned int srcLayer, unsigned int chan, unsigned int destLayer);
+
+	ImageSource imgsrc; //!< the data storage of the current image (not the image itself, but meta data a pointer to it)
+	bool ** isAllocated; //!< for each image in the filterbank, a bool to account whether the pointer is to an external resource or a self-allocated resource
+	bool accessed; //!< marked true once getImage is called, reset to false with each new image (i.e. processEvent())
+	
+private:
+	BufferedImageGenerator(const BufferedImageGenerator&); //!< don't call
+	BufferedImageGenerator& operator=(const BufferedImageGenerator&); //!< don't call
+};
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:04 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Vision/CDTGenerator.cc ./Vision/CDTGenerator.cc
--- ../Tekkotsu_2.3/Vision/CDTGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/CDTGenerator.cc	Fri Jun  3 18:56:30 2005
@@ -6,14 +6,21 @@
 #include "Shared/Config.h"
 #include "Shared/WorldState.h"
 
-#include <OPENR/ODataFormats.h>
-#include <OPENR/OFbkImage.h>
+#include "Shared/ODataFormats.h"
+#include "OFbkImage.h"
 
 #include "Shared/debuget.h"
 
-CDTGenerator::CDTGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid)
-	: FilterBankGenerator("CDTGenerator",gid,sid,EventBase::visSegmentEGID,mysid), numRealLayers(numRawLayers), layers(NULL), imageInfos(NULL)
+CDTGenerator::CDTGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, unsigned int mysid, EventBase::EventGeneratorID_t gid, unsigned int sid)
+	: FilterBankGenerator("CDTGenerator","CDTGenerator",EventBase::visSegmentEGID,mysid,gid,sid), numRealLayers(numRawLayers), layers(NULL), imageInfos(NULL)
 {
+	/* As a root stage, we need to listen to all incoming image
+	 * events, even if we don't currently have listeners of our own --
+	 * This is just in case user code directly accesses a generator
+	 * and we have to retroactively go back and dig up the previous
+	 * frame */
+	unsetAutoListen();
+	
 	setNumImages(numCalcLayers,NUM_CHANNELS);
 }
 
@@ -26,45 +33,55 @@
 	EventGeneratorBase::processEvent(event);
 	if(event.getGeneratorID()!=getListenGeneratorID() || event.getSourceID()!=getListenSourceID())
 		return;
+	if(event.getTypeID()==EventBase::activateETID) {
+		typedef DataEvent<const OFbkImageVectorData*> OFbkEvent;
+		const OFbkEvent& fbkevent=dynamic_cast<const OFbkEvent& >(event);
+		OFbkImageVectorData& fbkdat=*const_cast<OFbkImageVectorData*>(fbkevent.getData());
+		for(unsigned int res=0; res<numRealLayers; res++) {
+			layers[numLayers-1-res] = fbkdat.GetData(res);
+			imageInfos[numLayers-1-res] = fbkdat.GetInfo(res);
+		}
+		{
+			const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[numLayers-2]), const_cast<unsigned char*>(layers[numLayers-2]), ofbkimageBAND_CDT);
+			//I have to do this crazy thing because apparently img.FieldCounter() doesn't work
+			sysFrameNumber=frameNumber=*(int*)(img.Pointer()+(img.Height()-1)*(img.Skip()+img.Width()));
+		}
+		unsigned int numNotRealLayers=numLayers-numRealLayers;
+		bool dimchange=false;
+		for(unsigned int res=numNotRealLayers; res<numLayers; res++) {
+			if(widths[res]!=imageInfos[res]->width || heights[res]!=imageInfos[res]->height) {
+				dimchange=true;
+				serr->printf("WARNING: the image dimensions changed, now %dx%d\n",widths[numLayers-1],heights[numLayers-1]);
+				widths[res] = imageInfos[res]->width;
+				heights[res] = imageInfos[res]->height;
+			}
 
-	typedef DataEvent<const OFbkImageVectorData*> OFbkEvent;
-	const OFbkEvent& fbkevent=dynamic_cast<const OFbkEvent& >(event);
-	OFbkImageVectorData& fbkdat=*const_cast<OFbkImageVectorData*>(fbkevent.getData());
-	for(unsigned int res=0; res<numRealLayers; res++) {
-		layers[numLayers-1-res] = fbkdat.GetData(res);
-		imageInfos[numLayers-1-res] = fbkdat.GetInfo(res);
-	}
-	{
-		const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[numLayers-2]), const_cast<unsigned char*>(layers[numLayers-2]), ofbkimageBAND_CDT);
-		//I have to do this crazy thing because apparently img.FieldCounter() doesn't work
-		frameNumber=*(int*)(img.Pointer()+(img.Height()-1)*(img.Skip()+img.Width()));
-	}
-	unsigned int numNotRealLayers=numLayers-numRealLayers;
-	for(unsigned int res=numNotRealLayers; res<numLayers; res++) {
-		widths[res] = imageInfos[res]->width;
-		heights[res] = imageInfos[res]->height;
-
-		const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[res]), const_cast<unsigned char*>(layers[res]), ofbkimageBAND_CDT);
-		skips[res]=img.Skip();
-		strides[res]=skips[res]+widths[res];
+			const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[res]), const_cast<unsigned char*>(layers[res]), ofbkimageBAND_CDT);
+			skips[res]=img.Skip();
+			strides[res]=skips[res]+widths[res];
 
-		ASSERT(static_cast<unsigned int>(img.Width())==getWidth(res),"Widths don't match");
-		ASSERT(static_cast<unsigned int>(img.Height())==getHeight(res),"Heights don't match");
-	}
-	if(numNotRealLayers>0) {
-		if(widths[numNotRealLayers-1]*2!=widths[numNotRealLayers] || heights[numNotRealLayers]*2!=heights[numNotRealLayers]) {
-			//|| widths[numLayers-2-numRealLayers]*2!=widths[numNotRealLayers]
-			//|| heights[numLayers-2-numRealLayers]*2!=heights[numNotRealLayers]) {
-			//set the width and height of non-real layers (since they don't match what they should be)
-			ASSERT(widths[numLayers-1]==0,"Strange, the image width changed after initial setting" << widths[numLayers-1]);
-			setDimensions();
+			ASSERT(static_cast<unsigned int>(img.Width())==getWidth(res),"Widths don't match");
+			ASSERT(static_cast<unsigned int>(img.Height())==getHeight(res),"Heights don't match");
 		}
-	}
+		if(numNotRealLayers>0) {
+			if(widths[numNotRealLayers-1]*2!=widths[numNotRealLayers] || heights[numNotRealLayers]*2!=heights[numNotRealLayers]) {
+				//|| widths[numLayers-2-numRealLayers]*2!=widths[numNotRealLayers]
+				//|| heights[numLayers-2-numRealLayers]*2!=heights[numNotRealLayers]) {
+				//set the width and height of non-real layers (since they don't match what they should be)
+				serr->printf("WARNING: the image dimensions don't match values predicted by RobotInfo consts, now %dx%d\n",widths[numLayers-1],heights[numLayers-1]);
+				dimchange=true;
+			} else if(strides[0]==0) {
+				dimchange=true;
+			}
+		}
+		if(dimchange)
+			setDimensions();
 
-	invalidateCaches();
-	framesProcessed++;
+		invalidateCaches();
+		framesProcessed++;
+	}
 	// todo - i wish we had some color infomation to pass here so we could use the event for CMVision's RLE, etc.
-	erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),NULL,0,NULL,NULL));
+	erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),event.getTypeID(),NULL,0,NULL,NULL));
 }
 
 unsigned int
@@ -95,7 +112,15 @@
 	if(0==(used=encode("CDTImage",buf,len))) return 0;
 	len-=used; buf+=used;
 	
-	unsigned char* img=getImage(selectedSaveLayer,selectedSaveChannel);
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("CDTImage::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("CDTImage::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
 	used=widths[selectedSaveLayer]*heights[selectedSaveLayer];
 	if(used>len)
 		return 0;
@@ -172,7 +197,7 @@
 }
 
 void
-CDTGenerator::calcImage(unsigned int layer, unsigned int chan) const {
+CDTGenerator::calcImage(unsigned int layer, unsigned int chan) {
 	PROFSECTION("CDTGenerator::calcImage(...)",state->mainProfile);
 	unsigned int numNotRealLayers=numLayers-numRealLayers;
 	if(layer>=numNotRealLayers) {
@@ -237,9 +262,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/06/03 22:56:30 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/CDTGenerator.h ./Vision/CDTGenerator.h
--- ../Tekkotsu_2.3/Vision/CDTGenerator.h	Wed Feb 18 16:13:32 2004
+++ ./Vision/CDTGenerator.h	Wed Jun  1 01:47:58 2005
@@ -4,7 +4,6 @@
 
 #include "Vision/FilterBankGenerator.h"
 
-class OFbkImageVectorData;
 class OFbkImageInfo;
 
 //! Generates SegmentedColorFilterBankEvents with images provided from the system
@@ -44,7 +43,7 @@
 class CDTGenerator : public FilterBankGenerator {
 public:
 	//!constructor
-	CDTGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid);
+	CDTGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, unsigned int mysid, EventBase::EventGeneratorID_t gid, unsigned int sid);
 
 	//! destructor
 	virtual ~CDTGenerator() {
@@ -60,6 +59,9 @@
 		NUM_CHANNELS //!< number of channels per resolution layer
 	};
 
+	//! need to override EventGeneratorBase's lazy listening -- as a root stage, need to remember each frame, just in case it might be used
+	virtual void DoStart() { FilterBankGenerator::DoStart(); addSrcListener(); }
+
 	//! called with system's image info
 	virtual void processEvent(const EventBase& event);
 	
@@ -79,7 +81,7 @@
 	virtual void setDimensions();
 	
 	virtual unsigned char * createImageCache(unsigned int layer, unsigned int chan) const;
-	virtual void calcImage(unsigned int layer, unsigned int chan) const;
+	virtual void calcImage(unsigned int layer, unsigned int chan);
 	virtual void destruct();
 	
 	unsigned int numRealLayers; //!< the number of actual layers to expect from the system
@@ -97,10 +99,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/02/18 21:13:32 $
+ * $Date: 2005/06/01 05:47:58 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/CVS/Entries ./Vision/CVS/Entries
--- ../Tekkotsu_2.3/Vision/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Vision/CVS/Entries	Wed Aug 10 11:03:21 2005
@@ -0,0 +1,29 @@
+/BallDetectionGenerator.cc/1.15/Wed Jul  6 22:49:22 2005//Ttekkotsu-2_4
+/BallDetectionGenerator.h/1.9/Thu Jun 23 18:46:15 2005//Ttekkotsu-2_4
+/BufferedImageGenerator.cc/1.11/Fri Aug  5 21:56:21 2005//Ttekkotsu-2_4
+/BufferedImageGenerator.h/1.5/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/CDTGenerator.cc/1.10/Fri Jun  3 22:56:30 2005//Ttekkotsu-2_4
+/CDTGenerator.h/1.5/Wed Jun  1 05:47:58 2005//Ttekkotsu-2_4
+/FilterBankGenerator.cc/1.10/Wed Jul  6 22:49:22 2005//Ttekkotsu-2_4
+/FilterBankGenerator.h/1.18/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/Graphics.cc/1.4/Sun Jul 10 20:02:39 2005//Ttekkotsu-2_4
+/Graphics.h/1.4/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/InterleavedYUVGenerator.cc/1.14/Fri Aug  5 21:56:04 2005//Ttekkotsu-2_4
+/InterleavedYUVGenerator.h/1.14/Mon Jun 13 18:03:15 2005//Ttekkotsu-2_4
+/JPEGGenerator.cc/1.13/Mon Jun 13 19:39:33 2005//Ttekkotsu-2_4
+/JPEGGenerator.h/1.10/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/OFbkImage.h/1.2/Wed Jun  1 05:47:58 2005//Ttekkotsu-2_4
+/RLEGenerator.cc/1.11/Mon Jun 13 21:24:11 2005//Ttekkotsu-2_4
+/RLEGenerator.h/1.8/Wed Jun  1 05:47:58 2005//Ttekkotsu-2_4
+/RawCameraGenerator.cc/1.21/Mon Jun  6 19:33:31 2005//Ttekkotsu-2_4
+/RawCameraGenerator.h/1.17/Fri Jun  3 22:56:30 2005//Ttekkotsu-2_4
+/RegionGenerator.cc/1.11/Mon Jun  6 20:23:15 2005//Ttekkotsu-2_4
+/RegionGenerator.h/1.7/Wed Jun 29 22:06:11 2005//Ttekkotsu-2_4
+/SegmentedColorGenerator.cc/1.10/Mon Jun  6 19:33:31 2005//Ttekkotsu-2_4
+/SegmentedColorGenerator.h/1.11/Wed Jun  1 05:47:58 2005//Ttekkotsu-2_4
+/cmv_region.h/1.9/Wed Jun  1 05:47:58 2005//Ttekkotsu-2_4
+/cmv_threshold.h/1.6/Sat Jun  4 23:23:31 2005//Ttekkotsu-2_4
+/cmv_types.h/1.5/Sat Jun  4 23:23:31 2005//Ttekkotsu-2_4
+/cmvision.h/1.3/Thu Jan 23 18:14:11 2003//Ttekkotsu-2_4
+/colors.h/1.5/Thu Mar 10 23:18:07 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Vision/CVS/Repository ./Vision/CVS/Repository
--- ../Tekkotsu_2.3/Vision/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Vision/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/Vision
diff -urdN ../Tekkotsu_2.3/Vision/CVS/Root ./Vision/CVS/Root
--- ../Tekkotsu_2.3/Vision/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Vision/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Vision/CVS/Tag ./Vision/CVS/Tag
--- ../Tekkotsu_2.3/Vision/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Vision/CVS/Tag	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Vision/FilterBankGenerator.cc ./Vision/FilterBankGenerator.cc
--- ../Tekkotsu_2.3/Vision/FilterBankGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/FilterBankGenerator.cc	Wed Jul  6 18:49:22 2005
@@ -1,13 +1,19 @@
 #include "FilterBankGenerator.h"
 #include "Events/FilterBankEvent.h"
 #include "Events/EventRouter.h"
+#include "Wireless/Socket.h"
+#include "Shared/RobotInfo.h"
 
 using namespace std;
 
+unsigned int FilterBankGenerator::sysFrameNumber=-1U;
+
 unsigned char *
-FilterBankGenerator::getImage(unsigned int layer, unsigned int channel) const {
+FilterBankGenerator::getImage(unsigned int layer, unsigned int channel) {
 	//for(int i=0;i<1000;i++)
 	//std::cout << i << " FBG::getImage(" << layer<<'/'<<numLayers  << ',' << channel<<'/'<<numChannels << ");" << std::endl;
+	if(!refresh())
+		return NULL;
 	if(!imageValids[layer][channel]) {
 		if(images[layer][channel]==NULL)
 			images[layer][channel]=createImageCache(layer,channel);
@@ -37,15 +43,12 @@
 FilterBankGenerator::processEvent(const EventBase & event) {
 	if(event.getGeneratorID()==getListenGeneratorID() && event.getSourceID()==getListenSourceID()) {
 		const FilterBankEvent& fbkevent=dynamic_cast<const FilterBankEvent& >(event);
-		src=fbkevent.getSource();
-		frameNumber=src->getFrameNumber();
-		setNumImages(src->getNumLayers(),src->getNumChannels());
-		if(numLayers>0 && (src->getWidth(numLayers-1)!=getWidth(numLayers-1) || src->getHeight(numLayers-1)!=getHeight(numLayers-1))) {
-			ASSERT(widths[numLayers-1]==0,"Strange, the image dim changed after initial setting" << widths[numLayers-1] << ' ' << heights[numLayers-1]);
-			setDimensions();
+		if(fbkevent.getSource()==NULL) {
+			serr->printf("%s %s received event with null source\n",getClassName().c_str(),getName().c_str());
+			return;
 		}
-		invalidateCaches();
-		framesProcessed++;
+		src=fbkevent.getSource();
+		refresh();
 	} else {
 		EventGeneratorBase::processEvent(event);
 	}
@@ -102,19 +105,26 @@
 	destruct();
 	numLayers=nLayers;
 	numChannels=nChannels;
+	
 	widths=new unsigned int[numLayers];
 	heights=new unsigned int[numLayers];
+	if(numLayers>0) {
+		for(unsigned int res=0; res<numLayers-1; res++) {
+			widths[res] = CameraResolutionX>>(numLayers-2-res);
+			heights[res] = CameraResolutionY>>(numLayers-2-res);
+		}
+		widths[numLayers-1]=CameraResolutionX*2;
+		heights[numLayers-1]=CameraResolutionY*2;
+	}
+
 	skips=new unsigned int[numLayers];
 	strides=new unsigned int[numLayers];
 	increments=new unsigned int[numLayers];
-	for(unsigned int res=0; res<numLayers; res++) {
-		widths[res]=heights[res]=skips[res]=strides[res]=0;
-		increments[res]=1;
-	}
 	images=new unsigned char**[numLayers];
 	imageValids=new bool*[numLayers];
 	for(unsigned int i=0; i<numLayers; i++) {
-		widths[i]=heights[i]=0;
+		skips[i]=strides[i]=0;
+		increments[i]=1;
 		images[i]=new unsigned char*[numChannels];
 		imageValids[i]=new bool[numChannels];
 		for(unsigned int j=0; j<numChannels; j++) {
@@ -157,6 +167,37 @@
 	numLayers=numChannels=0;
 }
 
+bool FilterBankGenerator::refresh() {
+	if(sysFrameNumber==-1U) {
+		serr->printf("ERROR: attempted access to camera image before any data was available\n");
+		return false;
+	}
+	if(frameNumber==sysFrameNumber)
+		return true;
+	if(src==NULL) {
+		serr->printf("ERROR: attempted access to camera image before stage had a known source\n");
+		return false;
+	}
+	if(!src->refresh())
+		return false;
+	if(frameNumber==src->getFrameNumber())
+		return true;
+	frameNumber=src->getFrameNumber();
+	setNumImages(src->getNumLayers(),src->getNumChannels());
+	if(numLayers<=0 || numChannels<=0) {
+		serr->printf("ERROR: attempted to access image in empty FilterBankGenerator\n");
+		return false;
+	}
+	if(src->getWidth(numLayers-1)!=getWidth(numLayers-1) || src->getHeight(numLayers-1)!=getHeight(numLayers-1)) {
+		serr->printf("WARNING: the image dimensions don't match values predicted by RobotInfo consts, now %dx%d",widths[numLayers-1],heights[numLayers-1]);
+		setDimensions();
+	} else if(framesProcessed==0) {
+		setDimensions();
+	}
+	invalidateCaches();
+	framesProcessed++;
+	return true;
+}
 
 
 /*! @file
@@ -164,9 +205,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/07/06 22:49:22 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/FilterBankGenerator.h ./Vision/FilterBankGenerator.h
--- ../Tekkotsu_2.3/Vision/FilterBankGenerator.h	Mon Dec 20 16:47:59 2004
+++ ./Vision/FilterBankGenerator.h	Sun Aug  7 00:11:04 2005
@@ -141,7 +141,7 @@
 	
 	//! returns pointer to the beginning of the image data for the specified layer and channel
 	/*! this will cause the data to be calculated and cached if it's not already available */
-	virtual unsigned char * getImage(unsigned int layer, unsigned int channel) const;
+	virtual unsigned char * getImage(unsigned int layer, unsigned int channel);
 
 	//! returns width (in samples) of the image in a given layer
 	unsigned int getWidth(unsigned int layer) const { return widths[layer]; }
@@ -165,6 +165,59 @@
 	//! returns the number of frames processed, see #framesProcessed
 	unsigned int getFramesProcessed() const { return framesProcessed; }
 	
+	//! returns a pointer to a particular sample; if you are using this in an inner loop, consider using the getSkip() and getIncrement() values to iterate with better performance
+	/*! @param px      the horizontal pizel position, relative to left edge; no boundary checking is done, ranges 0 through width-1
+	 *  @param py      the vertical pixel position, relative to top edge; no boundary checking is done, ranges 0 through height-1
+	 *  @param layer   the resolution layer to extract from
+	 *  @param channel the image channel to extract from */
+	unsigned char * getPixel(unsigned int px, unsigned int py, unsigned int layer, unsigned int channel) { return getImage(layer,channel)+py*getStride(layer)+px*getIncrement(layer); }
+	
+	//! returns a pointer to a particular sample; if you are using this in an inner loop, consider using the getSkip() and getIncrement() values to iterate with better performance
+	/*! @param x       the horizontal position, relative to center of the image, left edge is -1 and right edge is 1; no boundary checking is done
+	 *  @param y       the vertical pixel position, relative to center of the image, top edge is the negative aspect ratio, bottom edge is positive aspect ratio; no boundary checking is done
+	 *  @param layer   the resolution layer to extract from
+	 *  @param channel the image channel to extract from
+	 *
+	 *  To keep the coordinate system square, the x is defined to range -1,1, but y's range depends on the
+	 *  aspect ratio of the image, height/width.  Thus typically y will approx. -.75,.75 */
+	unsigned char * getPixel(float x, float y, unsigned int layer, unsigned int channel) {
+		unsigned int px,py;
+		getPixelCoordinates(px,py,x,y,layer);
+		return getPixel(px,py,layer,channel);
+	}
+
+	//! sets the pixel-coordinate px and py parameters to the corresponding value of x and y
+	/*! @param[out] px      the pixel position, relative to left edge, positive right, ranges 0 through width-1
+	 *  @param[out] py      the pixel position, relative to top edge, positive down, ranges 0 through height-1
+	 *  @param[in]  x       the horizontal position, relative to center of the image, left edge is -1 and right edge is 1; no boundary checking is done
+	 *  @param[in]  y       the vertical pixel position, relative to center of the image, top edge is the negative aspect ratio, bottom edge is positive aspect ratio; no boundary checking is done
+	 *  @param[in]  layer   the resolution layer the pixel coordinates are relative to
+	 *
+	 *  To keep the coordinate system square, the x is defined to range -1,1, but y's range depends on the
+	 *  aspect ratio of the image, height/width.  Thus typically y will approx. -.75,.75 */
+	void getPixelCoordinates(unsigned int& px, unsigned int& py, float x, float y, unsigned int layer) const {
+		//note width sets the scale for both, so coordinate system is square... is good? I'm up for debate.
+		px=(unsigned int)((getWidth(layer)-1)*(x+1)/2+.5f); //+.5 to round to nearest
+		float aspect=getHeight(layer)/(float)getWidth(layer);
+		py=(unsigned int)((getHeight(layer)-1)*(y+aspect)/(aspect*2)+.5f);
+	}
+	
+	//! sets the x and y parameters from the pixel-coordinates px and py
+	/*! @param[out] x       the horizontal position, relative to center of the image, left edge is -1 and right edge is 1; no boundary checking is done
+	 *  @param[out] y       the vertical pixel position, relative to center of the image, top edge is the negative aspect ratio, bottom edge is positive aspect ratio; no boundary checking is done
+	 *  @param[in]  px      the pixel position, relative to left edge, positive right, ranges 0 through width-1
+	 *  @param[in]  py      the pixel position, relative to top edge, positive down, ranges 0 through height-1
+	 *  @param[in]  layer   the resolution layer the pixel coordinates are relative to
+	 *
+	 *  To keep the coordinate system square, the x is defined to range -1,1, but y's range depends on the
+	 *  aspect ratio of the image, height/width.  Thus typically y will approx. -.75,.75 */
+	void getRealCoordinates(float& x, float& y, unsigned int px, unsigned int py, unsigned int layer) const {
+		//note width sets the scale for both, so coordinate system is square... is good? I'm up for debate.
+		x=px/(float)(getWidth(layer)-1)*2-1;
+		float aspect=getHeight(layer)/(float)getWidth(layer);
+		y=py/(float)(getHeight(layer)-1)*aspect*2-aspect;
+	}
+	
 	//! deletes storage of cached images and marks it invalid
 	/*! you should override this if the images cache pointer isn't actually an array of bytes... 
 	 *  Don't forget to call it in your subclass's destructor or your version won't get called... */
@@ -192,9 +245,12 @@
 
 	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
 
-	//! not actually part of the LoadSave interface, but allows you to select which image of the bank will be saved
-	/*! when loading, the saved image's layer and channel will reset this */
-	virtual void selectSaveImage(unsigned int layer, unsigned int channel) { selectedSaveLayer=layer; selectedSaveChannel=channel; }
+	//! Not actually part of the LoadSave interface, but allows you to select which image of the bank will be saved
+	/*! Calling this will also cause the image data for that image to be calculated,
+	 *  otherwise SaveBuffer won't have up-to-date data to save.
+	 *  
+	 *  When loading, the saved image's layer and channel will reset this */
+	virtual void selectSaveImage(unsigned int layer, unsigned int channel) { selectedSaveLayer=layer; selectedSaveChannel=channel; getImage(layer,channel);}
 
 	virtual unsigned int getSelectedSaveLayer() const { return selectedSaveLayer; } //!< returns layer to be saved, or layer of last image loaded
 	virtual unsigned int getSelectedSaveChannel() const { return selectedSaveChannel; } //!< returns channel to be saved, or channel of last image loaded
@@ -203,16 +259,44 @@
 
 
 protected:
-	//! constructor, @a name is both class and instance name
-	FilterBankGenerator(const std::string& name,EventBase::EventGeneratorID_t srcgid, unsigned int srcsid, EventBase::EventGeneratorID_t mgid, unsigned int msid)
-		: EventGeneratorBase(name,mgid,msid,srcgid,srcsid), src(NULL), numLayers(0), numChannels(0), widths(NULL), heights(NULL), skips(NULL), strides(NULL), increments(NULL), images(NULL), imageValids(NULL), selectedSaveLayer(0), selectedSaveChannel(0), frameNumber(0), framesProcessed(0)
+	//! constructor, separate class and instance names, with a raw event specification, excluding type typically for stages which reference the previous stage's data
+	FilterBankGenerator(const std::string& classname,const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid, EventBase::EventGeneratorID_t srcegid, unsigned int srcsrc)
+		: EventGeneratorBase(classname, instancename, mgid, msid, srcegid, srcsrc),
+			src(NULL), numLayers(0), numChannels(0), widths(NULL), heights(NULL), skips(NULL),
+			strides(NULL), increments(NULL), images(NULL), imageValids(NULL), selectedSaveLayer(0),
+			selectedSaveChannel(0), frameNumber(0), framesProcessed(0)
 	{ }
 
-	//! constructor, separate class and instance names
-	FilterBankGenerator(const std::string& classname,const std::string& instancename,EventBase::EventGeneratorID_t srcgid, unsigned int srcsid, EventBase::EventGeneratorID_t mgid, unsigned int msid)
-		: EventGeneratorBase(classname,instancename,mgid,msid,srcgid,srcsid), src(NULL), numLayers(0), numChannels(0), widths(NULL), heights(NULL), skips(NULL), strides(NULL), increments(NULL), images(NULL), imageValids(NULL), selectedSaveLayer(0), selectedSaveChannel(0), frameNumber(0), framesProcessed(0)
+	//! constructor, separate class and instance names, with a raw event specification, including type typically for stages which will store their own copy of the data
+	FilterBankGenerator(const std::string& classname,const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid, EventBase::EventGeneratorID_t srcegid, unsigned int srcsrc, EventBase::EventTypeID_t srcetid)
+		: EventGeneratorBase(classname, instancename, mgid, msid, srcegid, srcsrc, srcetid),
+			src(NULL), numLayers(0), numChannels(0), widths(NULL), heights(NULL), skips(NULL),
+			strides(NULL), increments(NULL), images(NULL), imageValids(NULL), selectedSaveLayer(0),
+			selectedSaveChannel(0), frameNumber(0), framesProcessed(0)
 	{ }
 
+	//! constructor, separate class and instance names, with a filter bank source, passes on all types typically for stages which reference the previous stage's data
+	FilterBankGenerator(const std::string& classname,const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid, FilterBankGenerator * fbgsrc)
+		: EventGeneratorBase(classname, instancename, mgid, msid, fbgsrc!=NULL?fbgsrc->getGeneratorID():EventBase::numEGIDs, fbgsrc!=NULL?fbgsrc->getSourceID():0),
+			src(fbgsrc), numLayers(0), numChannels(0), widths(NULL), heights(NULL), skips(NULL),
+			strides(NULL), increments(NULL), images(NULL), imageValids(NULL), selectedSaveLayer(0),
+			selectedSaveChannel(0), frameNumber(0), framesProcessed(0)
+	{
+		if(src!=NULL)
+			setNumImages(src->getNumLayers(),src->getNumChannels());
+	}
+
+	//! constructor, separate class and instance names, with a filter bank source, accepts a particular type typically for stages which will store their own data
+	FilterBankGenerator(const std::string& classname,const std::string& instancename, EventBase::EventGeneratorID_t mgid, unsigned int msid, FilterBankGenerator * fbgsrc, EventBase::EventTypeID_t etid)
+		: EventGeneratorBase(classname, instancename, mgid, msid, fbgsrc!=NULL?fbgsrc->getGeneratorID():EventBase::numEGIDs, fbgsrc!=NULL?fbgsrc->getSourceID():0,etid),
+			src(fbgsrc), numLayers(0), numChannels(0), widths(NULL), heights(NULL), skips(NULL),
+			strides(NULL), increments(NULL), images(NULL), imageValids(NULL), selectedSaveLayer(0),
+			selectedSaveChannel(0), frameNumber(0), framesProcessed(0)
+	{
+		if(src!=NULL)
+			setNumImages(src->getNumLayers(),src->getNumChannels());
+	}
+
 	//! resizes the filter bank information storage area, you should override this to do your setup and call it from your constructor
 	/*! In general, it isn't expected that FilterBankGenerator's should
 	 *  necessarily be dynamically resizeable (although it would be
@@ -227,7 +311,7 @@
 	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
 
 	//! resets width and height parameters to that of the #src
-	/*! You'll probably want to override this to also set #skip and #stride */
+	/*! You'll probably want to override this to also set #skips and #strides */
 	virtual void setDimensions();
 	
 	//! create new image data storage area for the cache - this called by getImage() only when the corresponding entry in images is NULL
@@ -239,12 +323,22 @@
 
 	//! should calculate new image data, called by getImage() only when #imageValids indicates the image being requested is dirty (and only after getImage() has already called createImageCache())
 	/*! This is where you'll want to put your user-specific code for calculating the image data */
-	virtual void calcImage(unsigned int layer, unsigned int channel) const=0;
+	virtual void calcImage(unsigned int layer, unsigned int channel) =0;
 
 	//! deletes the arrays
 	virtual void destruct();
 
-	const FilterBankGenerator * src; //!< the generator of the last FilterBankEvent received
+	//! updates the image data to make sure its up to date with what's available from the source
+	/*! If someone calls getImage on a stage which hadn't been listening for
+	 *  events (an optimization to save time when it doesn't have any listeners
+	 *  of its own -- see EventGeneratorBase), then this will retroactively
+	 *  pull image data from the source even though the event for it was missed
+	 *
+	 *  @return false if no image data is available yet, true otherwise*/
+	virtual bool refresh();
+
+
+	FilterBankGenerator * src; //!< the generator of the last FilterBankEvent received
 
 	unsigned int numLayers;   //!< current number of layers available
 	unsigned int numChannels; //!< current number of channels available
@@ -261,7 +355,7 @@
 	unsigned int selectedSaveLayer;   //!< layer to be manipulated with the LoadSave functions
 	unsigned int selectedSaveChannel; //!< channel to be manipulated with the LoadSave functions
 
-	//! the current frame number - subclasses will need to set to the source's frameNumber when they receive a new frame (probably from processEvent())	
+	//! the frame number of last frame received by processEvent - subclasses will need to set to the source's frameNumber if they don't call FilterBankGenerator::processEvent()
 	/*! The idea is to use this as a unique serial number for each
 	 *	frame.  That way you can know if the current image in different
 	 *	generators is actually the same camera image before you try to
@@ -269,11 +363,15 @@
 	 *
 	 *  You could also figure out the number of dropped frames by
 	 *  subtracting framesProcessed from this value.  Give some leeway
-	 *  however, because it takes the first 40-70 frames just to boot
-	 *  up, so there's no way they can be processed.
+	 *  however, because it takes the first 40-70 frames just to boot up
+	 *  (when running on the aibo), so there's no way they can be
+	 *  processed.
 	 */
 	unsigned int frameNumber; 
 
+	//! the current frame number available from the system - subclasses which receive data directly from the system should set this (and should not use EventGeneratorBase's auto-listen to ensure this is accurate)
+	static unsigned int sysFrameNumber;
+
 	//! subclasses should increment this any time they make a new filter bank available
 	/*! this is automatically incremented if you use the FilterBankGenerator::processEvent() */
 	unsigned int framesProcessed; 
@@ -288,10 +386,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.15 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.18 $
  * $State: Exp $
- * $Date: 2004/12/20 21:47:59 $
+ * $Date: 2005/08/07 04:11:04 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/Graphics.cc ./Vision/Graphics.cc
--- ../Tekkotsu_2.3/Vision/Graphics.cc	Wed Dec 31 19:00:00 1969
+++ ./Vision/Graphics.cc	Sun Jul 10 16:02:39 2005
@@ -0,0 +1,247 @@
+#include "Graphics.h"
+#include "FilterBankGenerator.h"
+
+using namespace std;
+
+//! empty definition of macro for checking for any exceeding of image's memory boundaries
+//#define CHKBOUNDS(p) {}
+
+// ! check memory boundaries of image, first that we are after the start of the image, second that we are before the end of the image, and third that we are within a valid row (in case of interleaved rows), fourth that we are within a valid column (interleaved pixels)
+#define CHKBOUNDS(p,ERR_F) { \
+	unsigned int rowoffset=(p-img)-(p-img)/yInc*yInc; \
+	if(p<img || p>=img+w*xInc+h*yInc || rowoffset>=w*xInc || rowoffset/xInc*xInc!=rowoffset) { \
+		cout << "Graphics Bad draw! line:" << __LINE__ << " frame=" << (gen!=NULL?gen->getFrameNumber():0) << ' '  /*<< (void*)p << '-' << (void*)img << '='*/ << (int)(p-img) << " w=" << w << " xInc=" << xInc << " h=" << h << " yInc=" << yInc << endl; \
+		ERR_F; \
+	} \
+}
+
+
+Graphics::Graphics(FilterBankGenerator& fbg, unsigned int layer, unsigned int channel)
+	: gen(&fbg), genLayer(layer), genChan(channel), img(NULL), w(0), h(0), xInc(0), yInc(0), c(0)
+{
+	updateFBG();
+}
+
+Graphics::Graphics(unsigned char * base, unsigned int width, unsigned int height, unsigned int interval, unsigned int stride)
+	: gen(NULL), genLayer(), genChan(), img(base), w(width), h(height), xInc(interval), yInc(stride), c(0)
+{}
+
+void Graphics::updateFBG() {
+	if(gen==NULL)
+		return;
+	img=gen->getImage(genLayer,genChan);
+	w=gen->getWidth(genLayer);
+	h=gen->getHeight(genLayer);
+	xInc=gen->getIncrement(genLayer);
+	yInc=gen->getStride(genLayer);
+}
+
+void Graphics::drawRect(int x, int y, int width, int height) {
+	if(img==NULL)
+		return;
+	if(width<0) {
+		x+=width;
+		width=-width;
+	}
+	if(height<0) {
+		y+=height;
+		height=-height;
+	}
+	if(x>=(int)w || y>=(int)h || x+width<0 || y+height<0) //completely out of bounds
+		return;
+	if(x<0 && y<0 && x+width>=(int)w && y+height>=(int)h) //out of bounds (circumscribed)
+		return;
+	unsigned int left=x>0?x:0;
+	unsigned int top=y>0?y:0;
+	unsigned int right=x+width>=(int)w?w:x+width; //not inclusive
+	unsigned int bot=y+height>=(int)h?h:y+height; //not inclusive
+	//left vertical
+	if(x>=0) {
+		unsigned char * p=img+top*yInc+left*xInc;
+		unsigned char * end=img+bot*yInc+left*xInc;
+		while(p!=end) {
+			CHKBOUNDS(p,return);
+			*p=c;
+			p+=yInc;
+		}
+	}		
+	//top horizontal
+	if(y>=0) {
+		unsigned char * p=img+top*yInc+left*xInc;
+		unsigned char * end=img+top*yInc+right*xInc;
+		while(p!=end) {
+			CHKBOUNDS(p,return);
+			*p=c;
+			p+=xInc;
+		}
+	}
+	//right vertical
+	if(right<w && left!=right) {
+		unsigned char * p=img+top*yInc+right*xInc;
+		unsigned char * end=img+bot*yInc+right*xInc;
+		while(p!=end) {
+			CHKBOUNDS(p,return);
+			*p=c;
+			p+=yInc;
+		}
+	}		
+	//bottom horizontal
+	if(bot<h && top!=bot) {
+		unsigned char * p=img+bot*yInc+left*xInc;
+		unsigned char * end=img+bot*yInc+right*xInc;
+		while(p!=end) {
+			CHKBOUNDS(p,return);
+			*p=c;
+			p+=xInc;
+		}
+	}
+	//bottom right corner
+	if((unsigned int)right<w && (unsigned int)bot<h) {
+		unsigned char * p=img+bot*yInc+right*xInc;
+		CHKBOUNDS(p,return);
+		*p=c;
+		return;
+	}
+}
+void Graphics::drawRect(float x, float y, float width, float height) {
+	unsigned int left,top,right,bot;
+	getPixelCoordinates(left,top,x,y);
+	getPixelCoordinates(right,bot,x+width,y+height);
+	drawRect((int)left,(int)top,(int)(right-left),(int)(bot-top));
+}
+
+/*! @todo I think this could be a little faster by writing two cases -- one that
+ *  handles mostly-vertical lines, and one that handles mostly-horizontal ones.
+ *  Then the primary loop could be over integer coordinates along that axis, and
+ *  only the position along the other axis would have to be calculated as
+ *  floating point */
+void Graphics::drawLine(int ix1, int iy1, int ix2, int iy2) {
+	// the "right" way, allows full range of unsigned int for width
+	//if(ix1<0 && ix2<0 || iy1<0 && iy2<0 || ix1>0 && ix2>0 && (unsigned int)ix1>=w && (unsigned int)ix2>=w || iy1>0 && iy2>0 && (unsigned int)iy1>=h && (unsigned int)iy2>=h)
+	//  return; //completely outside visible region
+
+	// the "realistic way" saves some CPU
+	if(ix1<0 && ix2<0 || iy1<0 && iy2<0 || ix1>=(int)w && ix2>=(int)w || iy1>=(int)h && iy2>=(int)h)
+		return; //completely outside visible region
+
+	float x1=ix1, y1=iy1, x2=ix2, y2=iy2;
+	float width=x2-x1;
+	float height=y2-y1;
+	bool clipped=false;
+	if(width!=0) {
+		float slope=height/width;
+		if(x1<x2) {
+			if(x1<0) {
+				y1-=x1*slope;
+				x1=0;
+				clipped=true;
+			}
+			if(x2>=w) {
+				y2-=(x2-(w-1))*slope;
+				x2=w-1;
+				clipped=true;
+			}
+		} else {
+			if(x2<0) {
+				y2-=x2*slope;
+				x2=0;
+				clipped=true;
+			}
+			if(x1>=w) {
+				y1-=(x1-(w-1))*slope;
+				x1=w-1;
+				clipped=true;
+			}
+		}
+	}
+	if(clipped) {
+		if(x1<0 && x2<0 || y1<0 && y2<0 || x1>=w && x2>=w || y1>=h && y2>=h)
+			return; //completely outside visible region
+		clipped=false;
+	}
+	if(height!=0) {
+		float invslope=width/height;
+		if(y1<y2) {
+			if(y1<0) {
+				x1-=y1*invslope;
+				y1=0;
+				clipped=true;
+			}
+			if(y2>=h) {
+				x2-=(y2-(h-1))*invslope;
+				y2=h-1;
+				clipped=true;
+			}
+		} else {
+			if(y2<0) {
+				x2-=y2*invslope;
+				y2=0;
+				clipped=true;
+			}
+			if(y1>=h) {
+				x1-=(y1-(h-1))*invslope;
+				y1=h-1;
+				clipped=true;
+			}
+		}
+	}
+	if(clipped) {
+		if(x1<0 && x2<0 || y1<0 && y2<0 || x1>=w && x2>=w || y1>=h && y2>=h)
+			return; //completely outside visible region
+		clipped=false;
+	}
+	width=x2-x1;
+	height=y2-y1;
+	int aw=abs((int)width);
+	int ah=abs((int)height);
+	int d=aw>ah?aw:ah;
+	float dx=width/d;
+	float dy=height/d;
+	for(float x=x1,y=y1;d>0;d--,x+=dx,y+=dy) {
+		unsigned char * p=(img+((int)y)*yInc+((int)x)*xInc);
+		CHKBOUNDS(p,continue);
+		*p=c;
+	}
+	unsigned char * p=(img+((int)y2)*yInc+((int)x2)*xInc);
+	CHKBOUNDS(p,return);
+	*p=c;
+}
+void Graphics::drawLine(float x1, float y1, float x2, float y2) {
+	unsigned int px1,py1,px2,py2;
+	getPixelCoordinates(px1,py1,x1,y1);
+	getPixelCoordinates(px2,py2,x2,y2);
+	drawLine((int)px1,(int)py1,(int)px2,(int)py2);
+}
+
+void Graphics::getPixelCoordinates(unsigned int& px, unsigned int& py, float x, float y) const {
+	if(gen!=NULL) {
+		gen->getPixelCoordinates(px,py,x,y,genLayer);
+	} else {
+		//note width sets the scale for both, so coordinate system is square... is good? I'm up for debate.
+		px=(unsigned int)((w-1)*(x+1)/2+.5f); //+.5 to round to nearest
+		float aspect=h/(float)w;
+		py=(unsigned int)((h-1)*(y+aspect)/(aspect*2)+.5f); //+.5 to round to nearest
+	}
+}
+	
+void Graphics::getRealCoordinates(float& x, float& y, unsigned int px, unsigned int py) const {
+	if(gen!=NULL) {
+		gen->getRealCoordinates(x,y,px,py,genLayer);
+	} else {
+		//note width sets the scale for both, so coordinate system is square... is good? I'm up for debate.
+		x=px/(float)(w-1)*2-1;
+		float aspect=h/(float)w;
+		y=py/(float)(h-1)*aspect*2-aspect;
+	}
+}
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/07/10 20:02:39 $
+ */
diff -urdN ../Tekkotsu_2.3/Vision/Graphics.h ./Vision/Graphics.h
--- ../Tekkotsu_2.3/Vision/Graphics.h	Wed Dec 31 19:00:00 1969
+++ ./Vision/Graphics.h	Sun Aug  7 00:11:04 2005
@@ -0,0 +1,127 @@
+//-*-c++-*-
+#ifndef INCLUDED_Graphics_h_
+#define INCLUDED_Graphics_h_
+
+class FilterBankGenerator;
+
+//! Provides basic graphics capabilities for drawing into any bitmap, particularly FilterBankGenerators
+/*! Wherever possible, this should try to emulate the graphics API of Java 1 to minimize learning curve.
+ *  For instance, the pen hangs down and to the right. */
+class Graphics {
+public:
+	//! constructor, pass a FilterBankGenerator and layer/channel to draw into
+	Graphics(FilterBankGenerator& fbg, unsigned int layer, unsigned int channel);
+	//! constructor, directly specify an image buffer
+	Graphics(unsigned char * base, unsigned int width, unsigned int height, unsigned int interval, unsigned int stride);
+
+	//! If you want to reuse a graphics object across multiple frames from a FilterBankGenerator, call this after each new frame, but before you do any drawing
+	/*! This is automatically called by the constructor, so you don't need to do it if you
+	 *  constructor a fresh Graphics object for each frame.  But otherwise you'll need this
+	 *  to update #img, #w, #h, #xInc, and #yInc from the current frame available in #gen */
+	void updateFBG(); 
+
+	//! Draws a rectange, upper left at @a x,@a y and extending right and down by @a width and @a height
+	/*! This expects direct-pixel coordinates, so make sure you check the
+	 *  width and height of the layer you are drawing into */
+	void drawRect(int x, int y, int width, int height);
+	//! Draws a rectange, upper left at @a x,@a y and extending right and down by @a width and @a height
+	/*  This expects resolution independent coordinates, such that
+	 *  x ranges [-1,1] and y ranges plus/minus the aspect ratio */
+	void drawRect(float x, float y, float width, float height);
+
+	//! Draws a line from (@a x1, @a y1) to (@a x2, @a y2)
+	/*! This expects direct-pixel coordinates, so make sure you check the
+	 *  width and height of the layer you are drawing into */
+	void drawLine(int x1, int y1, int x2, int y2);
+	//! Draws a line from (@a x1, @a y1) to (@a x2, @a y2)
+	/*  This expects resolution independent coordinates, such that
+	 *  x ranges [-1,1] and y ranges plus/minus the aspect ratio */
+	void drawLine(float x1, float y1, float x2, float y2);
+
+	//! Draws a single point at (@a x1, @a y1)
+	/*! This expects direct-pixel coordinates, so make sure you check the
+	 *  width and height of the layer you are drawing into */
+	inline void drawPoint(int x, int y) {
+		if(x<0 || y<0 || (unsigned int)x>=w || (unsigned int)y>=h)
+			return;
+		*(img+y*yInc+x*xInc)=c;
+	}
+	//! Draws a single point at (@a x1, @a y1)
+	/*  This expects resolution independent coordinates, such that
+	 *  x ranges [-1,1] and y ranges plus/minus the aspect ratio */
+	void drawPoint(float x, float y) {
+		unsigned int px,py;
+		getPixelCoordinates(px,py,x,y);
+		drawPoint((int)px,(int)py);
+	}
+
+	//! Sets the "color" of the pen
+	/*! Currently we don't support multi-channel drawing, so you have to draw into
+	 *  each channel separately to do real color based drawing, but maybe someday
+	 *  we'll add a color class.\n
+	 *  In the mean time, this is just the byte that's going to be used to fill in
+	 *  wherever the pen traces */
+	void setColor(char color) { c=color; }
+	//! returns the "color" of the pen
+	/*! Currently we don't support multi-channel drawing, so you have to draw into
+	 *  each channel separately to do real color based drawing, but maybe someday
+	 *  we'll add a color class.\n
+	 *  In the mean time, this is just the byte that's going to be used to fill in
+	 *  wherever the pen traces */
+	char getColor() const { return c; }
+
+	//! sets the pixel-coordinate px and py parameters to the corresponding value of x and y
+	/*! @param[out] px      the pixel position, relative to left edge, positive right, ranges 0 through width-1
+	 *  @param[out] py      the pixel position, relative to top edge, positive down, ranges 0 through height-1
+	 *  @param[in]  x       the horizontal position, relative to center of the image, left edge is -1 and right edge is 1; no boundary checking is done
+	 *  @param[in]  y       the vertical pixel position, relative to center of the image, top edge is the negative aspect ratio, bottom edge is positive aspect ratio; no boundary checking is done
+	 *
+	 *  To keep the coordinate system square, the x is defined to range -1,1, but y's range depends on the
+	 *  aspect ratio of the image, height/width.  Thus typically y will approx. -.75,.75 */
+	void getPixelCoordinates(unsigned int& px, unsigned int& py, float x, float y) const;
+	
+	//! sets the x and y parameters from the pixel-coordinates px and py
+	/*! @param[out] x       the horizontal position, relative to center of the image, left edge is -1 and right edge is 1; no boundary checking is done
+	 *  @param[out] y       the vertical pixel position, relative to center of the image, top edge is the negative aspect ratio, bottom edge is positive aspect ratio; no boundary checking is done
+	 *  @param[in]  px      the pixel position, relative to left edge, positive right, ranges 0 through width-1
+	 *  @param[in]  py      the pixel position, relative to top edge, positive down, ranges 0 through height-1
+	 *
+	 *  To keep the coordinate system square, the x is defined to range -1,1, but y's range depends on the
+	 *  aspect ratio of the image, height/width.  Thus typically y will approx. -.75,.75 */
+	void getRealCoordinates(float& x, float& y, unsigned int px, unsigned int py) const;
+	
+protected:
+	FilterBankGenerator * gen; //!< the filter bank generator we are drawing into, or NULL
+	unsigned int genLayer; //!< the layer within #gen we are drawing into
+	unsigned int genChan; //!< the channel within #gen we are drawing into
+
+	unsigned char * img; //!< the image we are currently drawing into (may need to be updated if #gen is non-NULL, see updateFBG())
+	unsigned int w; //!< the width of #img
+	unsigned int h; //!< the height of #img
+	unsigned int xInc; //!< the number of bytes to skip to move horizontally one pixel in #img
+	unsigned int yInc; //!< the number of bytes to skip to move vertically one pixel in #img
+
+	unsigned char c; //!< the current pen color
+
+private:
+	// Providing declarations for these functions will avoid a compiler warning if
+	// you have any class members which are pointers.  However, as it is, an error
+	// will result if you inadvertantly cause a call to either (which is probably
+	// a good thing, unless you really intended to copy/assign a behavior, in
+	// which case simply provide implementations for the functions)
+	Graphics(const Graphics&); //!< don't call (copy constructor)
+	Graphics& operator=(const Graphics&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/08/07 04:11:04 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/Vision/InterleavedYUVGenerator.cc ./Vision/InterleavedYUVGenerator.cc
--- ../Tekkotsu_2.3/Vision/InterleavedYUVGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/InterleavedYUVGenerator.cc	Fri Aug  5 17:56:04 2005
@@ -6,19 +6,34 @@
 
 #include "Shared/debuget.h"
 
-InterleavedYUVGenerator::InterleavedYUVGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid)
-	: FilterBankGenerator("InterleavedYUVGenerator",gid,sid,EventBase::visInterleaveEGID,mysid), srcYChan(0), srcUChan(1), srcVChan(2)
-{ }
+InterleavedYUVGenerator::InterleavedYUVGenerator(unsigned int mysid,FilterBankGenerator* fbg, EventBase::EventTypeID_t tid)
+	: FilterBankGenerator("InterleavedYUVGenerator","InterleavedYUVGenerator",EventBase::visInterleaveEGID,mysid,fbg,tid), srcYChan(0), srcUChan(1), srcVChan(2), isAllocated(NULL)
+{
+	//this part is only necessary if you override setNumImages yourself
+	if(fbg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(fbg->getNumLayers(),fbg->getNumChannels()); //channels gets overridden to '1' in setNumImages
+	}
+}
 
-InterleavedYUVGenerator::InterleavedYUVGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, unsigned int syc, unsigned int suc, unsigned int svc)
-	: FilterBankGenerator("InterleavedYUVGenerator",gid,sid,EventBase::visInterleaveEGID,mysid), srcYChan(syc), srcUChan(suc), srcVChan(svc)
-{ }
+InterleavedYUVGenerator::InterleavedYUVGenerator(unsigned int mysid, unsigned int syc, unsigned int suc, unsigned int svc,FilterBankGenerator* fbg, EventBase::EventTypeID_t tid)
+	: FilterBankGenerator("InterleavedYUVGenerator","InterleavedYUVGenerator",EventBase::visInterleaveEGID,mysid,fbg,tid), srcYChan(syc), srcUChan(suc), srcVChan(svc), isAllocated(NULL)
+{
+	//this part is only necessary if you override setNumImages yourself
+	if(fbg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(fbg->getNumLayers(),fbg->getNumChannels()); //channels gets overridden to '1' in setNumImages
+	}
+}
 
 void
 InterleavedYUVGenerator::processEvent(const EventBase& event) {
 	FilterBankGenerator::processEvent(event);
-	if(event.getGeneratorID()==getListenGeneratorID() && event.getSourceID()==getListenSourceID())
-		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID()));
+	if(event.getGeneratorID()==getListenGeneratorID() && event.getSourceID()==getListenSourceID()) {
+		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::activateETID));
+		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::statusETID));
+		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::deactivateETID));
+	}
 }
 
 unsigned int
@@ -69,7 +84,15 @@
 	used=widths[selectedSaveLayer]*heights[selectedSaveLayer]*3;
 	if(used>len)
 		return 0;
-	unsigned char* img=getImage(selectedSaveLayer,selectedSaveChannel);
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("InterleavedYUVGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("InterleavedYUVGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
 	if(img==NULL)
 		return 0;
 	memcpy(buf,img,used);
@@ -85,27 +108,71 @@
 }
 
 void
+InterleavedYUVGenerator::destruct() {
+	FilterBankGenerator::destruct();
+	for(unsigned int i=0; i<numLayers; i++)
+		delete [] isAllocated[i];
+	delete [] isAllocated;
+	isAllocated=NULL;
+}
+
+void
 InterleavedYUVGenerator::setNumImages(unsigned int nLayers, unsigned int nChannels) {
 	if(nLayers==numLayers && nChannels==numChannels)
 		return;
 	FilterBankGenerator::setNumImages(nLayers,1);
-	for(unsigned int res=0; res<numLayers; res++)
+	isAllocated=new bool*[numLayers];
+	for(unsigned int res=0; res<numLayers; res++) {
 		increments[res]=3;
+		isAllocated[res]=new bool[numChannels];
+		for(unsigned int c=0; c<numChannels; c++)
+			isAllocated[res][c]=false;
+	}
+}
+
+void
+InterleavedYUVGenerator::freeCaches() {
+	FilterBankGenerator::freeCaches();
+	for(unsigned int i=0; i<numChannels; i++)
+		for(unsigned int j=0; j<numLayers; j++)
+			isAllocated[i][j]=false;
+}
+
+void
+InterleavedYUVGenerator::invalidateCaches() {
+	for(unsigned int i=0; i<numLayers; i++)
+		for(unsigned int j=0; j<numChannels; j++) {
+			if(!isAllocated[i][j])
+				images[i][j]=NULL;
+			imageValids[i][j]=false;
+		}
 }
 
 unsigned char *
-InterleavedYUVGenerator::createImageCache(unsigned int layer, unsigned int /*chan*/) const {
-	return new unsigned char[widths[layer]*heights[layer]*3];
+InterleavedYUVGenerator::createImageCache(unsigned int layer, unsigned int chan) const {
+	if(src->getStride(layer)==getStride(layer) && src->getIncrement(layer)==getIncrement(layer)) {
+		//already interleaved, pass through
+		ASSERT(!isAllocated[layer][chan],"pass through over allocated image!")
+		imageValids[layer][chan]=true;
+		return src->getImage(layer,srcYChan);
+	} else {
+		isAllocated[layer][chan]=true;
+		return new unsigned char[widths[layer]*heights[layer]*3];
+	}
 }
 
 void
-InterleavedYUVGenerator::calcImage(unsigned int layer, unsigned int chan) const {
+InterleavedYUVGenerator::calcImage(unsigned int layer, unsigned int chan) {
 	PROFSECTION("InterleavedYUVGenerator::calcImage(...)",state->mainProfile);
+	if(imageValids[layer][chan]) //check if createCache set valid flag
+		return; //indicates pass through from previous stage
+	
 	unsigned char* dimg=images[layer][chan];
 	const unsigned char* syimg=src->getImage(layer,srcYChan);
 	const unsigned char* suimg=src->getImage(layer,srcUChan);
 	const unsigned char* svimg=src->getImage(layer,srcVChan);
 	const unsigned int inc=src->getIncrement(layer);
+	const unsigned int skip=src->getSkip(layer);
 	//std::cout << src->getWidth(layer) << " inc=" << inc << " skip=" << src->getSkip(layer) << " stride=" << src->getStride(layer) << std::endl;
 	for(unsigned int y=0; y<getHeight(layer); y++) {
 		for(unsigned int x=0; x<getWidth(layer); x++) {
@@ -113,12 +180,12 @@
 			*dimg++=*svimg;
 			*dimg++=*suimg;
 			syimg+=inc;
-			suimg+=inc;
 			svimg+=inc;
+			suimg+=inc;
 		}
-		syimg+=src->getSkip(layer);
-		suimg+=src->getSkip(layer);
-		svimg+=src->getSkip(layer);
+		syimg+=skip;
+		svimg+=skip;
+		suimg+=skip;
 	}
 	imageValids[layer][chan]=true;
 }
@@ -128,9 +195,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.14 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/08/05 21:56:04 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/InterleavedYUVGenerator.h ./Vision/InterleavedYUVGenerator.h
--- ../Tekkotsu_2.3/Vision/InterleavedYUVGenerator.h	Wed Feb 18 16:13:32 2004
+++ ./Vision/InterleavedYUVGenerator.h	Mon Jun 13 14:03:15 2005
@@ -7,8 +7,8 @@
 //! Generates FilterBankEvents containing raw camera images with interleaved pixels (YVUYVUYVU... instead of YYY...UUU...VVV...)
 /*! @note That's not a typo - the byte ordering is YVU, @e not YUV
  *
- *  Sorry about the misleading name... This @a takes filter banks
- *  containing YUV information, however, the main reason for this
+ *  Sorry about the misleading name... This @e takes filter banks
+ *  containing YUV information, however.  The main reason for this
  *  class is to interleave the image in order to pass it to the jpeg
  *  compression routines.  JPEG expect YCbCr, which corresponds to YVU
  *  order.
@@ -35,9 +35,9 @@
 class InterleavedYUVGenerator : public FilterBankGenerator {
 public:
 	//! constructor
-	InterleavedYUVGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid);
+	InterleavedYUVGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid);
 	//! constructor, you can pass which channels to interleave
-	InterleavedYUVGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, unsigned int syc, unsigned int suc, unsigned int svc);
+	InterleavedYUVGenerator(unsigned int mysid, unsigned int syc, unsigned int suc, unsigned int svc, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid);
 
 	//! destructor
 	virtual ~InterleavedYUVGenerator() {
@@ -58,15 +58,21 @@
 
 	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
 
+	virtual void freeCaches();
+	virtual void invalidateCaches();
+
 protected:
 	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
 	virtual void setDimensions(); //!< resets stride parameter (to correspond to width*3 from FilterBankGenerator::setDimensions())
+	virtual void destruct();
 	virtual unsigned char * createImageCache(unsigned int layer, unsigned int chan) const;
-	virtual void calcImage(unsigned int layer, unsigned int chan) const;
+	virtual void calcImage(unsigned int layer, unsigned int chan);
 
 	unsigned int srcYChan; //!< the channel of the source's Y channel
 	unsigned int srcUChan; //!< the channel of the source's U channel
 	unsigned int srcVChan; //!< the channel of the source's V channel
+	
+	bool ** isAllocated; //!< flag for each image, set to true if the corresponding value in #images will need to be freed, or false if it's a passthrough from the previous stage
 
 private:
 	InterleavedYUVGenerator(const InterleavedYUVGenerator& fbk); //!< don't call
@@ -78,10 +84,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.11 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.14 $
  * $State: Exp $
- * $Date: 2004/02/18 21:13:32 $
+ * $Date: 2005/06/13 18:03:15 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/JPEGGenerator.cc ./Vision/JPEGGenerator.cc
--- ../Tekkotsu_2.3/Vision/JPEGGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/JPEGGenerator.cc	Mon Jun 13 15:39:33 2005
@@ -4,33 +4,55 @@
 #include "Events/EventRouter.h"
 #include "Events/FilterBankEvent.h"
 #include "Wireless/Wireless.h"
-#include <write_jpeg.h>
 #include "Shared/Config.h"
 #include "Shared/WorldState.h"
 
-#include <jpeg_mem_dest.h>
-
+#include "Shared/jpeg-6b/jpeg_mem_dest.h"
 
 #include "Shared/debuget.h"
 
-JPEGGenerator::JPEGGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid)
-	: FilterBankGenerator("JPEGGenerator",gid,sid,EventBase::visJPEGEGID,mysid), srcMode(SRC_AUTO), curMode(SRC_AUTO), bytesUsed(NULL), cinfo(), jerr(), quality(-1U)
+JPEGGenerator::JPEGGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid)
+	: FilterBankGenerator("JPEGGenerator","JPEGGenerator",EventBase::visJPEGEGID,mysid,fbg,tid), srcMode(SRC_AUTO), curMode(SRC_AUTO), bytesUsed(NULL), cinfo(), jerr(), quality(-1U)
 {
+	if(dynamic_cast<const InterleavedYUVGenerator*>(src)!=NULL)
+		curMode=SRC_COLOR;
+	else
+		curMode=SRC_GRAYSCALE;
+
 	// We set the err object before we create the compress...  the idea
 	// is if the creation fails, we can still get the error as to why it
 	// failed.
 	cinfo.err = jpeg_std_error(&jerr);
 	jpeg_create_compress(&cinfo);
+
+	//this part is only necessary if you override setNumImages yourself
+	if(fbg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(fbg->getNumLayers(),fbg->getNumChannels());
+	}
 }
 
-JPEGGenerator::JPEGGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, src_mode_t mode)
-	: FilterBankGenerator("JPEGGenerator",gid,sid,EventBase::visJPEGEGID,mysid), srcMode(mode), curMode(SRC_AUTO), bytesUsed(NULL), cinfo(), jerr(), quality(-1U)
+JPEGGenerator::JPEGGenerator(unsigned int mysid, src_mode_t mode, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid)
+	: FilterBankGenerator("JPEGGenerator","JPEGGenerator",EventBase::visJPEGEGID,mysid,fbg,tid), srcMode(mode), curMode(mode), bytesUsed(NULL), cinfo(), jerr(), quality(-1U)
 {
+	if(srcMode==SRC_AUTO) {
+		if(dynamic_cast<const InterleavedYUVGenerator*>(src)!=NULL)
+			curMode=SRC_COLOR;
+		else
+			curMode=SRC_GRAYSCALE;
+	}
+	
 	// We set the err object before we create the compress...  the idea
 	// is if the creation fails, we can still get the error as to why it
 	// failed.
 	cinfo.err = jpeg_std_error(&jerr);
 	jpeg_create_compress(&cinfo);
+
+	//this part is only necessary if you override setNumImages yourself
+	if(fbg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(fbg->getNumLayers(),fbg->getNumChannels());
+	}
 }
 
 JPEGGenerator::~JPEGGenerator() {
@@ -54,7 +76,9 @@
 			else
 				curMode=SRC_GRAYSCALE;
 		}
-		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID()));
+		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::activateETID));
+		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::statusETID));
+		erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::deactivateETID));
 	}
 }
 
@@ -124,7 +148,15 @@
 	if(0==(used=encode(type,buf,len))) return 0;
 	len-=used; buf+=used;
 	
-	unsigned char* img=getImage(selectedSaveLayer,selectedSaveChannel);
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("JPEGGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("JPEGGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
 	if(img==NULL)
 		return 0;
 	if(0==(used=encode(bytesUsed[selectedSaveLayer][selectedSaveChannel],buf,len))) return 0;
@@ -165,7 +197,7 @@
  *  process greyscale images as well as color.
  */
 void
-JPEGGenerator::calcImage(unsigned int layer, unsigned int chan) const {
+JPEGGenerator::calcImage(unsigned int layer, unsigned int chan) {
 	PROFSECTION("JPEGGenerator::calcImage(...)",state->mainProfile);
 
 	//pass the destination buffer and buffer size here
@@ -181,7 +213,7 @@
 		cinfo.input_components = 1;		/* # of color components per pixel */
 		cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
 	} else {
-		serr->printf("Compression failed - unsuitable or unknown mode/generator pair");
+		serr->printf("%s %s Compression failed - unsuitable or unknown mode/generator pair",getClassName().c_str(),getName().c_str());
 		jpeg_destroy_compress(&cinfo);
 		return;
 	}
@@ -191,36 +223,53 @@
 	unsigned int qual=(quality==-1U?config->vision.rawcam_compress_quality:quality);
 	jpeg_set_quality(&cinfo, qual, false); /* limit to baseline-JPEG values */
 	cinfo.dct_method=config->vision.jpeg_dct_method;
-	if(cinfo.in_color_space==JCS_YCbCr) {
-		unsigned int ysamp=1;
-		unsigned int uvsamp=1;
-		const unsigned int maxsamp=2;  // according to jpeg docs, this should be able to go up to 4, but I get error: "Sampling factors too large for interleaved scan"
-		if(config->vision.rawcam_y_skip>config->vision.rawcam_uv_skip) {
-			uvsamp=config->vision.rawcam_y_skip-config->vision.rawcam_uv_skip+1;
-			if(uvsamp>maxsamp)
-				uvsamp=maxsamp;
-		} else {
-			ysamp=config->vision.rawcam_uv_skip-config->vision.rawcam_y_skip+1;
-			if(ysamp>maxsamp)
-				ysamp=maxsamp;
+	if(cinfo.in_color_space==JCS_GRAYSCALE && src->getIncrement(layer)!=1) {
+		//special case, need to remove interleaved channels as we compress (single channel, grayscale)
+		jpeg_start_compress(&cinfo, TRUE);
+		unsigned int row_stride = src->getStride(layer);	/* JSAMPLEs per row in image_buffer */
+		JSAMPROW row_pointer[1] = { new JSAMPLE[src->getWidth(layer)] };
+		unsigned char * curpos=src->getImage(layer,chan);
+		const unsigned int inc=src->getIncrement(layer);
+		while (cinfo.next_scanline < cinfo.image_height) {
+			for(unsigned int x=0; x<src->getWidth(layer); x++)
+				row_pointer[0][x] = curpos[x*inc];
+			jpeg_write_scanlines(&cinfo, row_pointer, 1);
+			curpos+=row_stride;
+		}
+		jpeg_finish_compress(&cinfo);
+		
+	} else	{
+		if(cinfo.in_color_space==JCS_YCbCr) {
+			unsigned int ysamp=1;
+			unsigned int uvsamp=1;
+			const unsigned int maxsamp=2;  // according to jpeg docs, this should be able to go up to 4, but I get error: "Sampling factors too large for interleaved scan"
+			if(config->vision.rawcam_y_skip>config->vision.rawcam_uv_skip) {
+				uvsamp=config->vision.rawcam_y_skip-config->vision.rawcam_uv_skip+1;
+				if(uvsamp>maxsamp)
+					uvsamp=maxsamp;
+			} else {
+				ysamp=config->vision.rawcam_uv_skip-config->vision.rawcam_y_skip+1;
+				if(ysamp>maxsamp)
+					ysamp=maxsamp;
+			}
+			cinfo.comp_info[0].h_samp_factor=ysamp;
+			cinfo.comp_info[0].v_samp_factor=ysamp;
+			cinfo.comp_info[1].h_samp_factor=uvsamp;
+			cinfo.comp_info[1].v_samp_factor=uvsamp;
+			cinfo.comp_info[2].h_samp_factor=uvsamp;
+			cinfo.comp_info[2].v_samp_factor=uvsamp;
 		}
-		cinfo.comp_info[0].h_samp_factor=ysamp;
-		cinfo.comp_info[0].v_samp_factor=ysamp;
-		cinfo.comp_info[1].h_samp_factor=uvsamp;
-		cinfo.comp_info[1].v_samp_factor=uvsamp;
-		cinfo.comp_info[2].h_samp_factor=uvsamp;
-		cinfo.comp_info[2].v_samp_factor=uvsamp;
-	}
 
-	// compression
-	jpeg_start_compress(&cinfo, TRUE);
-	unsigned int row_stride = src->getStride(layer);	/* JSAMPLEs per row in image_buffer */
-	JSAMPROW row_pointer[1] = { const_cast<JSAMPROW>(src->getImage(layer,chan)) };
-	while (cinfo.next_scanline < cinfo.image_height) {
-		jpeg_write_scanlines(&cinfo, row_pointer, 1);
-		row_pointer[0]+=row_stride;
+		// compression
+		jpeg_start_compress(&cinfo, TRUE);
+		unsigned int row_stride = src->getStride(layer);	/* JSAMPLEs per row in image_buffer */
+		JSAMPROW row_pointer[1] = { const_cast<JSAMPROW>(src->getImage(layer,chan)) };
+		while (cinfo.next_scanline < cinfo.image_height) {
+			jpeg_write_scanlines(&cinfo, row_pointer, 1);
+			row_pointer[0]+=row_stride;
+		}
+		jpeg_finish_compress(&cinfo);
 	}
-	jpeg_finish_compress(&cinfo);
 
 	// results
 	bytesUsed[layer][chan]=jpeg_mem_size(&cinfo);
@@ -241,9 +290,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.9 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.13 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/06/13 19:39:33 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/JPEGGenerator.h ./Vision/JPEGGenerator.h
--- ../Tekkotsu_2.3/Vision/JPEGGenerator.h	Wed Feb 18 16:13:32 2004
+++ ./Vision/JPEGGenerator.h	Sun Aug  7 00:11:04 2005
@@ -42,9 +42,9 @@
 	};
 
 	//! constructor
-	JPEGGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid);
+	JPEGGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid);
 	//! constructor
-	JPEGGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, src_mode_t sMode);
+	JPEGGenerator(unsigned int mysid, JPEGGenerator::src_mode_t sMode, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid);
 
 	//! destructor
 	virtual ~JPEGGenerator();
@@ -84,7 +84,7 @@
 protected:
 	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
 	virtual unsigned char * createImageCache(unsigned int layer, unsigned int chan) const;
-	virtual void calcImage(unsigned int layer, unsigned int chan) const;
+	virtual void calcImage(unsigned int layer, unsigned int chan);
 	virtual void destruct();
 
 	src_mode_t srcMode;   //!< how to interpret source channel of next filter bank event
@@ -92,8 +92,8 @@
 
 	unsigned int ** bytesUsed; //!< number of bytes used per image to actually store data;
 
-	mutable struct jpeg_compress_struct cinfo; //!< used to interface with libjpeg - holds compression parameters and state
-	mutable struct jpeg_error_mgr jerr;        //!< used to interface with libjpeg - gives us access to error information
+	struct jpeg_compress_struct cinfo; //!< used to interface with libjpeg - holds compression parameters and state
+	struct jpeg_error_mgr jerr;        //!< used to interface with libjpeg - gives us access to error information
 
 	unsigned int quality; //!< quality level to pass to libjpeg; -1U causes Config::vision_config::rawcam_compress_quality to be used
 	
@@ -107,10 +107,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/02/18 21:13:32 $
+ * $Date: 2005/08/07 04:11:04 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/OFbkImage.h ./Vision/OFbkImage.h
--- ../Tekkotsu_2.3/Vision/OFbkImage.h	Wed Dec 31 19:00:00 1969
+++ ./Vision/OFbkImage.h	Wed Jun  1 01:47:58 2005
@@ -0,0 +1,91 @@
+//-*-c++-*-
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OFbkImage.h>
+#else
+#  ifndef INCLUDED_OFbkImage_h_
+#  define INCLUDED_OFbkImage_h_
+
+#include "Shared/ODataFormats.h"
+
+typedef longword OFbkImageBand;
+const OFbkImageBand ofbkimageBAND_Y	   = 0; // Y_LL
+const OFbkImageBand ofbkimageBAND_Cr   = 1;
+const OFbkImageBand ofbkimageBAND_Cb   = 2;
+const OFbkImageBand ofbkimageBAND_CDT  = 3;
+const OFbkImageBand ofbkimageBAND_Y_LH = 4;
+const OFbkImageBand ofbkimageBAND_Y_HL = 5;
+const OFbkImageBand ofbkimageBAND_Y_HH = 6;
+
+class OFbkImage {
+public:
+	OFbkImage(OFbkImageInfo* /*info*/, byte* /*data*/, OFbkImageBand /*band*/) : image_(NULL), width_(0), height_(0), skip_(0) {}
+	~OFbkImage() {}
+
+	bool   IsValid() const { return image_ != 0 ? true : false; }
+	byte*  Pointer() const { return image_;	   }
+	int	   Width()	 const { return width_;	   }
+	int	   Height()	 const { return height_;   }
+	int	   Skip()	 const { return skip_;	   }
+
+	inline byte Pixel(int x, int y) const;
+
+	// Tag Information
+	inline word FieldCounter() const;
+	inline byte ColorFrequency(OCdtChannel chan) const;
+
+
+protected:
+	byte* image_;
+	int	  width_;
+	int	  height_;
+	int	  skip_;
+	
+private:
+	OFbkImage(const OFbkImage&); //!< don't call
+	OFbkImage& operator =(const OFbkImage& fbk_image); //!< don't call
+};
+
+byte
+OFbkImage::Pixel(int x, int y) const
+{
+	return *(image_ + (width_ + skip_) * y + x);
+}
+
+word
+OFbkImage::FieldCounter() const
+{
+	byte* tag = image_ + (width_ + skip_) * (height_ - 1) + 0;
+	return ((word)tag[1] << 8) | (word)tag[0];
+}
+
+byte
+OFbkImage::ColorFrequency(OCdtChannel chan) const
+{
+	byte freq;
+	byte* tag = image_ + (width_ + skip_) * (height_ - 1) + 0;
+
+	if (chan == ocdtCHANNEL0) {
+		freq = tag[8];
+	} else if (chan == ocdtCHANNEL1) {
+		freq = tag[9];
+	} else if (chan == ocdtCHANNEL2) {
+		freq = tag[10];
+	} else if (chan == ocdtCHANNEL3) {
+		freq = tag[11];
+	} else if (chan == ocdtCHANNEL4) {
+		freq = tag[4];
+	} else if (chan == ocdtCHANNEL5) {
+		freq = tag[5];
+	} else if (chan == ocdtCHANNEL6) {
+		freq = tag[6];
+	} else if (chan == ocdtCHANNEL7) {
+		freq = tag[7];
+	} else {
+		freq = 0;
+	}
+
+	return freq;
+}
+
+#  endif
+#endif
diff -urdN ../Tekkotsu_2.3/Vision/RLEGenerator.cc ./Vision/RLEGenerator.cc
--- ../Tekkotsu_2.3/Vision/RLEGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/RLEGenerator.cc	Mon Jun 13 17:24:11 2005
@@ -6,18 +6,40 @@
 
 #include "Shared/debuget.h"
 
-RLEGenerator::RLEGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid)
-	: FilterBankGenerator("RLEGenerator",gid,sid,EventBase::visRLEEGID,mysid), numRuns(NULL), maxRuns(NULL)
-{ }
+/*! TODO - after RLEGraphics is inplace, replace the 'tid' parameter in FBG's constructor call! */
+RLEGenerator::RLEGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t /*tid*/)
+	: FilterBankGenerator("RLEGenerator","RLEGenerator",EventBase::visRLEEGID,mysid,fbg), numRuns(NULL), maxRuns(NULL)
+{
+	//this part is only necessary if you override setNumImages yourself
+	if(fbg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(fbg->getNumLayers(),fbg->getNumChannels());
+	}
+}
 
 void
 RLEGenerator::processEvent(const EventBase& event) {
 	FilterBankGenerator::processEvent(event);
 	if(event.getGeneratorID()==getListenGeneratorID() && event.getSourceID()==getListenSourceID()) {
-		if(const SegmentedColorFilterBankEvent * segsrc=dynamic_cast<const SegmentedColorFilterBankEvent *>(&event))
-			erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),*segsrc));
-		else
-			erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID()));
+		//Technically, we should do things this way:
+		/*
+		if(const SegmentedColorFilterBankEvent * segsrc=dynamic_cast<const SegmentedColorFilterBankEvent *>(&event)) {
+			erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::activateETID,*segsrc));
+			erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::statusETID,*segsrc));
+			erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::deactivateETID,*segsrc));
+		} else {
+			erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::activateETID));
+			erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::statusETID));
+			erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::deactivateETID));
+		}
+		*/
+		//But until RLEGraphics is in place, we'll do it this way so recompression can be triggered
+		//after drawing into segmented image
+		if(const SegmentedColorFilterBankEvent * segsrc=dynamic_cast<const SegmentedColorFilterBankEvent *>(&event)) {
+			erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),event.getTypeID(),*segsrc));
+		} else {
+			erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),event.getTypeID()));
+		}
 	}
 }
 
@@ -82,7 +104,16 @@
 	if(0==(used=encode("RLEImage",buf,len))) return 0;
 	len-=used; buf+=used;
 	
-	run * runs=reinterpret_cast<run*>(getImage(selectedSaveLayer,selectedSaveChannel));
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("RLEGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("RLEGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
+	run * runs=reinterpret_cast<run*>(img);
 	if(runs==NULL)
 		return 0;
 	if(0==(used=encode(numRuns[selectedSaveLayer][selectedSaveChannel],buf,len))) return 0;
@@ -126,7 +157,7 @@
 
 //! a single call to the CMVision library to do the work, and we're done.
 void
-RLEGenerator::calcImage(unsigned int layer, unsigned int chan) const {
+RLEGenerator::calcImage(unsigned int layer, unsigned int chan) {
 	PROFSECTION("RLEGenerator::calcImage(...)",state->mainProfile);
   numRuns[layer][chan] = CMVision::EncodeRuns(reinterpret_cast<run*>(images[layer][chan]),src->getImage(layer,chan),getWidth(layer),getHeight(layer),maxRuns[layer]);
 	imageValids[layer][chan]=true; // <--- don't forget to do this, otherwise you'll recompute on every access, even if the cache is still valid
@@ -149,9 +180,9 @@
  * @author ejt (reorganized)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.8 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/06/13 21:24:11 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/RLEGenerator.h ./Vision/RLEGenerator.h
--- ../Tekkotsu_2.3/Vision/RLEGenerator.h	Wed Feb 18 16:13:32 2004
+++ ./Vision/RLEGenerator.h	Wed Jun  1 01:47:58 2005
@@ -67,7 +67,7 @@
 	typedef CMVision::run<cmap_t> run; //!< use the CMVision library's run structure
 	
 	//! constructor
-	RLEGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid);
+	RLEGenerator(unsigned int mysid, FilterBankGenerator * fbg, EventBase::EventTypeID_t tid);
 	
 	//! destructor
 	virtual ~RLEGenerator() {
@@ -85,11 +85,14 @@
 	virtual unsigned int SaveBuffer(char buf[], unsigned int len) const;
 
 	//! returns the number of runs for the image
-	virtual unsigned int getNumRuns(unsigned int layer, unsigned int chan) const { if(!imageValids[layer][chan]) getImage(layer,chan); return numRuns[layer][chan]; }
-	//! returns the actual runs of the specified image
-	virtual const run * getRuns(unsigned int layer, unsigned int chan) const { return reinterpret_cast<const run*>(getImage(layer,chan)); }
+	virtual unsigned int getNumRuns(unsigned int layer, unsigned int chan) { if(!imageValids[layer][chan]) getImage(layer,chan); return numRuns[layer][chan]; }
+	//! returns the actual runs of the specified image -- returned pointer is to internal storage; do not free
+	virtual run * getRuns(unsigned int layer, unsigned int chan) { return reinterpret_cast<run*>(getImage(layer,chan)); }
 	//! returns a specific run of the specified image
-	virtual const run& getRun(unsigned int layer, unsigned int chan, unsigned int i) const { return reinterpret_cast<const run*>(getImage(layer,chan))[i]; }
+	virtual const run& getRun(unsigned int layer, unsigned int chan, unsigned int i) { return reinterpret_cast<const run*>(getImage(layer,chan))[i]; }
+
+	//! in case you have inserted or removed runs during postprocessing, call this to update the count
+	virtual void setNumRuns(unsigned int layer, unsigned int chan, unsigned int num) { numRuns[layer][chan]=num; }
 	
 protected:
 	static const unsigned int MIN_EXP_RUN_LENGTH=8; //!< The expected minimum average length of each run
@@ -98,7 +101,7 @@
 	virtual void setDimensions(); //!< sets the width, height, skip and stride, as well as #maxRuns
 	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
 	virtual unsigned char * createImageCache(unsigned int layer, unsigned int chan) const;
-	virtual void calcImage(unsigned int layer, unsigned int chan) const;
+	virtual void calcImage(unsigned int layer, unsigned int chan);
 	virtual void destruct();
 	//! uses a heuristic to predict the maximum number of runs expected per layer
 	unsigned int calcExpMaxRuns(unsigned int layer) const { return getWidth(layer)*getHeight(layer)/MIN_EXP_RUN_LENGTH; }
@@ -117,10 +120,10 @@
  * @author ejt (reorganized)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
  * $State: Exp $
- * $Date: 2004/02/18 21:13:32 $
+ * $Date: 2005/06/01 05:47:58 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/RawCameraGenerator.cc ./Vision/RawCameraGenerator.cc
--- ../Tekkotsu_2.3/Vision/RawCameraGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/RawCameraGenerator.cc	Mon Jun  6 15:33:31 2005
@@ -6,14 +6,23 @@
 #include "Shared/Config.h"
 #include "Shared/WorldState.h"
 
-#include <OPENR/ODataFormats.h>
-#include <OPENR/OFbkImage.h>
+#include "Shared/ODataFormats.h"
+#include "OFbkImage.h"
 
 #include "Shared/debuget.h"
 
-RawCameraGenerator::RawCameraGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid)
-	: FilterBankGenerator("RawCameraGenerator",gid,sid,EventBase::visRawCameraEGID,mysid), numRealLayers(numRawLayers), layers(NULL), imageInfos(NULL)
+#include <float.h>
+
+RawCameraGenerator::RawCameraGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, unsigned int mysid, EventBase::EventGeneratorID_t gid, unsigned int sid)
+	: FilterBankGenerator("RawCameraGenerator","RawCameraGenerator",EventBase::visRawCameraEGID,mysid,gid,sid), numRealLayers(numRawLayers), layers(NULL), imageInfos(NULL)
 {
+	/* As a root stage, we need to listen to all incoming image
+	 * events, even if we don't currently have listeners of our own --
+	 * This is just in case user code directly accesses a generator
+	 * and we have to retroactively go back and dig up the previous
+	 * frame */
+	unsetAutoListen();
+	
 	setNumImages(numCalcLayers,NUM_CHANNELS);
 }
 
@@ -26,41 +35,66 @@
 	EventGeneratorBase::processEvent(event);
 	if(event.getGeneratorID()!=getListenGeneratorID() || event.getSourceID()!=getListenSourceID())
 		return;
-	typedef DataEvent<const OFbkImageVectorData*> OFbkEvent;
-	const OFbkEvent& fbkevent=dynamic_cast<const OFbkEvent& >(event);
-	OFbkImageVectorData& fbkdat=*const_cast<OFbkImageVectorData*>(fbkevent.getData());
-	for(unsigned int res=0; res<numRealLayers; res++) {
-		layers[numLayers-2-res] = fbkdat.GetData(res);
-		imageInfos[numLayers-2-res] = fbkdat.GetInfo(res);
-	}
-	{
-		const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[numLayers-2]), const_cast<unsigned char*>(layers[numLayers-2]), ofbkimageBAND_Y);
-		//I have to do this crazy thing because apparently img.FieldCounter() doesn't work
-		frameNumber=*(int*)(img.Pointer()+(img.Height()-1)*(img.Skip()+img.Width()));
-	}
-	unsigned int numNotRealLayers=numLayers-1-numRealLayers;
-	for(unsigned int res=numNotRealLayers; res<numLayers-1; res++) {
-		widths[res] = imageInfos[res]->width;
-		heights[res] = imageInfos[res]->height;
+	if(event.getTypeID()==EventBase::activateETID) {
+		typedef DataEvent<const OFbkImageVectorData*> OFbkEvent;
+		const OFbkEvent& fbkevent=dynamic_cast<const OFbkEvent& >(event);
+		OFbkImageVectorData& fbkdat=*const_cast<OFbkImageVectorData*>(fbkevent.getData());
+		for(unsigned int res=0; res<numRealLayers; res++) {
+			layers[numLayers-2-res] = fbkdat.GetData(res);
+			imageInfos[numLayers-2-res] = fbkdat.GetInfo(res);
+		}
+		{
+			const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[numLayers-2]), const_cast<unsigned char*>(layers[numLayers-2]), ofbkimageBAND_Y);
+			//I have to do this crazy thing because apparently img.FieldCounter() doesn't work
+			sysFrameNumber=frameNumber=*(int*)(img.Pointer()+(img.Height()-1)*(img.Skip()+img.Width()));
+		}
+		unsigned int numNotRealLayers=numLayers-1-numRealLayers;
+		bool dimchange=false;
+		for(unsigned int res=numNotRealLayers; res<numLayers-1; res++) {
+			if(widths[res]!=imageInfos[res]->width || heights[res]!=imageInfos[res]->height) {
+				dimchange=true;
+				serr->printf("WARNING: the image dimensions changed, now %dx%d\n",widths[numLayers-1],heights[numLayers-1]);
+				widths[res] = imageInfos[res]->width;
+				heights[res] = imageInfos[res]->height;
+			}
 
-		const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[res]), const_cast<unsigned char*>(layers[res]), ofbkimageBAND_Y);
-		skips[res]=img.Skip();
-		strides[res]=skips[res]+widths[res];
+			const OFbkImage img(const_cast<OFbkImageInfo*>(imageInfos[res]), const_cast<unsigned char*>(layers[res]), ofbkimageBAND_Y);
+			skips[res]=img.Skip();
+			strides[res]=skips[res]+widths[res];
 
-		ASSERT(static_cast<unsigned int>(img.Width())==getWidth(res),"Widths don't match");
-		ASSERT(static_cast<unsigned int>(img.Height())==getHeight(res),"Heights don't match");
-	}
-	if(widths[numLayers-2]*2!=widths[numLayers-1] || heights[numLayers-2]*2!=heights[numLayers-1]) {
-		//|| widths[numLayers-2-numRealLayers]*2!=widths[numNotRealLayers]
-		//|| heights[numLayers-2-numRealLayers]*2!=heights[numNotRealLayers]) {
-		//set the width and height of non-real layers (since they don't match what they should be)
-		ASSERT(widths[numLayers-1]==0,"Strange, the image width changed after initial setting" << widths[numLayers-1]);
-		setDimensions();
+			ASSERT(static_cast<unsigned int>(img.Width())==getWidth(res),"Widths don't agree for layer "<<res);
+			ASSERT(static_cast<unsigned int>(img.Height())==getHeight(res),"Heights don't agree for layer "<<res);
+		}
+		if(widths[numLayers-2]*2!=widths[numLayers-1] || heights[numLayers-2]*2!=heights[numLayers-1]) {
+			//|| widths[numLayers-2-numRealLayers]*2!=widths[numNotRealLayers]
+			//|| heights[numLayers-2-numRealLayers]*2!=heights[numNotRealLayers]) {
+			//set the width and height of non-real layers (since they don't match what they should be)
+			serr->printf("WARNING: the image dimensions don't match values predicted by RobotInfo consts, now %dx%d\n",widths[numLayers-1],heights[numLayers-1]);
+			freeCaches();
+			dimchange=true;
+		} else if(strides[numLayers-1]==0) {
+			// first frame
+			dimchange=true;
+		}
+		if(dimchange)
+			setDimensions();
+		float testaspect=widths[numLayers-2]/(float)heights[numLayers-2];
+		if(fabs(testaspect-config->vision.aspectRatio)>FLT_EPSILON) {
+			serr->printf("WARNING: the image aspect ratio changed, was %g, now %g (diff %g)\n",config->vision.aspectRatio,testaspect,testaspect-config->vision.aspectRatio);
+			config->vision.aspectRatio=testaspect;
+			if(testaspect>1) {
+				config->vision.x_range=1;
+				config->vision.y_range=1/testaspect;
+			} else {
+				config->vision.x_range=testaspect;
+				config->vision.y_range=1;
+			}
+		}
+		
+		invalidateCaches();	
+		framesProcessed++;
 	}
-
-	invalidateCaches();	
-	framesProcessed++;
-	erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID()));
+	erouter->postEvent(new FilterBankEvent(this,getGeneratorID(),getSourceID(),event.getTypeID()));
 }
 
 unsigned int
@@ -108,7 +142,15 @@
 	if(0==(used=encode("RawImage",buf,len))) return 0;
 	len-=used; buf+=used;
 	
-	unsigned char* img=getImage(selectedSaveLayer,selectedSaveChannel);
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("RawCameraGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("RawCameraGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
 	used=widths[selectedSaveLayer]*heights[selectedSaveLayer];
 	ASSERTRETVAL(used<=len,"buffer too small",0);
 	unsigned int inc=getIncrement(selectedSaveLayer);
@@ -164,7 +206,15 @@
 	if(0==(used=encode("RawImage",f))) return 0;
 	totalused+=used;
 	
-	unsigned char* img=getImage(selectedSaveLayer,selectedSaveChannel);
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("RawCameraGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("RawCameraGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
 	used=widths[selectedSaveLayer]*heights[selectedSaveLayer];
 	unsigned int inc=getIncrement(selectedSaveLayer);
 	if(inc==1) {
@@ -247,7 +297,7 @@
 }
 
 void
-RawCameraGenerator::calcImage(unsigned int layer, unsigned int chan) const {
+RawCameraGenerator::calcImage(unsigned int layer, unsigned int chan) {
 	PROFSECTION("RawCameraGenerator::calcImage(...)",state->mainProfile);
 	unsigned int numNotRealLayers=numLayers-1-numRealLayers;
 	if(layer==numLayers-1) {
@@ -333,7 +383,7 @@
 }
 
 void
-RawCameraGenerator::upsampleImage(channel_id_t chan) const {
+RawCameraGenerator::upsampleImage(channel_id_t chan) {
 	const unsigned int dblLayer=numLayers-1;
 	const unsigned int srcLayer=dblLayer-1;
 	const unsigned int width=widths[dblLayer];
@@ -374,7 +424,7 @@
 		</pre>
 */
 void
-RawCameraGenerator::reconstructImage() const {
+RawCameraGenerator::reconstructImage() {
 	byte* yLLPtr = getImage(numLayers-2,CHAN_Y);
 	byte* yLHPtr = getImage(numLayers-2,CHAN_Y_DY);
 	byte* yHLPtr = getImage(numLayers-2,CHAN_Y_DX);
@@ -425,9 +475,9 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.16 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.21 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/06/06 19:33:31 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/RawCameraGenerator.h ./Vision/RawCameraGenerator.h
--- ../Tekkotsu_2.3/Vision/RawCameraGenerator.h	Wed Feb 18 16:13:32 2004
+++ ./Vision/RawCameraGenerator.h	Fri Jun  3 18:56:30 2005
@@ -3,8 +3,8 @@
 #define INCLUDED_RawCameraGenerator_h_
 
 #include "Vision/FilterBankGenerator.h"
+#include "Shared/RobotInfo.h"
 
-class OFbkImageVectorData;
 class OFbkImageInfo;
 
 //! Generates FilterBankEvents containing raw camera images directly from the system (doesn't make a copy)
@@ -27,7 +27,7 @@
 	 *
 	 *  @see FilterBankGenerator for information on serialization format
 	 */
-	RawCameraGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid);
+	RawCameraGenerator(unsigned int numRawLayers, unsigned int numCalcLayers, unsigned int mysid, EventBase::EventGeneratorID_t gid, unsigned int sid);
 
 	//! destructor
 	virtual ~RawCameraGenerator() {
@@ -48,6 +48,9 @@
 		NUM_CHANNELS //!< number of channels per resolution layer
 	};
 
+	//! need to override EventGeneratorBase's lazy listening -- as a root stage, need to remember each frame, just in case it might be used
+	virtual void DoStart() { FilterBankGenerator::DoStart(); addSrcListener(); }
+
 	//! called with system's image info
 	virtual void processEvent(const EventBase& event);
 	
@@ -70,28 +73,24 @@
 	 * 
 	 *  The 2.0 release had the proper dynamic allocation
 	 *  implementation, but has been replaced in 2.0.1 with this static
-	 *  allocation so it won't crash.
-	 *
-	 *  Of course, if the memory allocation bug is never fixed, and
-	 *  camera sizes increase in later models, this will have to be
-	 *  modified. */
-	unsigned char dblRes[NUM_CHANNELS][416][320]; 
+	 *  allocation so it won't crash.*/
+	unsigned char dblRes[NUM_CHANNELS][CameraResolutionX*2][CameraResolutionY*2]; 
 
 	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
 
 	virtual void setDimensions(); //!< resets the width, height, skip and stride values
 	virtual unsigned char * createImageCache(unsigned int layer, unsigned int chan) const;
-	virtual void calcImage(unsigned int layer, unsigned int chan) const;
+	virtual void calcImage(unsigned int layer, unsigned int chan);
 	virtual void destruct();
 
 	//! returns the value to pass to OPENR functions corresponding to the desired channel_id_t.
 	inline static unsigned int mapChannelID(channel_id_t chan);
 
 	//! Creates a double resolution version of a channel, doesn't do any smoothing
-	void upsampleImage(channel_id_t chan) const;
+	void upsampleImage(channel_id_t chan);
 
 	//! Creates a double resolution Y-channel from the Y and Y gradient channels
-	void reconstructImage() const;
+	void reconstructImage();
 
 	//! helper functions for reconstructImage() - see documentation for that function
 	static inline unsigned char clipRange(int val) {
@@ -115,10 +114,10 @@
  * @author ejt (Creator)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.14 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.17 $
  * $State: Exp $
- * $Date: 2004/02/18 21:13:32 $
+ * $Date: 2005/06/03 22:56:30 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/RegionGenerator.cc ./Vision/RegionGenerator.cc
--- ../Tekkotsu_2.3/Vision/RegionGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/RegionGenerator.cc	Mon Jun  6 16:23:15 2005
@@ -7,9 +7,15 @@
 
 #include "Shared/debuget.h"
 
-RegionGenerator::RegionGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid)
-	: FilterBankGenerator("RegionGenerator",gid,sid,EventBase::visRegionEGID,mysid), srcNumColors(0), srcColors(0), regions(NULL)
-{ }
+RegionGenerator::RegionGenerator(unsigned int mysid, RLEGenerator* rleg, EventBase::EventTypeID_t tid)
+	: FilterBankGenerator("RegionGenerator","RegionGenerator",EventBase::visRegionEGID,mysid,rleg,tid), srcNumColors(0), srcColors(0), regions(NULL)
+{
+	//this part is only necessary if you override setNumImages yourself
+	if(rleg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(rleg->getNumLayers(),rleg->getNumChannels());
+	}
+}
 
 void
 RegionGenerator::freeCaches() {
@@ -39,7 +45,9 @@
 			freeCaches();
 		srcNumColors=segev->getNumColors();
 		srcColors=segev->getColors();
-		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),*segev));
+		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::activateETID,*segev));
+		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::statusETID,*segev));
+		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::deactivateETID,*segev));
 	}
 }
 
@@ -47,12 +55,22 @@
 RegionGenerator::getBinSize() const {
 	unsigned int used=FilterBankGenerator::getBinSize();
 	used+=strlen("RegionImage")+LoadSave::stringpad;
-	used+=sizeof(unsigned int);
+	used+=sizeof(unsigned int); //srcNumColors
+	used+=sizeof(unsigned int)*srcNumColors; //stats[i].num (for each color i)
 	unsigned int xmit_bytes_per_run=5*sizeof(int)+2*sizeof(float)+2*sizeof(int);
-	if(imageValids[selectedSaveLayer][selectedSaveChannel])
-		used+=xmit_bytes_per_run;//* ? todo
-	else
+	if(imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
+		region_stats * stats=reinterpret_cast<region_stats*>(img);
+		if(stats==NULL)
+			return 0;
+		for(unsigned int i=0; i<srcNumColors; i++)
+			used+=xmit_bytes_per_run*stats[i].num;
+	} else {
 		used+=xmit_bytes_per_run*MAX_REGIONS;
+	}
+	used+=sizeof(unsigned int)*srcNumColors; //stats[i].min_area (for each color i)
+	used+=sizeof(unsigned int)*srcNumColors; //stats[i].total_area (for each color i)
+	used+=sizeof(float)*srcNumColors; //stats[i].merge_threshold (for each color i)
 	return used;
 }
 
@@ -135,7 +153,16 @@
 	if(0==(used=encode("RegionImage",buf,len))) return 0;
 	len-=used; buf+=used;
 	
-	region_stats * stats=reinterpret_cast<region_stats*>(getImage(selectedSaveLayer,selectedSaveChannel));
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("RegionGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("RegionGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
+	region_stats * stats=reinterpret_cast<region_stats*>(img);
 	if(stats==NULL)
 		return 0;
 	if(0==(used=encode(srcNumColors,buf,len))) return 0;
@@ -205,11 +232,11 @@
 }
 
 void
-RegionGenerator::calcImage(unsigned int layer, unsigned int chan) const {
+RegionGenerator::calcImage(unsigned int layer, unsigned int chan) {
 	PROFSECTION("RegionGenerator::calcImage(...)",state->mainProfile);
 	
 	//some shorthand to make the rest of the code more readable
-	const RLEGenerator& srcRLE=dynamic_cast<const RLEGenerator&>(*src); //source generator
+	RLEGenerator& srcRLE=dynamic_cast<RLEGenerator&>(*src); //source generator
 	RLEGenerator::run * rmap=reinterpret_cast<RLEGenerator::run*>(srcRLE.getImage(layer,chan)); //the RLE encoded image from source
 	region_stats * stats=reinterpret_cast<region_stats*>(images[layer][chan]); //our top level region stats array (which is what users get from getImage())
 
@@ -239,9 +266,9 @@
  * @author ejt (reorganized)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.8 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/06/06 20:23:15 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/RegionGenerator.h ./Vision/RegionGenerator.h
--- ../Tekkotsu_2.3/Vision/RegionGenerator.h	Wed Feb 18 16:13:32 2004
+++ ./Vision/RegionGenerator.h	Wed Jun 29 18:06:11 2005
@@ -6,6 +6,8 @@
 #include "Events/SegmentedColorFilterBankEvent.h"
 #include "Vision/cmvision.h"
 
+class RLEGenerator;
+
 //! Connects regions of CMVision format runs in RLEGenerator
 /*! Uses the CMVision library for main processing.
  *
@@ -31,7 +33,7 @@
 	typedef CMVision::color_class_state region_stats; //!< using the CMVision library's color struct to store the region info
 	
 	//! constructor
-	RegionGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid);
+	RegionGenerator(unsigned int mysid, RLEGenerator* rleg, EventBase::EventTypeID_t tid);
 	
 	//! destructor
 	virtual ~RegionGenerator() {
@@ -56,11 +58,11 @@
 
 	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
 	virtual unsigned char * createImageCache(unsigned int layer, unsigned int chan) const;
-	virtual void calcImage(unsigned int layer, unsigned int chan) const;
+	virtual void calcImage(unsigned int layer, unsigned int chan);
 	virtual void destruct();
 
 	unsigned int srcNumColors; //!< number of colors available (from src->src, which should be SegmentedColorGenerator...)
-	color_class_state * srcColors; //!< colors information (from src->src, which should be SegmentedColorGenerator...)
+	const color_class_state * srcColors; //!< colors information (from src->src, which should be SegmentedColorGenerator...)
 	region *** regions; //!< data storage for region information
 
 private:
@@ -74,10 +76,10 @@
  * @author ejt (reorganized)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.5 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.7 $
  * $State: Exp $
- * $Date: 2004/02/18 21:13:32 $
+ * $Date: 2005/06/29 22:06:11 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/SegmentedColorGenerator.cc ./Vision/SegmentedColorGenerator.cc
--- ../Tekkotsu_2.3/Vision/SegmentedColorGenerator.cc	Tue Nov  9 15:01:49 2004
+++ ./Vision/SegmentedColorGenerator.cc	Mon Jun  6 15:33:31 2005
@@ -3,16 +3,28 @@
 #include "Events/SegmentedColorFilterBankEvent.h"
 #include "Wireless/Wireless.h"
 #include "Shared/WorldState.h"
+#include "Shared/Config.h"
 
 #include "Shared/debuget.h"
 
-SegmentedColorGenerator::SegmentedColorGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid)
-	: FilterBankGenerator("SegmentedColorGenerator",gid,sid,EventBase::visSegmentEGID,mysid), srcYChan(0), srcUChan(1), srcVChan(2), tmaps(), tmapNames(), numColors(0), colorNames()
-{ }
+SegmentedColorGenerator::SegmentedColorGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid)
+	: FilterBankGenerator("SegmentedColorGenerator","SegmentedColorGenerator",EventBase::visSegmentEGID,mysid,fbg,tid), srcYChan(0), srcUChan(1), srcVChan(2), tmaps(), tmapNames(), numColors(0), colorNames()
+{
+	//this part is only necessary if you override setNumImages yourself
+	if(fbg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(fbg->getNumLayers(),fbg->getNumChannels());
+	}
+}
 
-SegmentedColorGenerator::SegmentedColorGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, unsigned int syc, unsigned int suc, unsigned int svc)
-	: FilterBankGenerator("SegmentedColorGenerator",gid,sid,EventBase::visSegmentEGID,mysid), srcYChan(syc), srcUChan(suc), srcVChan(svc), tmaps(), tmapNames(), numColors(0), colorNames()
-{ }
+SegmentedColorGenerator::SegmentedColorGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid, unsigned int syc, unsigned int suc, unsigned int svc)
+	: FilterBankGenerator("SegmentedColorGenerator","SegmentedColorGenerator",EventBase::visSegmentEGID,mysid,fbg,tid), srcYChan(syc), srcUChan(suc), srcVChan(svc), tmaps(), tmapNames(), numColors(0), colorNames()
+{
+	if(fbg!=NULL) {
+		numLayers=numChannels=0; //this is to force setNumImages to override settings provided by FilterBankGenerator
+		setNumImages(fbg->getNumLayers(),fbg->getNumChannels());
+	}
+}
 
 SegmentedColorGenerator::~SegmentedColorGenerator() {
 	freeCaches();
@@ -31,15 +43,18 @@
 void
 SegmentedColorGenerator::processEvent(const EventBase& event) {
 	FilterBankGenerator::processEvent(event);
-	if(event.getGeneratorID()==getListenGeneratorID() && event.getSourceID()==getListenSourceID())
-		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),this,getNumColors(),getColors(),&colorNames));
+	if(event.getGeneratorID()==getListenGeneratorID() && event.getSourceID()==getListenSourceID()) {
+		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::activateETID,this,getNumColors(),getColors(),&colorNames));
+		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::statusETID,this,getNumColors(),getColors(),&colorNames));
+		erouter->postEvent(new SegmentedColorFilterBankEvent(this,getGeneratorID(),getSourceID(),EventBase::deactivateETID,this,getNumColors(),getColors(),&colorNames));
+	}
 }
 
 unsigned int
 SegmentedColorGenerator::loadThresholdMap(const std::string& tm_file) {
   const unsigned int size = 1 << (BITS_Y + BITS_U + BITS_V);
 	cmap_t * tmap = new cmap_t[size];
-  if(!CMVision::LoadThresholdFile(tmap,NUM_Y,NUM_U,NUM_V,tm_file.c_str())) {
+  if(!CMVision::LoadThresholdFile(tmap,NUM_Y,NUM_U,NUM_V,config->portPath(tm_file).c_str())) {
     serr->printf("  ERROR: Could not load threshold file '%s'.\n",tm_file.c_str());
 		delete [] tmap;
 		return -1U;
@@ -66,7 +81,7 @@
 
   colorNames.clear(); //we're leaking the memory of the names themselves...
 
-  numColors=CMVision::LoadColorInformation(colors,MAX_COLORS,col_file.c_str(),colorNames);
+  numColors=CMVision::LoadColorInformation(colors,MAX_COLORS,config->portPath(col_file).c_str(),colorNames);
   if(numColors > 0){
     sout->printf("  Loaded %d colors.\n",numColors);
   } else {
@@ -139,7 +154,15 @@
 	used=widths[selectedSaveLayer]*heights[selectedSaveLayer];
 	if(used>len)
 		return 0;
-	unsigned char* img=getImage(selectedSaveLayer,selectedSaveChannel);
+	if(images[selectedSaveLayer][selectedSaveChannel]==NULL) {
+		serr->printf("SegmentedColorGenerator::SaveBuffer() failed because selected image is NULL -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	if(!imageValids[selectedSaveLayer][selectedSaveChannel]) {
+		serr->printf("SegmentedColorGenerator::SaveBuffer() failed because selected image is invalid -- call selectSaveImage first to make sure it's up to date\n");
+		return 0;
+	}
+	unsigned char* img=images[selectedSaveLayer][selectedSaveChannel];
 	if(img==NULL)
 		return 0;
 	memcpy(buf,img,used);
@@ -204,7 +227,7 @@
 }
 
 void
-SegmentedColorGenerator::calcImage(unsigned int layer, unsigned int chan) const {
+SegmentedColorGenerator::calcImage(unsigned int layer, unsigned int chan) {
 	PROFSECTION("SegmentedColorGenerator::calcImage(...)",state->mainProfile);
 	CMVision::image_yuv<const cmap_t> img;
 	img.buf_y=src->getImage(layer,srcYChan);
@@ -212,9 +235,10 @@
 	img.buf_v=src->getImage(layer,srcVChan);
 	img.width=getWidth(layer);
 	img.height=getHeight(layer);
-  img.row_stride=src->getStride(layer);
+	img.row_stride=src->getStride(layer);
+	img.col_stride=src->getIncrement(layer);
 
-  CMVision::ThresholdImageYUVPlanar<cmap_t,CMVision::image_yuv<const cmap_t>,const cmap_t,BITS_Y,BITS_U,BITS_V>(images[layer][chan],img,tmaps[chan]);
+	CMVision::ThresholdImageYUVPlanar<cmap_t,CMVision::image_yuv<const cmap_t>,const cmap_t,BITS_Y,BITS_U,BITS_V>(images[layer][chan],img,tmaps[chan]);
 	imageValids[layer][chan]=true;
 }
 
@@ -224,9 +248,9 @@
  * @author ejt (reorganized)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.7 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
  * $State: Exp $
- * $Date: 2004/11/09 20:01:49 $
+ * $Date: 2005/06/06 19:33:31 $
  */
 
diff -urdN ../Tekkotsu_2.3/Vision/SegmentedColorGenerator.h ./Vision/SegmentedColorGenerator.h
--- ../Tekkotsu_2.3/Vision/SegmentedColorGenerator.h	Wed Dec 22 20:47:07 2004
+++ ./Vision/SegmentedColorGenerator.h	Wed Jun  1 01:47:58 2005
@@ -57,9 +57,9 @@
 	typedef __gnu_cxx::hash_map<const char*, unsigned int, __gnu_cxx::hash<const char*>, hashcmp_eqstr> hashmap; //!< a shorthand for the hash structure that CMVision expects for the color lookups
 	
 	//! constructor
-	SegmentedColorGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid);
+	SegmentedColorGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid);
 	//! constructor, you can pass which channels to use as Y, U, & V channels
-	SegmentedColorGenerator(EventBase::EventGeneratorID_t gid, unsigned int sid, unsigned int mysid, unsigned int syc, unsigned int suc, unsigned int svc);
+	SegmentedColorGenerator(unsigned int mysid, FilterBankGenerator* fbg, EventBase::EventTypeID_t tid, unsigned int syc, unsigned int suc, unsigned int svc);
 	//! destructor
 	virtual ~SegmentedColorGenerator();
 
@@ -138,7 +138,7 @@
 	virtual void setNumImages(unsigned int nLayers, unsigned int nChannels);
 	virtual void setDimensions(); //!< sets stride parameter to width (as set by FilterBankGenerator::setDimensions())
 	virtual unsigned char * createImageCache(unsigned int layer, unsigned int chan) const;
-	virtual void calcImage(unsigned int layer, unsigned int chan) const;
+	virtual void calcImage(unsigned int layer, unsigned int chan);
 
 	unsigned int srcYChan; //!< the channel of the source's Y channel
 	unsigned int srcUChan; //!< the channel of the source's U channel
@@ -162,10 +162,10 @@
  * @author ejt (reorganized)
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.10 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
  * $State: Exp $
- * $Date: 2004/12/23 01:47:07 $
+ * $Date: 2005/06/01 05:47:58 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Vision/cmv_region.h ./Vision/cmv_region.h
--- ../Tekkotsu_2.3/Vision/cmv_region.h	Sun Dec  7 19:21:06 2003
+++ ./Vision/cmv_region.h	Wed Jun  1 01:47:58 2005
@@ -1013,10 +1013,10 @@
 // used to speed up searching over the map.  This function assumes
 // there is at least one run in every row.
 {
-  y = 0;
+  int y = 0;
   yindex[y] = 0;
 
-  for(i=0; i<num; i++){
+  for(int i=0; i<num; i++){
     if(rmap[i].y > y){
       y = rmap[i].y;
       yindex[y] = i;
diff -urdN ../Tekkotsu_2.3/Vision/cmv_threshold.h ./Vision/cmv_threshold.h
--- ../Tekkotsu_2.3/Vision/cmv_threshold.h	Fri Dec  5 15:26:47 2003
+++ ./Vision/cmv_threshold.h	Sat Jun  4 19:23:31 2005
@@ -117,19 +117,21 @@
     row_v = img.buf_v + row*img.row_stride;
     row_cmap = cmap + row*width;
 
+    int rowidx=0;
     for(col=0; col<width; col++) {
-      py = row_y[col] >> rshift_y;
-      pu = row_u[col] >> rshift_u;
-      pv = row_v[col] >> rshift_v;
+      rowidx+=img.col_stride;
+      py = row_y[rowidx] >> rshift_y;
+      pu = row_u[rowidx] >> rshift_u;
+      pv = row_v[rowidx] >> rshift_v;
       tmap_idx = 
         (py << lshift_y) +
         (pu << lshift_u) +
         (pv << lshift_v);
       row_cmap[col] = tmap[tmap_idx];
 #ifdef CALC_AVG_IMG_COLOR
-      total_y += row_y[col];
-      total_u += row_u[col];
-      total_v += row_v[col];
+      total_y += row_y[rowidx];
+      total_u += row_u[rowidx];
+      total_v += row_v[rowidx];
 #endif
 
       /*
diff -urdN ../Tekkotsu_2.3/Vision/cmv_types.h ./Vision/cmv_types.h
--- ../Tekkotsu_2.3/Vision/cmv_types.h	Fri Jul 16 18:27:59 2004
+++ ./Vision/cmv_types.h	Sat Jun  4 19:23:31 2005
@@ -44,7 +44,8 @@
 public:
   element *buf_y,*buf_u,*buf_v;
   int width,height;
-  int row_stride; // number of elements to skip to move one row in buf_[yuv]
+  int row_stride; // number of elements to skip to move one row in buf_[yuv] (handle row interleaving)
+  int col_stride; // number of elements to move one column in buf_[yuv] (handle pixel interleaving)
 };
 
 #define CMV_PARAM <class pixel,class vimage,class threshold>
@@ -112,7 +113,7 @@
 struct color_class_state{
 	color_class_state() : list(), num(), min_area(), total_area(), merge_threshold(), color(), name() {}
 	color_class_state(const color_class_state& c) : list(c.list), num(c.num), min_area(c.min_area), total_area(c.total_area), merge_threshold(c.merge_threshold), color(c.color), name(c.name) {}
-	color_class_state operator=(const color_class_state& c) { list=c.list; num=c.num; min_area=c.min_area; total_area=c.total_area; merge_threshold=c.merge_threshold; color=c.color; name=c.name; return *this;}
+	color_class_state& operator=(const color_class_state& c) { list=c.list; num=c.num; min_area=c.min_area; total_area=c.total_area; merge_threshold=c.merge_threshold; color=c.color; name=c.name; return *this;}
   region *list;          // head of region list for this color
   int num;               // number of regions of this color
   int min_area;          // minimum area for a meaningful region
diff -urdN ../Tekkotsu_2.3/Vision/colors.h ./Vision/colors.h
--- ../Tekkotsu_2.3/Vision/colors.h	Fri Jul 16 18:11:38 2004
+++ ./Vision/colors.h	Thu Mar 10 18:18:07 2005
@@ -67,9 +67,11 @@
 struct rgb{
   uchar red,green,blue;
 
-	rgb(int r=0, int g=0, int b=0)
-		: red((uchar)r), green((uchar)g), blue((uchar)b)
-	{ };
+  rgb() : red(0), green(0), blue(0) {};
+
+  rgb(int r, int g, int b)
+    : red((uchar)r), green((uchar)g), blue((uchar)b)
+  { };
 			 
 
   bool operator ==(const rgb &x) const {
diff -urdN ../Tekkotsu_2.3/Wireless/CVS/Entries ./Wireless/CVS/Entries
--- ../Tekkotsu_2.3/Wireless/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./Wireless/CVS/Entries	Wed Aug 10 11:03:21 2005
@@ -0,0 +1,6 @@
+/DummySocket.h/1.5/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/Socket.cc/1.20/Tue Aug  2 22:24:29 2005//Ttekkotsu-2_4
+/Socket.h/1.23/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/Wireless.cc/1.25/Mon Aug  1 23:17:59 2005//Ttekkotsu-2_4
+/Wireless.h/1.22/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/Wireless/CVS/Repository ./Wireless/CVS/Repository
--- ../Tekkotsu_2.3/Wireless/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./Wireless/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/Wireless
diff -urdN ../Tekkotsu_2.3/Wireless/CVS/Root ./Wireless/CVS/Root
--- ../Tekkotsu_2.3/Wireless/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./Wireless/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/Wireless/CVS/Tag ./Wireless/CVS/Tag
--- ../Tekkotsu_2.3/Wireless/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./Wireless/CVS/Tag	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/Wireless/DummySocket.h ./Wireless/DummySocket.h
--- ../Tekkotsu_2.3/Wireless/DummySocket.h	Sun Jan 18 05:16:59 2004
+++ ./Wireless/DummySocket.h	Sun Aug  7 00:11:04 2005
@@ -13,28 +13,31 @@
  * Of course, since it does nothing, it doesn't need documentation
  */
 
+//! provides a no-op implementation of Socket for disabled operation
 class DummySocket : public Socket {
   friend class Wireless;
 
 public:
 	//! constructor
   DummySocket (int sockn) : Socket (sockn) { }
+	//! destructor
   virtual ~DummySocket () { }
-  byte* getWriteBuffer(int bytesreq) { return NULL; }
-  void write(int size) { }
-  int read() { return -1; }
-  byte* getReadBuffer() { return NULL; };
-  void init() { }
-  int setFlushType(FlushType_t fType) { return 0; }
-  void setTextForward() { }
-  void setForward(DummySocket * forsock) { } //!< sets another socket to send data to if this one is not connected
-  void setVerbosity(int verbose) { }
-  int write(const byte *buf, int size) { return -1; }
-  int read(byte *buf, int size) { return -1; }
-  int printf(const char *fmt, ...) { return 0; }
-  int vprintf(const char *fmt, va_list al) { return 0; }
-  int pprintf(int vlevel, const char *fmt, ...) { return 0; }
-  void flush() { }
+  
+	byte* getWriteBuffer(int /*bytesreq*/) { return NULL; } //!< returns NULL
+  void write(int /*size*/) { } //!< no-op
+  int read() { return -1; } //!< no-op (returns -1)
+  byte* getReadBuffer() { return NULL; }; //!< no-op (returns NULL)
+  void init() { } //!< no-op
+  int setFlushType(FlushType_t /*fType*/) { return 0; } //!< no-op
+  void setTextForward() { } //!< no-op
+  void setForward(DummySocket * /*forsock*/) { } //!< sets another socket to send data to if this one is not connected
+  void setVerbosity(int /*verbose*/) { } //!< no-op
+  int write(const byte * /*buf*/, int /*size*/) { return -1; } //!< no-op (returns -1)
+  int read(byte * /*buf*/, int /*size*/) { return -1; } //!< no-ip (returns -1)
+  int printf(const char */*fmt*/, ...) { return 0; } //!< no-op
+  int vprintf(const char */*fmt*/, va_list /*al*/) { return 0; } //!< no-op
+  int pprintf(int /*vlevel*/, const char * /*fmt*/, ...) { return 0; } //!< no-op
+  void flush() { } //!< no-op
 };
 
 /*! @file
@@ -42,10 +45,10 @@
  * @author alokl (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.3 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
  * $State: Exp $
- * $Date: 2004/01/18 10:16:59 $
+ * $Date: 2005/08/07 04:11:04 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Wireless/Socket.cc ./Wireless/Socket.cc
--- ../Tekkotsu_2.3/Wireless/Socket.cc	Mon Oct  4 16:38:05 2004
+++ ./Wireless/Socket.cc	Tue Aug  2 18:24:29 2005
@@ -1,7 +1,14 @@
 #include "Socket.h"
 #include <stdio.h>
-#ifdef PLATFORM_APERIOS
-#  include "Wireless.h"
+#include "Wireless.h"
+#ifndef PLATFORM_APERIOS
+#  include "IPC/Thread.h"
+#  include <sys/types.h>
+#  include <sys/socket.h>
+#  include <netinet/in.h>
+#  include <netdb.h>
+#  include <arpa/inet.h>
+#  include <fcntl.h>
 #endif
 #include "Shared/Config.h"
 #include <unistd.h>
@@ -9,9 +16,36 @@
 Socket* sout=NULL;
 Socket* serr=NULL;
 
+int Socket::setTransport(TransportType_t tr) {
+#ifdef PLATFORM_APERIOS
+	trType=tr;
+#else
+	if(trType==tr && endpoint!=-1)
+		return 0;
+	trType=tr;
+	init();
+#endif
+	return 0;
+}
+
+
+Socket::~Socket() {
+#ifndef PLATFORM_APERIOS
+	if(endpoint!=-1)
+		::close ( endpoint );
+	if(recvBuffer!=NULL)
+		delete [] recvBuffer;
+	if(sendBuffer!=NULL)
+		delete [] sendBuffer;
+#endif
+}
+
 byte*
 Socket::getWriteBuffer(int bytesreq)
 {
+#ifndef PLATFORM_APERIOS
+  wireless->getLock().lock();
+#endif
   if (sendBufSize-writeSize>=bytesreq
       && state==CONNECTION_CONNECTED)
     return writeData+writeSize;
@@ -34,6 +68,9 @@
 		textForwardBuf=NULL;
 	} else
 		flush();
+#ifndef PLATFORM_APERIOS
+  wireless->getLock().unlock();
+#endif
 }
 
 int
@@ -52,8 +89,34 @@
 void
 Socket::init()
 {
+#ifndef PLATFORM_APERIOS
+  ThreadNS::Lock(wireless->getLock());
+#endif
   sendSize=0;
   writeSize=0;
+  peer_addr=peer_port=-1;
+#ifndef PLATFORM_APERIOS
+	if(endpoint!=-1)
+		::close(endpoint);
+	endpoint = ::socket ( AF_INET,trType,0 );
+	if(endpoint==-1) {
+		perror("Socket::init(): socket()");
+		return;
+	}
+	// TIME_WAIT - argh
+	int on = 1;
+	if ( ::setsockopt ( endpoint, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 ) {
+		perror("Socket::init(): SO_REUSEADDR setsockopt");
+	}
+	if(trType==SocketNS::SOCK_DGRAM) {
+		if ( ::setsockopt ( endpoint, SOL_SOCKET, SO_BROADCAST, ( const char* ) &on, sizeof ( on ) ) == -1 ) {
+			perror("Socket::init(): SO_BROADCAST setsockopt");
+		}
+	}
+	if( ::fcntl(endpoint,F_SETFL,O_NONBLOCK) ==-1 ) {
+		perror("Socket::init(): fcntl");
+	}
+#endif
 }
 
 int
@@ -67,6 +130,9 @@
 void
 Socket::flush()
 {
+#ifndef PLATFORM_APERIOS
+  ThreadNS::Lock(wireless->getLock());
+#endif
   if (state!=CONNECTION_CONNECTED) {
 		if(forwardSock!=NULL)
 			return forwardSock->flush();
@@ -79,16 +145,12 @@
 				writeData=tempData;
 				sendSize=writeSize;
 				writeSize=tempSize;
-#ifdef PLATFORM_APERIOS
 				wireless->send(sock);
-#endif
 			}
 		} else {
 			sendData=writeData;
 			sendSize=writeSize;
-#ifdef PLATFORM_APERIOS
 			wireless->blockingSend(sock);
-#endif
 			writeSize=0;
 		}
 	}
@@ -121,11 +183,12 @@
 int
 Socket::vprintf(const char *fmt, va_list al)
 {
+	/*
   if (state==CONNECTION_CONNECTED && (sendBufSize-writeSize<256)) {
     flush();
     if (sendBufSize-writeSize<256)
       return -1;
-  }
+  }*/
 
   if (state!=CONNECTION_CONNECTED) {
 		if(forwardSock!=NULL)
@@ -133,7 +196,10 @@
 		if(textForward)
 			return vfprintf(stdout, fmt, al);
   } else {
-    int ret=vsprintf((char *)(writeData+writeSize), fmt, al);
+#ifndef PLATFORM_APERIOS
+		ThreadNS::Lock(wireless->getLock());
+#endif
+		int ret=vsnprintf((char *)(writeData+writeSize), sendBufSize-writeSize, fmt, al);
 		writeSize+=ret;
 		flush();
 		return ret;
@@ -150,6 +216,9 @@
 		if(textForward)
 			return ::write(STDOUT_FILENO,buf,size);
 	} else {
+#ifndef PLATFORM_APERIOS
+		ThreadNS::Lock(wireless->getLock());
+#endif
 		byte *destbuf=getWriteBuffer(size);
 		if (destbuf==NULL) return -1;
 		memcpy(destbuf, buf, size);
@@ -167,14 +236,23 @@
   return -1;
 }
 
+std::string Socket::getPeerAddressAsString() const {
+	char buf[20];
+	snprintf(buf,20,"%hhu.%hhu.%hhu.%hhu",(peer_addr>>24)&0xFF,(peer_addr>>16)&0xFF,(peer_addr>>8)&0xFF,peer_addr&0xFF);
+	//const unsigned char *b=(const unsigned char*)&peer_addr;
+	//snprintf(buf,20,"%hhu.%hhu.%hhu.%hhu",b[0],b[1],b[2],b[3]);
+	//snprintf(buf,20,"%hhu.%hhu.%hhu.%hhu",peer_addr&0xFF,(peer_addr>>8)&0xFF,(peer_addr>>16)&0xFF,(peer_addr>>24)&0xFF);
+	return buf;
+}
+
 /*! @file
  * @brief Implements Tekkotsu wireless Socket class, also sout and serr
  * @author alokl (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.17 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.20 $
  * $State: Exp $
- * $Date: 2004/10/04 20:38:05 $
+ * $Date: 2005/08/02 22:24:29 $
  */
 
diff -urdN ../Tekkotsu_2.3/Wireless/Socket.h ./Wireless/Socket.h
--- ../Tekkotsu_2.3/Wireless/Socket.h	Tue Jan 25 15:06:44 2005
+++ ./Wireless/Socket.h	Sun Aug  7 00:11:04 2005
@@ -1,20 +1,38 @@
+//-*-c++-*-
 #ifndef Socket_h_DEFINED
 #define Socket_h_DEFINED
 
 #ifdef PLATFORM_APERIOS
 #  include <ant.h>
 #  include <Types.h>
+#else
+#  include <sys/socket.h>
 #endif
 #include <stdarg.h>
 #include <stdlib.h>
+#include <string>
 
 //! holds socket enumerations and constants
 namespace SocketNS {
 	
+#ifdef PLATFORM_APERIOS
+	const int _SYS_SOCK_STREAM=1; //!< aperios doesn't provide SOCK_STREAM, so we will initialize them to these values
+	const int _SYS_SOCK_DGRAM=2;  //!< aperios doesn't provide SOCK_DGRAM, so we will initialize them to these values
+#else
+	//this is why you shouldn't use #define to declare constant values... grrr
+	const int _SYS_SOCK_STREAM=SOCK_STREAM;
+	const int _SYS_SOCK_DGRAM=SOCK_DGRAM;
+#  ifdef SOCK_STREAM
+#    undef SOCK_STREAM
+#  endif
+#  ifdef SOCK_DGRAM
+#    undef SOCK_DGRAM
+#  endif
+#endif
   //! Specifies transport type. TCP is usually a good idea
   enum TransportType_t {
-    SOCK_STREAM=0, //!< TCP: guaranteed delivery, higher overhead
-    SOCK_DGRAM     //!< UDP: no guarantees, low overhead
+    SOCK_STREAM=_SYS_SOCK_STREAM, //!< TCP: guaranteed delivery, higher overhead
+    SOCK_DGRAM=_SYS_SOCK_DGRAM     //!< UDP: no guarantees, low overhead
   };
 
   //! Internal TCP/UDP Connection State
@@ -69,13 +87,17 @@
   explicit Socket(int sockn)
 		: sock(sockn), trType(), flType(FLUSH_NONBLOCKING), verbosity(0), 
 			endpoint(), state(CONNECTION_CLOSED), sendBufSize(), recvBufSize(),
-			sendSize(0), recvSize(0), writeSize(0), readSize(0),
-			tx(false), rx(false), sendBuffer(), recvBuffer(), sendData(NULL),
-			recvData(NULL), readData(NULL), writeData(NULL), server_port(0),
-      rcvcbckfn(NULL), textForward(false), textForwardBuf(NULL),
+			sendSize(0), sentSize(0), recvSize(0), writeSize(0), readSize(0),
+			tx(false), rx(false), sendBuffer(), sendData(NULL), writeData(NULL), 
+			recvBuffer(), recvData(NULL), readData(NULL), server_port(0), 
+      rcvcbckfn(NULL), peer_addr(-1), peer_port(-1), textForward(false), textForwardBuf(NULL),
       forwardSock(NULL), daemon(false)
-	{ }
-  virtual ~Socket() {} //!< destructor
+	{
+#ifndef PLATFORM_APERIOS
+		endpoint=-1;
+#endif
+	}
+  virtual ~Socket(); //!< destructor
 
   //! use getWriteBuffer to get a memory address to write bytes to, for
   //! subsequent writing to a connection.
@@ -93,7 +115,7 @@
    */
   void write(int size);
 
-  //! Blocking read.
+  //! Blocking read. NOT IMPLEMENTED
   /*!
    * Tries to read upto receive buffer size worth of data from this socket.
    *
@@ -102,7 +124,7 @@
    */
   int read();
 
-  //! getReadBuffer is used with blocking read's
+  //! getReadBuffer is used with blocking read's NOT IMPLEMENTED
   /*!
    * The read(void) and getReadBuffer combo eliminates one buffer copy. You
    * don't need to use getReadBuffer with read(byte*, int)
@@ -123,6 +145,9 @@
    * @return 0 on success
    */
   int setFlushType(FlushType_t fType);
+	
+  //! can choose between different transports; will reset the socket
+  int setTransport(TransportType_t tr);
 
 	//!causes this socket to forward output to stdout if it is not connected, call setForward(NULL) to unset
   void setTextForward() { textForward=true; forwardSock=NULL; }
@@ -149,7 +174,7 @@
    */
   int write(const byte *buf, int size);
 
-  //! Blocking read.
+  //! Blocking read (NOT IMPLEMENTED)
   /*! You might want to consider the read(void) and getReadBuffer combo if you
    * call this often
    *
@@ -158,7 +183,6 @@
    * @param size number of bytes to write
    * @return number of bytes actually read
    */
-  
   int read(byte *buf, int size);
 
   //! It's standard stuff. man 3 printf on most systems should give you more
@@ -183,38 +207,60 @@
    * don't need to call it, unless you're implementing your own write
    */
   void flush();
+	
+  //! returns #daemon
+  bool getDaemon() const { return daemon; }
+	
+	int getPeerAddress() const { return peer_addr; } //!< returns the address of the remote host in local host byte order
+	std::string getPeerAddressAsString() const; //!< returns the address of the remote host as a human-readable string
+	int getPeerPort() const { return peer_port; } //!< returns the port number that the remote host's socket is on
 
 protected:
-	//@{
-	//!private ALOKL_TODO
-  TransportType_t trType;
-  FlushType_t flType;
+  TransportType_t trType; //!< stores choice between transports (UDP or TCP (aka Datagram or Stream))
+  FlushType_t flType; //!< blocking or non-blocking flushes... note that blocking flushes only block on the handoff to the system, not actual transmission (at least under aperios)
 
-  int verbosity;
+  int verbosity; //!< can be used to filter calls to pprintf
 
-#ifndef PLATFORM_APERIOS
-  typedef char* antSharedBuffer;
-  typedef unsigned int antModuleRef;
+#ifdef PLATFORM_APERIOS
+  typedef antSharedBuffer buf_t; //!< the Aibo Networking Toolkit buffer data structure
+  typedef antModuleRef endp_t; //!< the Aibo Networking Toolkit endpoint data structure
+#else
+  typedef char* buf_t; //!< a general buffer
+  typedef int endp_t; //!< a unix socket descriptor
 #endif
 
-  antModuleRef endpoint;
-  ConnectionState state;
+  endp_t endpoint; //!< holds the endpoint data structure for the host OS
+  ConnectionState state; //!< an enum representing the current state of the socket
 
-  int sendBufSize, recvBufSize, sendSize, recvSize, writeSize, readSize;
-  bool tx, rx;
+  int sendBufSize; //!< the size of the buffer for #sendData and #writeData
+  int recvBufSize; //!< the size of the buffer for #readData and #recvData
+  int sendSize; //!< the size of #sendData (total amount of data from last flush)
+  int sentSize; //!< the sent portion of #sendData (amount of data which has been sent to system so far)
+  int recvSize; //!< the size of #recvData (total amount of data returned by system)
+  int writeSize; //!< the size of #writeData (amount of data so far ready to be flushed)
+  int readSize; //!< the size of #readData (not used)
+  bool tx; //!< a flag set when #sendData is in the process of being sent to the system
+  bool rx; //!< not used, see #readData
 
-  antSharedBuffer sendBuffer, recvBuffer;
-  byte *sendData, *recvData;
-  byte *readData, *writeData;
-  int server_port;
-  int (*rcvcbckfn) (char*, int);
+  buf_t sendBuffer; //!< under aperios, a pointer to a shared region with the ip stack; under other OS, a pointer to a normal char * buffer
+  byte *sendData; //!< a region within #sendBuffer, holding data in the process of being sent
+  byte *writeData; //!< a region within #sendBuffer, holds data still being filled in by user code, not yet flushed
 
-  bool textForward;
-	char* textForwardBuf;
-	Socket * forwardSock;
+  buf_t recvBuffer; //!< under aperios, a pointer to a shared region with the ip stack; under other OS, a pointer to a normal char * buffer
+  byte *recvData; //!< a region within #recvBuffer, holding data either just filled in by ip stack (during call to #rcvcbckfn), or in the process of being filled in (any other time)
+  byte *readData; //!< not used (available for double buffering, but not implemented)
+  
+  int server_port; //!< if the socket is a server socket, this is the port it is listening on
+  int (*rcvcbckfn) (char*, int); //!< pointer to callback function, called after #recvData has been filled in
+	
+  int peer_addr; //!< inet address of peer (if connected) or last message sender (if udp and bound); -1 otherwise (in host byte-order, not network byte-order!)
+  int peer_port; //!< port of peer (if connected) or last message sender (if udp and bound); -1 otherwise
 
-  bool daemon;
-	//@}
+  bool textForward; //!< if true, when data is sent to the socket and the socket is not current connected, the data will be sent to stdout (overridden by #forwardSock)
+  char* textForwardBuf; //!< temporary buffer allocated in getWriteBuffer() and freed in write(), if the output is destined for stdout (#textForward)
+  Socket * forwardSock; //!< if non-NULL, output will be sent to this socket if the current socket is not otherwise connected (overrides #textForward)
+
+  bool daemon; //!< if true, the socket will automatically be reopened after any closure (manual or otherwise)
  
 protected:
   Socket(const Socket&); //!< copy constructor, don't call
@@ -229,10 +275,10 @@
  * @author alokl (Creator)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.20 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.23 $
  * $State: Exp $
- * $Date: 2005/01/25 20:06:44 $
+ * $Date: 2005/08/07 04:11:04 $
  */
 
 #endif
diff -urdN ../Tekkotsu_2.3/Wireless/Wireless.cc ./Wireless/Wireless.cc
--- ../Tekkotsu_2.3/Wireless/Wireless.cc	Thu Jan 27 00:40:45 2005
+++ ./Wireless/Wireless.cc	Mon Aug  1 19:17:59 2005
@@ -1,20 +1,23 @@
-#include <OPENR/OSyslog.h>
-#include <OPENR/OPENRAPI.h>
-#include <ant.h>
-#include <EndpointTypes.h>
-#include <TCPEndpointMsg.h>
-#include <UDPEndpointMsg.h>
-#include <cstring>
 #include "Wireless.h"
 #include "Socket.h"
-#include "MMCombo/entry.h"
-
-using namespace SocketNS;
+#include <cstring>
 
 Wireless *wireless=NULL;
 
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OSyslog.h>
+#  include <OPENR/OPENRAPI.h>
+#  include <ant.h>
+#  include <EndpointTypes.h>
+#  include <TCPEndpointMsg.h>
+#  include <UDPEndpointMsg.h>
+#  include "aperios/MMCombo/entry.h"
+
+using namespace SocketNS;
+using namespace std;
+
 Wireless::Wireless ()
-	: ipstackRef(), myOID(), freeSockets()
+	: ipstackRef(), myOID(), freeSockets(), usedSockets()
 {
 	ipstackRef = antStackRef("IPStack");
 	WhoAmI(&myOID);
@@ -28,7 +31,15 @@
 
 Wireless::~Wireless ()
 {
-	// TODO
+	if(usedSockets.size()>0) {
+		cerr << "WARNING: Wireless deleted with open Sockets" << endl;
+		for(list<int>::const_iterator it=usedSockets.begin(); it!=usedSockets.end(); ++it) {
+			delete sockets[*it];
+			sockets[*it]=NULL;
+		}
+		freeSockets.insert(freeSockets.end(),usedSockets.begin(),usedSockets.end());
+		usedSockets.clear();
+	}
 }
 
 Socket* Wireless::socket(TransportType_t ttype)
@@ -42,11 +53,12 @@
 			|| (recvsize + sendsize) <= 256) return sockets[0];
 	int sock_num=freeSockets.front();
 	freeSockets.pop_front();
+	usedSockets.push_back(sock_num);
 
 	sockets[sock_num]=new Socket(sock_num);
-	sockets[sock_num]->trType=ttype;
 	sockets[sock_num]->sendBufSize=sendsize;
 	sockets[sock_num]->recvBufSize=recvsize;
+	sockets[sock_num]->setTransport(ttype);
 
 	// setup send buffer
 	antEnvCreateSharedBufferMsg sendBufferMsg(sendsize*2);
@@ -80,7 +92,7 @@
 	sockets[sock]->server_port = port;
 	sockets[sock]->init();
 
-	if (sockets[sock]->trType==SOCK_STREAM) {
+	if (sockets[sock]->trType==SocketNS::SOCK_STREAM) {
 		// create endpoint
 		antEnvCreateEndpointMsg tcpCreateMsg( EndpointType_TCP, ( sockets[sock]->recvBufSize + sockets[sock]->sendBufSize ) * 3 );
 		tcpCreateMsg.Call( ipstackRef, sizeof( tcpCreateMsg ) );
@@ -139,6 +151,8 @@
 		connectMsg.continuation = ( void * ) sock;
 
 		connectMsg.Send( ipstackRef, myOID, Extra_Entry[entryConnectCont], sizeof( connectMsg ) );
+		sockets[sock]->peer_addr=connectMsg.fAddress.Address();
+		sockets[sock]->peer_port=connectMsg.fPort;
 
 		sockets[sock]->state = CONNECTION_CONNECTING;
 		return 0;
@@ -152,6 +166,8 @@
 			connectMsg.continuation = ( void * ) sock;
 
 			connectMsg.Send( ipstackRef, myOID, Extra_Entry[entryConnectCont], sizeof( connectMsg ) );
+			sockets[sock]->peer_addr=connectMsg.address.Address();
+			sockets[sock]->peer_port=connectMsg.port;
 
 			sockets[sock]->state = CONNECTION_CONNECTED;
 			//std::cout << "Sock " << sock << " connected via UDP to IP " << ipaddr << " port " << port << std::flush << std::endl;
@@ -182,6 +198,8 @@
 					// no use recycling since its a resource issue
 					return;
 				}
+			sockets[sock]->peer_addr=listenMsg->fAddress.Address();
+			sockets[sock]->peer_port=listenMsg->fPort;
 
 			sockets[sock]->state = CONNECTION_CONNECTED;
 			//sockets[sock]->local_ipaddr = listenMsg->lAddress.Address();
@@ -417,6 +435,8 @@
 					// This allows us to send UDP messages to any address instead of
 					// hard-coding a specific address beforehand
 
+					sockets[sock]->peer_addr=receiveMsg->address.Address();
+					sockets[sock]->peer_port=receiveMsg->port;
 					if ( !strncmp( "connection request", ( char * ) sockets[sock]->recvData, 18 ) )
 						{
 							// clear this message from the receiving buffer
@@ -471,6 +491,8 @@
 			closeMsg.Send( ipstackRef, myOID, Extra_Entry[entryCloseCont], sizeof( closeMsg ) );
 		}
 
+	sockets[sock]->peer_addr=sockets[sock]->peer_port=-1;
+
 	sockets[sock]->state = CONNECTION_CLOSING;
 }
 
@@ -506,6 +528,7 @@
 		return;
 
 	sockets[sock]->state = CONNECTION_CLOSED;
+	sockets[sock]->peer_addr=sockets[sock]->peer_port=-1;
 	if ( sockets[sock]->server_port > 0 && sockets[sock]->daemon )
 		{
 			// recycle if server
@@ -517,9 +540,506 @@
 			delete( sockets[sock] );
 			sockets[sock] = NULL;
 			freeSockets.push_back( sock );
+			for(list<int>::iterator it=usedSockets.begin(); it!=usedSockets.end(); ++it)
+				if(*it==sock) {
+					usedSockets.erase(it);
+					break;
+				}
+		}
+}
+
+#else // PLATFORM_LOCAL
+#  include "IPC/Thread.h"
+#  include <sys/types.h>
+#  include <sys/socket.h>
+#  include <netinet/in.h>
+#  include <netdb.h>
+#  include <arpa/inet.h>
+#  include <fcntl.h>
+#  include <unistd.h>
+#  include <iostream>
+#  include <errno.h>
+
+using namespace std;
+
+
+Wireless::Wireless ()
+: interruptChk(-1), interruptCtl(-1), rfds(), wfds(), efds(), fdsMax(0), freeSockets(), usedSockets()
+{
+	sockets[0]=new DummySocket(0);
+	for (int sock = 1; sock < WIRELESS_MAX_SOCKETS; sock++) {
+		sockets[sock]=NULL;
+		freeSockets.push_back(sock);
+	}
+	int p[2];
+	pipe(p);
+	interruptChk=p[0];
+	interruptCtl=p[1];
+	fdsMax=interruptChk;
+	if( ::fcntl(interruptChk,F_SETFL,O_NONBLOCK) ==-1 ) {
+		perror("Wireless::Wireless(): fcntl");
+	}
+	FD_ZERO(&rfds);
+	FD_SET(interruptChk,&rfds);
+	FD_ZERO(&wfds);
+	FD_ZERO(&efds);
+}
+
+Wireless::~Wireless ()
+{
+	ThreadNS::Lock l(getLock());
+	::close(interruptChk);
+	::close(interruptCtl);
+	interruptChk=interruptCtl=-1;
+	if(usedSockets.size()>0) {
+		cerr << "WARNING: Wireless deleted with open Sockets" << endl;
+		for(list<int>::const_iterator it=usedSockets.begin(); it!=usedSockets.end(); ++it) {
+			delete sockets[*it];
+			sockets[*it]=NULL;
+		}
+		freeSockets.insert(freeSockets.end(),usedSockets.begin(),usedSockets.end());
+		usedSockets.clear();
+	}
+}
+
+void Wireless::setReceiver(int sock, int (*rcvcbckfn) (char*, int) ) {
+	sockets[sock]->rcvcbckfn=rcvcbckfn;
+}
+
+void Wireless::close(int sock) {
+	ThreadNS::Lock l(getLock());
+	if ( sock <= 0 || sock >= WIRELESS_MAX_SOCKETS || sockets[sock] == NULL)
+		return;
+	sockets[sock]->flush();
+	sockets[sock]->peer_port = sockets[sock]->peer_addr = -1;
+	if(sockets[sock]->daemon) {
+		if(::close(sockets[sock]->endpoint)==-1)
+			perror("Wireless::close(): close");
+		sockets[sock]->endpoint=-1;
+		sockets[sock]->state = CONNECTION_CLOSED;
+		listen(sock,sockets[sock]->server_port);
+	} else {
+		bool found=false;
+		for(list<int>::iterator it=usedSockets.begin(); it!=usedSockets.end(); ++it) {
+			if(*it==sock) {
+				usedSockets.erase(it);
+				found=true;
+				break;
+			}
+		}
+		if(!found) {
+			cerr << "WARNING: Could not find socket " << sock << " in usedSockets list of size " << usedSockets.size() << endl;
+			return;
+		}
+		Socket * s=sockets[sock];
+		sockets[sock] = NULL;
+		wakeup(s); //avoid select giving error about bad FD
+		freeSockets.push_back( sock );
+	}
+}
+
+int Wireless::connect(int sock, const char* ipaddr, int port) {
+	ThreadNS::Lock l(getLock());
+	if ( port <= 0 || port >= 65535 || sock <= 0 || sock >= WIRELESS_MAX_SOCKETS
+			 || sockets[sock] == NULL || sockets[sock]->state != CONNECTION_CLOSED && sockets[sock]->trType!=SocketNS::SOCK_DGRAM )
+		return -1;
+	
+	if(sockets[sock]->endpoint==-1)
+		sockets[sock]->init();
+	int endpoint=sockets[sock]->endpoint;
+
+	sockaddr_in m_addr;
+	m_addr.sin_family = AF_INET;
+	m_addr.sin_port = htons ( port );
+	struct hostent* hostips = gethostbyname(ipaddr);
+	if ( hostips==NULL) {
+		cerr << "Wireless::connect(): gethostbyname returned NULL, h_errno==" << h_errno;
+		switch(h_errno) {
+		case HOST_NOT_FOUND: cerr << " (HOST_NOT_FOUND)" << endl; break;
+		case NO_ADDRESS: cerr << " (NO_ADDRESS)" << endl; break;
+			//case NO_DATA: cerr << " (NO_DATA)" << endl; break; //NO_DATA==NO_ADDRESS
+		case NO_RECOVERY: cerr << " (NO_RECOVERY)" << endl; break;
+		case TRY_AGAIN: cerr << " (TRY_AGAIN)" << endl; break;
+		default: cerr << " (unknown error code!)" << endl; break;
+		}		
+		return -1;
+	}
+	memcpy(&m_addr.sin_addr,hostips->h_addr_list[0],sizeof(m_addr.sin_addr));
+	
+	int status = ::connect ( endpoint, ( sockaddr * ) &m_addr, sizeof ( m_addr ) );
+	if ( status == 0 )
+		sockets[sock]->state=CONNECTION_CONNECTED;
+	else if(errno==EINPROGRESS)
+		sockets[sock]->state=CONNECTION_CONNECTING;
+	else {
+		perror("Wireless::connect(): connect");
+		return -1;
+	}
+	sockets[sock]->peer_port = port;
+	sockets[sock]->peer_addr = ntohl(m_addr.sin_addr.s_addr);
+	//cout << "connecting " << sockets[sock]->getPeerAddressAsString() << ' ' << sockets[sock]->getPeerPort() << "... " <<status << endl;
+	//this will allow sock to be added to wfds so we can tell when the connection goes through
+	wakeup();
+	return 0;
+}
+
+int Wireless::listen(int sock, int port) {
+  ThreadNS::Lock l(getLock());
+  if ( port <= 0 || port >= 65535 || sock <= 0 || sock >= WIRELESS_MAX_SOCKETS
+       || sockets[sock] == NULL || sockets[sock]->state != CONNECTION_CLOSED )
+		return -1;
+  sockets[sock]->server_port = port;
+  sockets[sock]->init();
+  int endpoint=sockets[sock]->endpoint;
+  if ( endpoint<0 )
+	return -1;
+  sockaddr_in m_addr;
+  m_addr.sin_family = AF_INET;
+  m_addr.sin_addr.s_addr = INADDR_ANY;
+  m_addr.sin_port = htons ( port );
+	
+	int bind_return = ::bind ( endpoint,( struct sockaddr * ) &m_addr,sizeof ( m_addr ) );
+	if ( bind_return == -1 ) {
+		perror("Wireless::listen: bind");
+		return -1;
+	}
+	if(sockets[sock]->trType==SocketNS::SOCK_STREAM) {
+		int listen_return = ::listen ( endpoint, MAXCONNECTIONS );
+		if ( listen_return == -1 ) {
+			perror("Wireless::listen: listen");
+			return -1;
+		}
+	}
+	sockets[sock]->state = CONNECTION_LISTENING;
+	//this will allow sock to be added to rfds so we can tell when a connection is available
+	wakeup();
+	return 0;
+}
+
+Socket* Wireless::socket(TransportType_t ttype) {
+	return socket(ttype, WIRELESS_DEF_RECV_SIZE, WIRELESS_DEF_SEND_SIZE);
+}
+Socket* Wireless::socket(TransportType_t ttype, int recvsize, int sendsize) {
+	ThreadNS::Lock l(getLock());
+	if (freeSockets.empty()
+			|| (recvsize + sendsize) <= 256) return sockets[0];
+	int sock_num=freeSockets.front();
+	freeSockets.pop_front();
+	usedSockets.push_back(sock_num);
+	
+	sockets[sock_num]=new Socket(sock_num);
+	
+	sockets[sock_num]->sendBufSize=sendsize;
+	sockets[sock_num]->sendBuffer=new char[sockets[sock_num]->sendBufSize*2];
+	//double buffered sending
+	sockets[sock_num]->sendData=(byte*)sockets[sock_num]->sendBuffer;
+	sockets[sock_num]->writeData=(byte*)sockets[sock_num]->sendBuffer+sockets[sock_num]->sendBufSize;
+
+	sockets[sock_num]->recvBufSize=recvsize;
+	sockets[sock_num]->recvBuffer = new char[sockets[sock_num]->recvBufSize];
+	sockets[sock_num]->recvData=(byte*)sockets[sock_num]->recvBuffer; //reading is single buffered
+	
+	sockets[sock_num]->setTransport(ttype);
+	
+	return sockets[sock_num]; 
+}
+
+/*! There's probably better ways to implement this...
+ *  (run through the interface list?  How does ifconfig do it?) */
+uint32 Wireless::getIPAddress(unsigned int idx/*=0*/) {
+	char buf[ 255 ];
+	if(gethostname( buf, 255)!=0) {
+		perror("Wireless::getIPAddress(): gethostname");
+		return 0;
+	}
+	struct hostent * h = gethostbyname( buf );
+	if(h==NULL) {
+		herror("Wireless::getIPAddress(): gethostbyname");
+		return 0;
+	}
+	//check to make sure 'idx' is valid
+	for(unsigned int x=0; x<=idx; x++)
+		if(h->h_addr_list[x]==NULL)
+			return 0;
+	//if we got here, it's valid
+	return *(uint32*)h->h_addr_list[idx];
+}
+
+void
+Wireless::send(int sock)
+{
+	ThreadNS::Lock l(getLock());
+	if ( sock <= 0 || sock >= WIRELESS_MAX_SOCKETS || sockets[sock] == NULL
+	    || sockets[sock]->state != CONNECTION_CONNECTED || sockets[sock]->sendSize <= 0 )
+		return;
+	
+	//we could defer all sending to the poll, but let's give a shot at sending it out right away to reduce latency
+	int s=sockets[sock]->endpoint;
+	int sent=::send(s,sockets[sock]->sendData+sockets[sock]->sentSize,sockets[sock]->sendSize-sockets[sock]->sentSize,0);
+	if(sent==-1) {
+		perror("Wireless::pollProcess(): send");
+		sockets[sock]->tx = false;
+		sockets[sock]->sendSize = sockets[sock]->sentSize = 0;
+	} else {
+		sockets[sock]->sentSize+=sent;
+		if(sockets[sock]->sentSize==sockets[sock]->sendSize) {
+			sockets[sock]->tx = false;
+			sockets[sock]->sendSize = sockets[sock]->sentSize = 0;
+			sockets[sock]->flush();
+		} else {
+			sockets[sock]->tx = true;
+			//more work will be done in poll()
+			//this will wake up the poll thread to make it check for pending writes (signaled by tx flag)
+			wakeup();
+		}
+	}
+}
+
+void
+Wireless::blockingSend(int sock)
+{
+	ThreadNS::Lock l(getLock());
+	if ( sock <= 0 || sock >= WIRELESS_MAX_SOCKETS || sockets[sock] == NULL
+	    || sockets[sock]->state != CONNECTION_CONNECTED || sockets[sock]->sendSize <= 0 )
+		return;
+	
+	while(sockets[sock]->sentSize<sockets[sock]->sendSize) {
+		fd_set bs_wfds;
+		FD_ZERO(&bs_wfds);
+		FD_SET(sockets[sock]->endpoint, &bs_wfds);
+		int retval = select(sockets[sock]->endpoint+1, NULL, &bs_wfds, NULL, NULL);
+		if(retval==0)
+			continue;
+		if(retval==-1) {
+			perror("Wireless::poll(): select");
+			return;
 		}
+		if(sockets[sock]->tx) //block on leftover non-blocking send
+			continue;
+		int sent=::send(sockets[sock]->endpoint,sockets[sock]->sendData+sockets[sock]->sentSize,sockets[sock]->sendSize-sockets[sock]->sentSize,0);
+		if(sent==-1) {
+			if(errno==EAGAIN) {
+				cerr << "Wireless::blockingSend(): send() was not ready, even though select() said it was" << endl;
+				continue;
+			}
+			perror("Wireless::blockingSend(): send");
+			sockets[sock]->tx = false;
+			sockets[sock]->sendSize = sockets[sock]->sentSize = 0;
+			return;
+		}
+		sockets[sock]->sentSize+=sent;
+	}
+	sockets[sock]->sendSize = sockets[sock]->sentSize = 0;
 }
 
+void Wireless::pollSetup() {
+	FD_ZERO(&rfds);
+	FD_ZERO(&wfds);
+	FD_ZERO(&efds);
+	FD_SET(interruptChk, &rfds);
+
+	fdsMax=interruptChk;
+	ThreadNS::Lock l(getLock());
+	//cout << "pollSetup " << usedSockets.size() << endl;
+	for(list<int>::const_iterator it=usedSockets.begin(); it!=usedSockets.end(); ++it) {
+		if(sockets[*it]==NULL) {
+			cerr << "ERROR: Wireless::pollSetup() encountered NULL socket " << *it << endl;
+			continue;
+		}
+		if(sockets[*it]->endpoint==-1) {
+			cerr << "ERROR Wireless::pollSetup() encountered bad endpoint " << *it << endl;
+			continue;
+		}
+		if(sockets[*it]->state!=CONNECTION_CLOSED && sockets[*it]->state!=CONNECTION_ERROR)
+			FD_SET(sockets[*it]->endpoint, &rfds);
+		if(sockets[*it]->state==CONNECTION_CONNECTING || sockets[*it]->tx)
+			FD_SET(sockets[*it]->endpoint, &wfds);
+		FD_SET(sockets[*it]->endpoint, &efds);
+		if(sockets[*it]->endpoint>fdsMax)
+			fdsMax=sockets[*it]->endpoint;
+	}
+}
+
+/*! @param tv  how long to wait -- NULL will wait indefinitely until a socket event occurs
+ *  @return true if there was a socket event to process, false if timed out */
+bool Wireless::pollTest(struct timeval* tv) {
+	int retval = select(fdsMax+1, &rfds, &wfds, &efds, tv);
+	if(retval==-1)
+		perror("Wireless::pollTest(): select");
+	return (retval!=0);
+}
+
+void Wireless::pollProcess() {
+	ThreadNS::Lock l(getLock());
+	if(FD_ISSET(interruptChk,&rfds)) {
+		//wakeup sent to handle non-blocking write
+		int res=1;
+		//cout << "Clearing interrupts..." << flush;
+		while(res>0) {
+			Socket * del=NULL;
+			res=::read(interruptChk,&del,sizeof(del));
+			//cout << ' ' << del << flush;
+			if(del!=NULL)
+				delete del;
+		}
+		//cout << " done" << endl;
+	}
+	for(list<int>::const_iterator it=usedSockets.begin(); it!=usedSockets.end(); ++it) {
+		if(sockets[*it]==NULL) {
+			cerr << "NULL socket " << *it << endl;
+			continue;
+		}
+		if(sockets[*it]->endpoint==-1) {
+			cerr << "bad endpoint " << *it << endl;
+			continue;
+		}
+		int s=sockets[*it]->endpoint;
+		if(FD_ISSET(s,&rfds)) {
+			//cout << *it << " set in read" << endl;
+			if(sockets[*it]->state==CONNECTION_CONNECTING) {
+				//cout << "Wireless::pollProcess(): read set on connecting" << endl;
+				sockets[*it]->state=CONNECTION_CONNECTED;
+			}
+			if(sockets[*it]->state==CONNECTION_LISTENING) {
+				if(sockets[*it]->trType==SocketNS::SOCK_STREAM) {
+					sockaddr_in m_addr;
+					socklen_t addrlen=sizeof(m_addr);
+					int n=accept(s,(sockaddr*)&m_addr,&addrlen);
+					if(n==-1) {
+						perror("Wireless::pollProcess(): accept");
+						continue;
+					}
+					sockets[*it]->peer_addr=ntohl(m_addr.sin_addr.s_addr);
+					sockets[*it]->peer_port=ntohs(m_addr.sin_port);
+					//this closes the server socket -- we'll want to address this
+					if(::close(s)==-1)
+						perror("Wireless::pollProcess(): close");
+					s=sockets[*it]->endpoint=n;
+					sockets[*it]->state=CONNECTION_CONNECTED;
+					//cout << "Accepted connection" << endl;
+				} else {
+					//cout << "UDP accept" << endl;
+					sockaddr_in m_addr;
+					socklen_t addrlen=sizeof(m_addr);
+					sockets[*it]->recvSize = recvfrom(s,sockets[*it]->recvData,sockets[*it]->recvBufSize,0,(sockaddr*)&m_addr,&addrlen);
+					if(sockets[*it]->recvSize==-1) {
+						perror("Wireless::pollProcess(): acception recvfrom");
+						continue;
+					}
+					/* //this can cause trouble for broadcasts... we'll make the user call 'connect' themselves if they want to send back
+					 //cout << "connecting..." << endl;
+					int ret = ::connect ( s, (sockaddr*) &m_addr, sizeof ( m_addr ) );
+					if ( ret==-1 && errno!=EINPROGRESS ) {
+						perror("Wireless::pollProcess(): connect");
+						continue;
+					}
+					//cout << "UDP accepted!" << endl;
+					sockets[*it]->state=CONNECTION_CONNECTING;
+					 */
+					sockets[*it]->peer_addr=ntohl(m_addr.sin_addr.s_addr);
+					sockets[*it]->peer_port=ntohs(m_addr.sin_port);
+					if(sockets[*it]->recvSize!=0) {
+						//cout << "Read " << sockets[*it]->recvSize << " bytes " << sockets[*it]->rcvcbckfn << endl;
+						if ( !strncmp( "connection request", ( char * ) sockets[*it]->recvData, 18 ) ) {
+							// clear this message from the receiving buffer
+							if ( sockets[*it]->state != CONNECTION_CONNECTED )
+								connect( *it, sockets[*it]->getPeerAddressAsString().c_str(), sockets[*it]->getPeerPort() );
+						} else if ( sockets[*it]->rcvcbckfn != NULL )
+							sockets[*it]->rcvcbckfn( ( char * ) sockets[*it]->recvData, sockets[*it]->recvSize );
+						sockets[*it]->recvSize = 0;
+					}
+				}
+			} else 	if(sockets[*it]->state==CONNECTION_CONNECTED || sockets[*it]->state==CONNECTION_CLOSING) {
+				sockets[*it]->recvSize = recvfrom(s,sockets[*it]->recvData,sockets[*it]->recvBufSize,0,NULL,NULL);
+				if(sockets[*it]->recvSize==-1) {
+					if(errno!=EAGAIN) { //may have just completed connection, not a problem
+						if(errno==ECONNREFUSED) {
+							cerr << "connection refused: endpoint=" << s << " sock=" << *it << " Socket=" << sockets[*it] << endl;
+							list<int>::const_iterator tmp=it;
+							//a UDP server could come in here
+							if(!sockets[*it]->daemon) //don't decrement if the socket is going to stay open
+								--it;
+							close(*tmp);
+							continue;
+						}
+						perror("Wireless::pollProcess(): recvfrom");
+					}
+				} else if(sockets[*it]->recvSize==0) {
+					list<int>::const_iterator tmp=it--;
+					close(*tmp);
+					//cout << "closed connection" << endl;
+					continue;
+				} else {
+					//cout << "Read " << sockets[*it]->recvSize << " bytes " << sockets[*it]->rcvcbckfn << endl;
+					if ( sockets[*it]->rcvcbckfn != NULL )
+						sockets[*it]->rcvcbckfn( ( char * ) sockets[*it]->recvData, sockets[*it]->recvSize );
+					sockets[*it]->recvSize = 0;
+				}
+			} else {
+				int dropped=0,n=0;
+				char buf[100];
+				while((n=recvfrom(s,buf,100,0,NULL,NULL))>0)
+					dropped+=n;
+				cerr << "Wireless::pollProcess(): socket (sys=" << s << ", tk="<<*it<<") read flag in bad state (" << sockets[*it]->state << "), " << dropped << " bytes were dropped, ending with:" << endl;
+				for(int i=0; i<n; i++)
+					if(isprint(buf[i]))
+						cerr << buf[i];
+					else
+						cerr << '.';
+				cerr << endl;
+			}
+		}
+		if(FD_ISSET(s,&wfds)) {
+			//cout << *it << " set in write" << endl;
+			if(sockets[*it]->state==CONNECTION_CONNECTING) {
+				sockets[*it]->state=CONNECTION_CONNECTED;
+			} else if(sockets[*it]->state==CONNECTION_CONNECTED) {
+				if(!sockets[*it]->tx) {
+					//cerr << "Wireless::pollProcess(): write available on non-tx socket??" << endl;
+					//can happen on a refused connection
+				} else {
+					int sent=::send(s,sockets[*it]->sendData+sockets[*it]->sentSize,sockets[*it]->sendSize-sockets[*it]->sentSize,0);
+					if(sent==-1) {
+						perror("Wireless::pollProcess(): send");
+						sockets[*it]->tx = false;
+						sockets[*it]->sendSize = sockets[*it]->sentSize = 0;
+					} else {
+						sockets[*it]->sentSize+=sent;
+						if(sockets[*it]->sentSize==sockets[*it]->sendSize) {
+							sockets[*it]->tx = false;
+							sockets[*it]->sendSize = sockets[*it]->sentSize = 0;
+							sockets[*it]->flush();
+						}
+					}
+				}
+			} else {
+				cerr << "Wireless::pollProcess(): socket write flag in bad state" << endl;
+			}
+		}
+		if(FD_ISSET(s,&efds)) {
+			cerr << "Socket exception: " << flush;
+			int err=0;
+			socklen_t errlen=sizeof(err);
+			if ( ::getsockopt ( s, SOL_SOCKET, SO_ERROR, &err, &errlen ) == -1 ) {
+				perror("Wireless::processPoll(): getsockopt");
+			}
+			cerr << err << " endpoint=" << s << " sock=" << *it << " Socket=" << sockets[*it] << endl;
+		}
+	}
+}
+
+/*! @param del if non-NULL, will cause the socket to be closed and deleted */
+void Wireless::wakeup(Socket * del/*=NULL*/) {
+	::write(interruptCtl,&del,sizeof(del)); 
+}
+
+ThreadNS::Lock& Wireless::getLock() {
+	static ThreadNS::Lock lock;
+	return lock;
+}
+
+#endif
+
 /*! @file
  * @brief Interacts with the system to provide networking services
  * @author alokl (Creator)
@@ -528,9 +1048,9 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.21 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.25 $
  * $State: Exp $
- * $Date: 2005/01/27 05:40:45 $
+ * $Date: 2005/08/01 23:17:59 $
  */
 
diff -urdN ../Tekkotsu_2.3/Wireless/Wireless.h ./Wireless/Wireless.h
--- ../Tekkotsu_2.3/Wireless/Wireless.h	Thu Jan 27 00:40:46 2005
+++ ./Wireless/Wireless.h	Sun Aug  7 00:11:04 2005
@@ -1,12 +1,18 @@
-
+//-*-c++-*-
 #ifndef Wireless_h_DEFINED
 #define Wireless_h_DEFINED
 
-#include <OPENR/OObject.h>
-#include <OPENR/OSubject.h>
-#include <OPENR/OObserver.h>
-#include <ant.h>
-//#include "MMCombo/def.h"
+#ifdef PLATFORM_APERIOS
+#  include <OPENR/OObject.h>
+#  include <OPENR/OSubject.h>
+#  include <OPENR/OObserver.h>
+#  include <ant.h>
+#else
+namespace ThreadNS {
+	class Lock;
+}
+typedef unsigned int uint32;
+#endif
 #include "Socket.h"
 #include "DummySocket.h"
 #include <list>
@@ -17,11 +23,8 @@
 //! Tekkotsu wireless class
 /*!
  * For more information on using wireless, please read the following tutorials:
- * - <a href="../AiboMon.html">TekkotsuMon</a>
+ * - <a href="../TekkotsuMon.html">TekkotsuMon</a>
  * - <a href="../Wireless.html">TCP/IP</a>
- * - <a href="../RemoteProcess.html">Remote Processing OPENR</a>
- * Tekkotsu Wireless and Remote Processing OPENR provide different
- * interfaces to comparable wireless functionality.
  *
  * The networking interface needs more documentation.  It also needs a
  * cleanup.  In the mean time, take a look at the TekkotsuMon objects
@@ -64,7 +67,8 @@
 
   //! The socket waits for incoming connections.
   /*! That is, it acts like a server. If a connection is established and
-   * later broken, it resumes waiting for new connections.
+   * later broken, it resumes waiting for new connections if the
+   * socket's daemon flag is set.
    */
   int listen(int sock, int port);
 
@@ -74,6 +78,8 @@
   void setReceiver(int sock, int (*rcvcbckfn) (char*, int) );
   //! sets the socket to be a daemon (recycles on close)
   void setDaemon(int sock, bool val=true) { sockets[sock]->daemon=val; }
+  //! sets the socket to be a daemon (recycles on close)
+  bool getDaemon(int sock) { return sockets[sock]->daemon; }
 	//! closes and destroys non server, daemon sockets
   void close(int sock);
 
@@ -82,8 +88,9 @@
   /*! You shouldn't need to use it, since asking sockets for write
    * and read buffers does the necessary sanity checks
    */
-  bool isConnected(int sock) { return sockets[sock]->state
-                                        ==CONNECTION_CONNECTED; }
+  bool isConnected(int sock) {
+    return sockets[sock]==NULL ? false : sockets[sock]->state==CONNECTION_CONNECTED;
+  }
   bool isReady(int sock) { return !sockets[sock]->tx; }
   bool hasData(int sock) { return !sockets[sock]->rx; }
   //@}
@@ -96,6 +103,8 @@
     { setReceiver(sobj->sock, rcvcbckfn); }
   void setDaemon(Socket &sobj, bool val=true) { setDaemon(sobj.sock, val); }
   void setDaemon(Socket *sobj, bool val=true) { setDaemon(sobj->sock, val); }
+  bool getDaemon(Socket &sobj) { return getDaemon(sobj.sock); }
+  bool getDaemon(Socket *sobj) { return getDaemon(sobj->sock); }
   int listen(Socket &sobj, int port) { return listen(sobj.sock, port); } 
   int listen(Socket *sobj, int port) { return listen(sobj->sock, port); } 
   int connect(Socket &sobj, const char* ipaddr, int port)
@@ -121,7 +130,7 @@
   void blockingSend(int sock);
   //@}
   
-
+#ifdef PLATFORM_APERIOS
   //@{
   //! callback function for communicating
   //! with Aperios Networking Toolkit. You should not call this.
@@ -133,13 +142,35 @@
   void CloseCont  (void* msg);
   //@}
 
-private:
+#else
+	void pollSetup(); //!< on non-aperios, set up structures to be checked in pollTest() (may want to protect this with a mutex lock)
+	bool pollTest(struct timeval* tv); //!< on non-aperios, check to see any network communication has occurred
+	void pollProcess(); //!< on non-aperios, process callbacks and state changes as signaled in pollTest() (may want to protect this with a mutex lock)
+	void wakeup(Socket * del=NULL); //!< writes @a del on #interruptCtl, breaking out of a pending pollTest() and thus giving an opportunity to change the contents of the FD sets being used;
+	
+#endif
+
+protected:
+	friend class Socket; //so socket can lock as well
+	static const int MAXCONNECTIONS = 5; //!< the maximum number of connections which can be queued when listening
+
 	//@{
 	//!private ALOKL_TODO
+#ifdef PLATFORM_APERIOS
   antStackRef ipstackRef;
   OID myOID;
+#else
+  static ThreadNS::Lock& getLock(); //! returns the lock to use during wireless operations
+  int interruptChk;
+  int interruptCtl;
+  fd_set rfds;
+  fd_set wfds;
+  fd_set efds;
+  int fdsMax;
+#endif
   Socket* sockets[WIRELESS_MAX_SOCKETS];
-  list<int> freeSockets;
+  std::list<int> freeSockets;
+  std::list<int> usedSockets;
 	//@}
 
 private:
@@ -157,10 +188,10 @@
  * @verbinclude CMPack_license.txt
  *
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
- * $Revision: 1.17 $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.22 $
  * $State: Exp $
- * $Date: 2005/01/27 05:40:46 $
+ * $Date: 2005/08/07 04:11:04 $
  */
 
 #endif // Wireless_h_DEFINED
diff -urdN ../Tekkotsu_2.3/Wireless/ionetstream.h ./Wireless/ionetstream.h
--- ../Tekkotsu_2.3/Wireless/ionetstream.h	Sat Mar  1 15:53:43 2003
+++ ./Wireless/ionetstream.h	Wed Dec 31 19:00:00 1969
@@ -1,484 +0,0 @@
-#ifndef __NETSTREAM_H__
-#define __NETSTREAM_H__
-
-#include <cstdio>
-#include <cstring>
-
-#include <iostream>
-#include <iosfwd>
-#include <streambuf.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <ctype.h>
-#include <unistd.h>
-
-#include <string.h>
-#include <string>
-
-#define INVALID_SOCKET (~0)
-
-using namespace std;
-
-template <class charT, class traits>
-class basic_netbuf : public streambuf {
-  public:
-  //  Types:
-	typedef charT                     char_type;
-	typedef typename traits::int_type int_type;
-	typedef typename traits::pos_type pos_type;
-	typedef typename traits::off_type off_type;
-	typedef traits                    traits_type;
-  //Constructors/Destructors:
-	basic_netbuf();
-	basic_netbuf(const IPaddr& addr);
-	basic_netbuf(const IPaddr::ipnum_t& host, const IPaddr::ipport_t port);
-	basic_netbuf(const IPaddr::const_ipname_t& host, const IPaddr::ipport_t port);
-	basic_netbuf(size_t buf_in_size, size_t buf_out_size);
-	virtual ~basic_netbuf();
-	
-	
-	
-  //basic_netbuf Functions:
-  public:
-	virtual bool			open(const IPaddr& addr);
-	virtual bool			open(const IPaddr::const_ipname_t& str);
-	virtual bool			open(const IPaddr::ipnum_t& addr, const IPaddr::ipport_t& aPort);
-	virtual bool			open(const IPaddr::const_ipname_t& ahost, unsigned int aPort) { return open(IPaddr(ahost,aPort)); }
-	virtual bool			is_open()	const { return (sock!=INVALID_SOCKET); }
-	virtual void			close();
-
-	virtual void			setEcho(bool val = true) { is_echoing = val; }
-	virtual bool			getEcho() { return is_echoing; }
-  protected:
-    static void			printBuffer(const char* buf, int buflen, const char* header);
-    void					Init() { Init(def_buf_in_size, def_buf_out_size); }
-    void					Init(size_t insize, size_t outsize);
-
-	
-  //Inherited Functions:
-  public:
-	virtual void			in_sync(); //users shouldn't need to call this directly... but can if want to
-	virtual void			out_flush();
-
-  protected:
-	//  lib.streambuf.virt.get Get area:
-	virtual streamsize	showmanyc();
-	//	virtual streamsize xsgetn(char_type* s, streamsize n);
-	virtual int_type		underflow();
-	virtual int_type		uflow();
-	
-	//  lib.streambuf.virt.pback Putback:
-	//	virtual int_type pbackfail(int_type c = traits::eof() );
-	//  lib.streambuf.virt.put Put area:
-	//	virtual streamsize xsputn(const char_type* s, streamsize n);
-	virtual int_type		overflow(int_type c  = traits::eof());
-	
-	//  lib.streambuf.virt.buffer Buffer management and positioning:
-	//	virtual _Myt basic_netbuf<char_type, traits_type>* setbuf(char_type* s, streamsize n);
-	//	virtual pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out);
-	//	virtual pos_type seekpos(pos_type sp, ios_base::openmode which = ios_base::in | ios_base::out);
-	virtual int			sync();
-	//  lib.streambuf.virt.locales Locales:
-	//	virtual void imbue(const locale &loc);
-  //Data:
-  protected:
-	charT *buf_in, *buf_out;
-	bool using_buf_in, using_buf_out;
-	static const size_t def_buf_in_size;
-	static const size_t def_buf_out_size;
-	int sock;
-	bool is_echoing;
-};
-template <class charT, class traits>
-const size_t basic_netbuf<charT,traits>::def_buf_in_size=1<<8;
-template <class charT, class traits>
-const size_t basic_netbuf<charT,traits>::def_buf_out_size=1<<12;
-
-
-template <class charT, class traits>
-class basic_iNetStream
-	: public istream
-{
-public:
-	typedef charT                     char_type;
-	typedef typename traits::int_type int_type;
-	typedef typename traits::pos_type pos_type;
-	typedef typename traits::off_type off_type;
-	typedef traits                    traits_type;
-	//  lib.ifstream.cons Constructors:
-	basic_iNetStream() : istream(&nb), nb() {}
-	basic_iNetStream(const IPaddr::ipnum_t& host, const IPaddr::ipport_t port) : basic_iNetStream(&nb), nb(host,port) {}
-	basic_iNetStream(const IPaddr::const_ipname_t& host, const IPaddr::ipport_t port) : basic_iNetStream(&nb), nb(host,port) {}
-	basic_iNetStream(const IPaddr& addr) : istream(&nb), nb(addr) {}
-	basic_iNetStream(size_t buf_in_size, size_t buf_out_size) : istream(&nb), nb(buf_in_size,buf_out_size) {}
-	//  lib.ifstream.members Members:
-	inline basic_netbuf<charT, traits>* rdbuf() const { return const_cast<basic_netbuf<charT, traits>*>(&nb); }
-	
-	inline bool			open(const IPaddr& addr) { return nb.open(addr); }
-	inline bool			open(const IPaddr::const_ipname_t& str) { return nb.open(str); }
-	inline bool			open(const IPaddr::ipnum_t& addr, const IPaddr::ipport_t& aPort) { return nb.open(addr,aPort); }
-	inline bool			open(const IPaddr::const_ipname_t& ahost, unsigned int aPort) { return nb.open(ahost,aPort); }
-	inline bool			is_open()	const { return nb.is_open(); }
-/*	inline IPaddr::ipnum_t		remotehost() { return nb.remotehost(); }
-	inline IPaddr::ipport_t		remoteport() { return nb.remoteport(); }
-	inline IPaddr::ipnum_t		localhost() { return nb.localhost();}
-	inline IPaddr::ipport_t		localport() { return nb.localport();}
-*/
-	inline void				close() { return nb.close(); }
-	inline void				setEcho(bool val=true) { return nb.setEcho(val); }
-	inline bool				getEcho() { return nb.getEcho(); }
-private:
-	basic_netbuf<charT, traits> nb;
-};
-
-
-template <class charT, class traits>
-class basic_oNetStream
-	: public ostream
-{
-public:
-	typedef charT                     char_type;
-	typedef typename traits::int_type int_type;
-	typedef typename traits::pos_type pos_type;
-	typedef typename traits::off_type off_type;
-	typedef traits                    traits_type;
-	//  lib.ifstream.cons Constructors:
-	basic_oNetStream() : ostream(&nb), nb() {}
-	basic_oNetStream(const IPaddr::ipnum_t& host, const IPaddr::ipport_t port) : basic_oNetStream(&nb), nb(host,port) {}
-	basic_oNetStream(const IPaddr::const_ipname_t& host, const IPaddr::ipport_t port) : basic_oNetStream(&nb), nb(host,port) {}
-	basic_oNetStream(const IPaddr& addr) : basic_oNetStream(&nb), nb(addr) {}
-	basic_oNetStream(size_t buf_in_size, size_t buf_out_size) : ostream(&nb), nb(buf_in_size,buf_out_size) {}
-	//  lib.ifstream.members Members:
-	inline basic_netbuf<charT, traits>* rdbuf() const { return const_cast<basic_netbuf<charT, traits>*>(&nb); }
-	
-	inline bool			open(const IPaddr& addr) { return nb.open(addr); }
-	inline bool			open(const IPaddr::const_ipname_t& str) { return nb.open(str); }
-	inline bool			open(const IPaddr::ipnum_t& addr, const IPaddr::ipport_t& aPort) { return nb.open(addr,aPort); }
-	inline bool			open(const IPaddr::const_ipname_t& ahost, unsigned int aPort) { return nb.open(ahost,aPort); }
-	inline bool			is_open()	const { return nb.is_open(); }
-/*	inline IPaddr::ipnum_t		remotehost() { return nb.remotehost(); }
-	inline IPaddr::ipport_t		remoteport() { return nb.remoteport(); }
-	inline IPaddr::ipnum_t		localhost() { return nb.localhost();}
-	inline IPaddr::ipport_t		localport() { return nb.localport();}
-*/
-	inline void				close() { return nb.close(); }
-	inline void				setEcho(bool val=true) { return nb.setEcho(val); }
-	inline bool				getEcho() { return nb.getEcho(); }
-private:
-	basic_netbuf<charT, traits> nb;
-};
-
-
-template <class charT, class traits>
-class basic_ioNetStream
-	: public iostream
-{
-public:
-	typedef charT                     char_type;
-	typedef typename traits::int_type int_type;
-	typedef typename traits::pos_type pos_type;
-	typedef typename traits::off_type off_type;
-	typedef traits                    traits_type;
-	//  lib.ifstream.cons Constructors:
-	basic_ioNetStream() : iostream(&nb), nb() {}
-	basic_ioNetStream(const IPaddr& addr) : basic_ioNetStream(&nb), nb(addr) {}
-	basic_ioNetStream(const IPaddr::ipnum_t& host, const IPaddr::ipport_t port) : basic_ioNetStream(&nb), nb(host,port) {}
-	basic_ioNetStream(const IPaddr::const_ipname_t& host, const IPaddr::ipport_t port) : basic_ioNetStream(&nb), nb(host,port) {}
-	basic_ioNetStream(size_t buf_in_size, size_t buf_out_size) : iostream(&nb), nb(buf_in_size,buf_out_size) {}
-	//  lib.ifstream.members Members:
-	inline basic_netbuf<charT, traits>* rdbuf() const { return const_cast<basic_netbuf<charT, traits>*>(&nb); }
-	
-	inline bool			open(const IPaddr& addr) { return nb.open(addr); }
-	inline bool			open(const IPaddr::const_ipname_t& str) { return nb.open(str); }
-	inline bool			open(const IPaddr::ipnum_t& addr, const IPaddr::ipport_t& aPort) { return nb.open(addr,aPort); }
-	inline bool			open(const IPaddr::const_ipname_t& ahost, unsigned int aPort) { return nb.open(ahost,aPort); }
-	inline bool			is_open()	{ return nb.is_open(); }
-/*	inline IPaddr::ipnum_t		remotehost() { return nb.remotehost(); }
-	inline IPaddr::ipport_t		remoteport() { return nb.remoteport(); }
-	inline IPaddr::ipnum_t		localhost() { return nb.localhost();}
-	inline IPaddr::ipport_t		localport() { return nb.localport();}
-*/
-	inline void				close() { nb.close(); }
-	inline void				setEcho(bool val=true) { return nb.setEcho(val); }
-	inline bool				getEcho() { return nb.getEcho(); }
-private:
-	basic_netbuf<charT, traits> nb;
-};
-
-template<class T>
-class char_traits {
-public:
-  typedef T char_type;
-  typedef int int_type;
-  typedef T* pos_type;
-  typedef unsigned int off_type;
-  static void copy(pos_type dst, pos_type src, off_type size) {
-    memcpy(dst,src,size);
-  }
-  static void move(pos_type dst, pos_type src, off_type size) {
-    memmove(dst,src,size);
-  }
-  static int to_int_type(T c) { return c; }
-  static int eof() { return EOF; }
-};
-
-typedef basic_netbuf<char, char_traits<char> > netbuf;
-typedef basic_iNetStream<char, char_traits<char> > iNetStream;
-typedef basic_oNetStream<char, char_traits<char> > oNetStream;
-typedef basic_ioNetStream<char, char_traits<char> > ioNetStream;
-
-
-
-
-template <class charT, class traits>
-basic_netbuf<charT,traits>::basic_netbuf() 
-  : buf_in(NULL), buf_out(NULL), using_buf_in(false), using_buf_out(false),
-	sock(INVALID_SOCKET), is_echoing(false) {
-  Init();
-}
-template <class charT, class traits>
-basic_netbuf<charT,traits>::basic_netbuf(const IPaddr& addr)
-  : buf_in(NULL), buf_out(NULL), using_buf_in(false), using_buf_out(false),
-	sock(INVALID_SOCKET), is_echoing(false) {
-  Init();
-  open(addr);
-}
-
-template <class charT, class traits>
-basic_netbuf<charT,traits>::basic_netbuf(const IPaddr::ipnum_t& host, const IPaddr::ipport_t port)
-  : buf_in(NULL), buf_out(NULL), using_buf_in(false), using_buf_out(false),
-	sock(INVALID_SOCKET), is_echoing(false) {
-  Init();
-  open(host,port);
-}
-
-template <class charT, class traits>
-basic_netbuf<charT,traits>::basic_netbuf(const IPaddr::const_ipname_t& host, const IPaddr::ipport_t port)
-  : buf_in(NULL), buf_out(NULL), using_buf_in(false), using_buf_out(false),
-	sock(INVALID_SOCKET), is_echoing(false) {
-  Init();
-  open(host,port);
-}
-
-template <class charT, class traits>
-basic_netbuf<charT,traits>::basic_netbuf(size_t buf_in_size, size_t buf_out_size) 
-  : buf_in(NULL), buf_out(NULL), using_buf_in(false), using_buf_out(false),
-	sock(INVALID_SOCKET), is_echoing(false) {
-  Init();
-}
-
-template <class charT, class traits>
-basic_netbuf<charT,traits>::~basic_netbuf() {
-	if(using_buf_in)
-		delete [] buf_in;
-	if(using_buf_out)
-		delete [] buf_out;
-}
-
-template<class charT, class traits>
-void
-basic_netbuf<charT,traits>::Init(size_t insize, size_t outsize) {
-  buf_in = new charT[insize];
-  buf_out = new charT[outsize];
-  using_buf_in = using_buf_out = true;
-  setg(buf_in,buf_in+insize,buf_in+insize);
-  setp(buf_out,buf_out+outsize);
-//  cout << "Buffer is:" << endl;
-//  cout << "Input buffer: " << egptr() << " to " << egptr() << " at " << gptr() << endl;
-//  cout << "Output buffer: " << pbase() << " to " << epptr() << " at " << pptr() << endl;
-}
-
-template <class charT, class traits>
-bool
-basic_netbuf<charT,traits>::open(const IPaddr& addr) {
-	if(addr.get_num())
-		return open(addr.get_num(),addr.get_port());
-	return false;
-}
-
-template <class charT, class traits>
-bool
-basic_netbuf<charT,traits>::open(const IPaddr::const_ipname_t& str) {
-	const char*const colon = strrchr(str,':');
-	if(colon==NULL)
-		return false;
-	char* tmp = new char[strlen(str)];
-	char * d = tmp;
-	for(const char * s=str; s!=colon; s++,d++)
-		*d=*s;
-	*d='\0';
-	IPaddr::ipport_t port = atoi(colon+1);
-	bool res = open(tmp,port);
-	delete [] tmp;
-	return res;
-}
-
-template <class charT, class traits>
-bool
-basic_netbuf<charT,traits>::open(const IPaddr::ipnum_t& addr, const IPaddr::ipport_t& aPort) { //depends on timeout
-	struct sockaddr_in server;
-	
-	memset((char *) &server, sizeof(server), 0);
-	server.sin_family      = AF_INET;
-	server.sin_addr.s_addr = addr;
-	server.sin_port        = htons(aPort);
-
-	// create socket
-	sock = socket(AF_INET, SOCK_STREAM, 0);
-	if(sock < 1) {
-		cout << "NetClient error: socket failed to create stream socket" << endl;
-		sock = INVALID_SOCKET;
-		return false;
-	}
-
-	// connect to server.
-	int err = connect(sock, (struct sockaddr *) &server, sizeof(server));
-	if(err < 0) {
-		cout << "NetClient error: connect failed to connect to requested address" << endl;
-		sock = INVALID_SOCKET;
-		return false;
-	}
-
-	return true;
-}
-
-template <class charT, class traits>
-void
-basic_netbuf<charT,traits>::close() {
-	cout << "close called" << endl;
-	if(!is_open())
-		return;
-	if(sock != INVALID_SOCKET) {
-		cout << "closing" << endl;
-		::close(sock);
-		cout << "closed" << endl;
-		sock = INVALID_SOCKET;
-	}
-}
-
-template <class charT, class traits>
-void
-basic_netbuf<charT,traits>::printBuffer(const char *buf, int buflen, const char *header) {
-	int line_begin = 1;
-	for(int i = 0; i < buflen; i++) {
-		if(buf[i] == '\n') {
-			line_begin = 1;
-			fputc('\n', stderr);
-		} else {
-			if(line_begin) fputs(header, stderr);
-			line_begin = 0;
-			fputc(buf[i], stderr);
-		}
-	}
-}
-
-template <class charT, class traits>
-void
-basic_netbuf<charT,traits>::in_sync() {
-	if(!is_open()) {
-		cout << "NetClient error: must open connection before reading from it" << endl;
-		return;
-	}
-	if(gptr()>egptr())
-		gbump( egptr()-gptr() );
-	unsigned long n = gptr()-eback()-1;
-	charT * temp_buf = new char[n*sizeof(charT)];
-	unsigned int used = read(sock, temp_buf, n*sizeof(charT));
-	if(used<=0) {
-		cout << "NetClient error: connection dropped" << endl;
-		delete [] temp_buf;
-		close();
-		return;
-	}
-	if(is_echoing)
-		printBuffer(temp_buf, used, "NetClient: recv: ");
-	//TODO - what if sizeof(charT)>1?  We might need to worry about getting/storing partial char
-	used/=sizeof(charT);
-	size_t remain = egptr()-eback()-used;
-	traits::move(eback(),egptr()-remain,remain);
-	traits::copy(egptr()-used,temp_buf,used);
-	delete [] temp_buf;
-	gbump( -used );
-}
-
-template <class charT, class traits>
-void
-basic_netbuf<charT,traits>::out_flush() {
-	if(!is_open()) {
-		cout << "NetClient error: must open connection before writing to it" << endl;
-		return;
-	}
-	size_t n = (pptr()-pbase())*sizeof(charT);
-	if(n==0)
-		return;
-	size_t total = 0;
-	while(total<n) {
-		int sent = write(sock, pbase()+total, n-total);
-		if(sent < 0) {
-			cout << "NetClient error: send error" << endl;
-			perror("send");
-			close();
-			return;
-		}
-		if(is_echoing)
-			printBuffer(pbase()+total, sent, "NetClient: sent: ");
-		total += sent;
-	}
-	total/=sizeof(charT);
-	n/=sizeof(charT);
-	if(total!=n)
-		traits::move(pbase(),pbase()+total,n-total);
-	pbump( -total );
-}
-
-
-template <class charT, class traits>
-inline streamsize
-basic_netbuf<charT, traits>::showmanyc() {
-	return (gptr()<egptr())?(egptr()-gptr()):0;
-}
-
-template <class charT, class traits>
-inline typename basic_netbuf<charT, traits>::int_type
-basic_netbuf<charT, traits>::underflow() {
-	in_sync();
-	if(gptr()<egptr())
-		return traits::to_int_type(*gptr());
-//	if( cur_input()!=kOTInvalidEndpointRef )
-//		return uflow();
-//	cout << "UNDERFLOW" << endl;
-	return traits::eof();
-}
-
-template <class charT, class traits>
-inline typename basic_netbuf<charT, traits>::int_type
-basic_netbuf<charT, traits>::uflow() {
-	in_sync();
-	if(gptr()<egptr()) {
-		int_type ans = traits::to_int_type(*gptr());
-		gbump(1);
-		return ans;
-	}
-//	cout << "UNDERFLOW" << endl;
-	return traits::eof();
-}
-
-template <class charT, class traits>
-inline typename basic_netbuf<charT, traits>::int_type
-basic_netbuf<charT, traits>::overflow(int_type c) { 
-	out_flush();
-	*pptr() = c;
-	pbump(1);
-	return is_open()?c:traits::eof();
-}
-
-template <class charT, class traits>
-inline int
-basic_netbuf<charT, traits>::sync() {
-	out_flush();
-	in_sync();
-	return is_open()?0:-1;
-}
-
-
-#endif
diff -urdN ../Tekkotsu_2.3/aperios/CVS/Entries ./aperios/CVS/Entries
--- ../Tekkotsu_2.3/aperios/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,12 @@
+/Makefile.aperios/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/build-jpeg/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/build-libpng/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/build-libxml/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/build-zlib/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+D/MMCombo////
+D/SndPlay////
+D/TinyFTPD////
+D/bin////
+D/include////
+D/lib////
+D/share////
diff -urdN ../Tekkotsu_2.3/aperios/CVS/Repository ./aperios/CVS/Repository
--- ../Tekkotsu_2.3/aperios/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios
diff -urdN ../Tekkotsu_2.3/aperios/CVS/Root ./aperios/CVS/Root
--- ../Tekkotsu_2.3/aperios/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/CVS/Tag ./aperios/CVS/Tag
--- ../Tekkotsu_2.3/aperios/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/CVS/Tag	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/CVS/Entries ./aperios/MMCombo/CVS/Entries
--- ../Tekkotsu_2.3/aperios/MMCombo/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/CVS/Entries	Wed Aug 10 11:03:21 2005
@@ -0,0 +1,5 @@
+/MMCombo.cc/1.8/Thu Aug  4 21:10:11 2005//Ttekkotsu-2_4
+/MMCombo.h/1.3/Wed Jun 29 22:06:33 2005//Ttekkotsu-2_4
+/MMCombo.ocf/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/stub.cfg/1.3/Wed Jun 29 22:06:33 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/CVS/Repository ./aperios/MMCombo/CVS/Repository
--- ../Tekkotsu_2.3/aperios/MMCombo/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/MMCombo
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/CVS/Root ./aperios/MMCombo/CVS/Root
--- ../Tekkotsu_2.3/aperios/MMCombo/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/CVS/Tag ./aperios/MMCombo/CVS/Tag
--- ../Tekkotsu_2.3/aperios/MMCombo/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/CVS/Tag	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/MMCombo.cc ./aperios/MMCombo/MMCombo.cc
--- ../Tekkotsu_2.3/aperios/MMCombo/MMCombo.cc	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/MMCombo.cc	Thu Aug  4 17:10:11 2005
@@ -0,0 +1,769 @@
+#include "MMCombo.h"
+#include "Shared/WorldState.h"
+#include "Shared/Profiler.h"
+#include "Shared/debuget.h"
+#include "Shared/Config.h"
+#include "IPC/SharedObject.h"
+#include "IPC/ProcessID.h"
+#include "Events/EventRouter.h"
+#include "Behaviors/BehaviorBase.h"
+#include "Motion/MotionManager.h"
+#include "Motion/Kinematics.h"
+#include "Sound/SoundManager.h"
+#include "Events/DataEvent.h"
+#include "Events/TextMsgEvent.h"
+#include "Events/FilterBankEvent.h"
+#include "Shared/WMclass.h"
+
+#include "Shared/ERS210Info.h"
+#include "Shared/ERS220Info.h"
+#include "Shared/ERS7Info.h"
+
+#include "Shared/ProjectInterface.h"
+
+#include "Events/EventBase.h"
+#include "Events/LocomotionEvent.h"
+#include "Events/TextMsgEvent.h"
+#include "Events/VisionObjectEvent.h"
+
+#include <OPENR/OSyslog.h>
+#include <OPENR/core_macro.h>
+#include <OPENR/OFbkImage.h>
+#include "aperios/MMCombo/entry.h"
+
+using namespace std;
+
+MMCombo::MMCombo()
+	: OObject(), motmanMemRgn(NULL), worldStateMemRgn(NULL),
+		soundManagerMemRgn(NULL),
+		runLevel(0), num_open(0), etrans(NULL), isStopped(true)
+{
+	for(unsigned int i=0; i<NumOutputs; i++) {
+		primIDs[i]=oprimitiveID_UNDEF;
+		open[i]=false;
+	}
+
+	//need to register any events which we might be sending or receiving
+	EventTranslator::registerPrototype<EventBase>();
+	EventTranslator::registerPrototype<LocomotionEvent>();
+	EventTranslator::registerPrototype<TextMsgEvent>();
+	EventTranslator::registerPrototype<VisionObjectEvent>();
+}
+
+
+OStatus
+MMCombo::DoInit(const OSystemEvent&)
+{
+	cout << objectName << "::DoInit() " << endl;
+
+	isStopped=false;
+
+	NEW_ALL_SUBJECT_AND_OBSERVER;
+	REGISTER_ALL_ENTRY;
+	SET_ALL_READY_AND_NOTIFY_ENTRY;
+		
+	// make sure the library doesn't drop data "for" us on this reliable communication channel
+	observer[obsReceiveWorldState]->SetBufCtrlParam(0,1,1);
+	observer[obsReceiveMotionManager]->SetBufCtrlParam(0,1,1);
+	observer[obsReceiveSoundManager]->SetBufCtrlParam(0,1,1);
+	observer[obsMotionManagerComm]->SetBufCtrlParam(0,1,MotionManager::MAX_MOTIONS+1);
+	//+1 to MAX_MOTIONS so we can get a delete message after we've filled up
+
+	cout << objectName << ": sbjRegisterWorldState==" << sbjRegisterWorldState << " selector==" << subject[sbjRegisterWorldState]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsReceiveWorldState==" << obsReceiveWorldState << " selector==" << observer[obsReceiveWorldState]->GetID().GetSelector() << '\n'
+			 << objectName << ": sbjRegisterMotionManager==" << sbjRegisterMotionManager << " selector==" << subject[sbjRegisterMotionManager]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsReceiveMotionManager==" << obsReceiveMotionManager << " selector==" << observer[obsReceiveMotionManager]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsEventTranslatorComm==" << obsEventTranslatorComm << " selector==" << observer[obsEventTranslatorComm]->GetID().GetSelector() << '\n'
+			 << objectName << ": sbjEventTranslatorComm==" << sbjEventTranslatorComm << " selector==" << observer[sbjEventTranslatorComm]->GetID().GetSelector() << '\n'
+			 << objectName << ": sbjMoveJoint==" << sbjMoveJoint << " selector==" << subject[sbjMoveJoint]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsSensorFrame==" << obsSensorFrame << " selector==" << observer[obsSensorFrame]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsImage==" << obsImage << " selector==" << observer[obsImage]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsMic==" << obsMic << " selector==" << observer[obsMic]->GetID().GetSelector() << '\n'
+			 << objectName << ": sbjMotionManagerComm==" << sbjMotionManagerComm << " selector==" << subject[sbjMotionManagerComm]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsMotionManagerComm==" << obsMotionManagerComm << " selector==" << observer[obsMotionManagerComm]->GetID().GetSelector() << '\n'
+			 << objectName << ": obsReceiveSoundManager==" << obsReceiveSoundManager << " selector==" << observer[obsReceiveSoundManager]->GetID().GetSelector() << '\n'
+			 << objectName << ": sbjSoundManagerComm==" << sbjSoundManagerComm << " selector==" << subject[sbjSoundManagerComm]->GetID().GetSelector() << '\n'
+			 << flush;
+
+	if(strcmp(objectName,"MainObj")==0)
+		ProcessID::setID(ProcessID::MainProcess);
+	else if(strcmp(objectName,"MotoObj")==0)
+		ProcessID::setID(ProcessID::MotionProcess);
+		
+	//Read config file
+	config=new Config("/ms/config/tekkotsu.cfg");
+
+	erouter = new EventRouter;
+
+	if(strcmp(objectName,"MainObj")==0) {
+		bool isSlowOutput[NumOutputs];
+		for(unsigned int i=0; i<NumOutputs; i++)
+			isSlowOutput[i]=!IsFastOutput[i];
+
+		SetupOutputs(isSlowOutput);
+
+		//Request power status updates
+		OPowerStatus observationStatus;
+		observationStatus.Set(orsbALL,obsbALL,opsoREMAINING_CAPACITY_NOTIFY_EVERY_CHANGE,opsoTEMPERATURE_NOTIFY_EVERY_CHANGE,opsoTIME_DIF_NOTIFY_EVERY_CHANGE,opsoVOLUME_NOTIFY_EVERY_CHANGE);
+		OServiceEntry entry(myOID_, Extra_Entry[entryGotPowerEvent]);
+		OStatus result = OPENR::ObservePowerStatus(observationStatus, entry);
+		if(result != oSUCCESS) {
+			OSYSLOG1((osyslogERROR, "%s : %s %d","MMCombo::DoStart()","OPENR::ObservePowerStatus() FAILED", result));
+			return oFAIL;
+		}
+		
+    //Setup wireless
+    wireless = new Wireless();
+    sout=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*12);
+    serr=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*4);
+    wireless->setDaemon(sout);
+    wireless->setDaemon(serr);
+		serr->setFlushType(SocketNS::FLUSH_BLOCKING);
+    sout->setTextForward();
+    serr->setForward(sout);
+
+		//worldStateMemRgn -> state setup
+		worldStateMemRgn = InitRegion(sizeof(WorldState));
+		state=new ((WorldState*)worldStateMemRgn->Base()) WorldState;
+
+		etrans=new NoOpEventTranslator(*erouter);
+		MotionManager::setTranslator(etrans);
+	}
+	if(strcmp(objectName,"MotoObj")==0) {
+		SetupOutputs(IsFastOutput);
+    OPENR::SetMotorPower(opowerON);
+		OPENR::EnableJointGain(oprimitiveID_UNDEF); //oprimitiveID_UNDEF means enable all
+
+    //Setup wireless
+    wireless = new Wireless();
+    sout=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*6);
+    serr=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*2);
+    wireless->setDaemon(sout);
+    wireless->setDaemon(serr);
+		serr->setFlushType(SocketNS::FLUSH_BLOCKING);
+    sout->setTextForward();
+    serr->setForward(sout);
+		
+		//motmanMemRgn -> motman setup
+		motmanMemRgn = InitRegion(sizeof(MotionManager));
+		motman = new (motmanMemRgn->Base()) MotionManager();
+		motman->InitAccess(subject[sbjMotionManagerComm]);
+
+		etrans=new IPCEventTranslator(*subject[sbjEventTranslatorComm]);
+		MotionManager::setTranslator(etrans);
+		//MotionCommands enqueue directly, so there shouldn't be any riff-raff to catch
+		//but just in case, subscribe to everything except erouterEGID
+		for(unsigned int i=0; i<EventBase::numEGIDs; i++)
+			if(i!=EventBase::erouterEGID)
+				erouter->addTrapper(etrans,static_cast<EventBase::EventGeneratorID_t>(i));
+	}
+	kine = new Kinematics();
+
+	cout << objectName << "::DoInit()-DONE" << endl;
+	return oSUCCESS;
+}
+
+OStatus
+MMCombo::DoStart(const OSystemEvent&)
+{
+	cout << objectName << "::DoStart() " << endl;
+
+	// initialize the current power status, doesn't always give us
+	// a power update right away otherwise
+	if(strcmp(objectName,"MainObj")==0) {
+		wireless->listen(sout, config->main.console_port);
+		wireless->listen(serr, config->main.stderr_port);
+		OPowerStatus power;
+		OPENR::GetPowerStatus(&power);
+		state->read(power,erouter);
+	}
+
+	if(strcmp(objectName,"MotoObj")==0) {
+		wireless->listen(sout, config->motion.console_port);
+		wireless->listen(serr, config->motion.stderr_port);
+	}
+	
+	isStopped=false;
+
+	ENABLE_ALL_SUBJECT;
+	ASSERT_READY_TO_ALL_OBSERVER;
+
+	addRunLevel();
+	
+	cout << objectName << "::DoStart()-DONE" << endl;
+	return oSUCCESS;
+}
+
+OStatus
+MMCombo::DoStop(const OSystemEvent&)
+{
+	cout << objectName << "::DoStop()..." << endl;
+	if(strcmp(objectName,"MainObj")==0) {
+		ProjectInterface::startupBehavior().DoStop();
+		wireless->close(sout);
+		wireless->close(serr);
+	}
+	DISABLE_ALL_SUBJECT;
+	DEASSERT_READY_TO_ALL_OBSERVER;
+	isStopped=true;
+	cout << objectName << "::DoStop()-DONE" << endl;
+	return oSUCCESS;
+}
+
+OStatus
+MMCombo::DoDestroy(const OSystemEvent&)
+{
+	cout << objectName << "::DoDestroy()..." << endl;
+	delete etrans;
+	etrans=NULL;
+	MotionManager::setTranslator(NULL);
+	if(strcmp(objectName,"MainObj")==0) {
+		delete erouter;
+		motmanMemRgn->RemoveReference();
+	}
+	if(strcmp(objectName,"MotoObj")==0) {
+		worldStateMemRgn->RemoveReference();
+	}
+	soundManagerMemRgn->RemoveReference();
+	DELETE_ALL_SUBJECT_AND_OBSERVER;
+	cout << objectName << "::DoDestroy()-DONE" << endl;
+	return oSUCCESS;
+}
+
+/*! Called when MotoObj is initially ready as well as when it has finished
+ *  processing the previous message - we only want to do this the first time
+ *  otherwise we infinite loop. */
+void
+MMCombo::ReadyRegisterWorldState(const OReadyEvent&){
+	static bool is_init=true;
+	if(is_init) {
+		is_init=false;
+		cout << objectName << " Registering WorldState" << endl;
+		if(strcmp(objectName,"MainObj")==0) {
+			subject[sbjRegisterWorldState]->SetData(worldStateMemRgn);
+			subject[sbjRegisterWorldState]->NotifyObservers();
+		}
+	}
+}
+
+void
+MMCombo::GotWorldState(const ONotifyEvent& event){
+	cout << objectName << "-GOTWORLDSTATE..." << flush;
+	//	PROFSECTION("GotMemRegion()",state->mainProfile);
+	if(strcmp(objectName,"MotoObj")==0) {
+		ASSERT(event.NumOfData()==1,"Too many WorldStates");
+		worldStateMemRgn = event.RCData(0);
+		worldStateMemRgn->AddReference();
+		state = reinterpret_cast<WorldState*>(worldStateMemRgn->Base());
+	}
+  observer[obsReceiveWorldState]->AssertReady();
+	cout << "done" << endl;
+}
+
+		
+/*! Called when MainObj is initially ready as well as when it has finished
+ *  processing the previous message - we only want to do this the first time
+ *  otherwise we infinite loop. */
+void
+MMCombo::ReadyRegisterMotionManager(const OReadyEvent&){
+	static bool is_init=true;
+	if(is_init) {
+		is_init=false;
+		cout << objectName << " Registering MotionManager" << endl;
+		if(strcmp(objectName,"MotoObj")==0) {
+			subject[sbjRegisterMotionManager]->SetData(motmanMemRgn);
+			subject[sbjRegisterMotionManager]->NotifyObservers();
+		}
+	}
+}
+
+void
+MMCombo::GotMotionManager(const ONotifyEvent& event){
+	cout << objectName << "-GOTMOTIONMANAGER..." << flush;
+	//	PROFSECTION("GotMemRegion()",state->mainProfile);
+	if(strcmp(objectName,"MainObj")==0) {
+		ASSERT(event.NumOfData()==1,"Too many MotionManagers");
+		motmanMemRgn = event.RCData(0);
+		motmanMemRgn->AddReference();
+		motman = reinterpret_cast<MotionManager*>(motmanMemRgn->Base());
+		cout << "MAIN INIT MOTMAN..." << flush;
+		//			hexout(event.RCData(event_data_id)->Base(),128);
+		motman->InitAccess(subject[sbjMotionManagerComm]);
+		addRunLevel();
+	}
+  observer[obsReceiveMotionManager]->AssertReady();
+	cout << "done" << endl;
+}
+
+
+void
+MMCombo::GotInterProcessEvent(const ONotifyEvent& event){
+	//cout << objectName << "-GOTInterProcessEvent " << event.NumOfData() << "..." << flush;
+	//cout << TimeET() << endl;
+	//	PROFSECTION("GotMemRegion()",state->mainProfile);
+	if(etrans==NULL)
+		return;
+	for(int i=0; i<event.NumOfData(); i++) {
+		RCRegion * msg = event.RCData(i);
+		EventBase* evt=etrans->decodeEvent(msg->Base(),msg->Size());
+		if(evt!=NULL)
+			erouter->postEvent(evt);
+	}
+  observer[obsEventTranslatorComm]->AssertReady();
+	//cout << "done" << endl;
+}
+
+		
+void
+MMCombo::ReadySendJoints(const OReadyEvent& sysevent) {
+
+	if(isStopped) {
+		//cout << "BAH!ReadySendJoints" << endl;
+		return;
+	}
+
+	static unsigned int id=-1U;
+	Profiler::Timer timer;
+	if(ProcessID::getID()==ProcessID::MotionProcess) {
+		if(state) {
+			if(id==-1U)
+				id=state->motionProfile.getNewID("ReadySendJoints()");
+			timer.setID(id,&state->motionProfile.prof);
+		}
+	}	else if(ProcessID::getID()==ProcessID::MainProcess) {
+		if(id==-1U)
+			id=state->mainProfile.getNewID("ReadySendJoints()");
+		timer.setID(id,&state->mainProfile.prof);
+	}
+
+	if(num_open==0) //If we don't have any joints to open, leave now. (i.e. MainObj on a 220, has no ears)
+		return;
+
+	// Find an unused command vector
+	RCRegion* rgn=NULL;
+	for (unsigned int i = 0; i < NUM_COMMAND_VECTOR; i++) {
+		if (region[i]->NumberOfReference() == 1) {
+			rgn=region[i];
+			/*			if(strcmp(objectName,"MainObj")==0) {
+							static unsigned int lasttime=get_time();
+							unsigned int thistime=get_time();
+							cout << '*' << i << ' ' << thistime << '\t' << (thistime-lasttime) << endl;
+							lasttime=thistime;
+							}*/
+			break;
+		}
+	}
+	ASSERTRET(rgn!=NULL,"Could not find unused command vector");
+	ASSERTRET(rgn->Base()!=NULL,"Bad Command Vector");
+	OCommandVectorData* cmdVecData = reinterpret_cast<OCommandVectorData*>(rgn->Base());
+	
+	// Update the outputs (note that Main is doing the ears)
+	//I'm using an id compare instead of the slightly more readable strcmp for a tiny bit of speed
+	bool isERS7;
+	if(state!=NULL)
+		isERS7=state->robotDesign&WorldState::ERS7Mask;
+	else {
+		char robotDesignStr[orobotdesignNAME_MAX + 1];
+		memset(robotDesignStr, 0, sizeof(robotDesignStr));
+		if (OPENR::GetRobotDesign(robotDesignStr) != oSUCCESS) {
+			cout << objectName << "::SetupOutputs - OPENR::GetRobotDesign() failed." << endl;
+			return;
+		}
+		isERS7=(strcmp(robotDesignStr,"ERS-7")==0);
+	}		
+	if(ProcessID::getID()==ProcessID::MotionProcess) {
+		float outputs[NumFrames][NumOutputs];
+		if(state!=NULL) {
+			motman->getOutputs(outputs);
+			motman->updatePIDs(primIDs);
+			motman->updateWorldState();
+		} else {
+			for(unsigned int f=0; f<NumFrames; f++)
+				for(unsigned int i=0; i<NumOutputs; i++)
+					outputs[f][i]=0;
+		}
+			
+		// Should be a relatively simple matter to copy angles into commands...
+		unsigned int used=0; //but only copy open joints (so main does ears on 210, motion does everything else)
+		for(unsigned int i=PIDJointOffset; i<PIDJointOffset+NumPIDJoints; i++)
+			if(open[i]) {
+				float cal=config->motion.calibration[i-PIDJointOffset];
+				OJointCommandValue2* jval = reinterpret_cast<OJointCommandValue2*>(cmdVecData->GetData(used)->value);
+				for(unsigned int frame=0; frame<NumFrames; frame++)
+					jval[frame].value = (slongword)(outputs[frame][i]/cal*1.0e6f);
+				used++;
+			}
+		if(isERS7) {
+			// except if it's an ERS-7, we have to use different data structures for some of the leds and the ears
+			for(unsigned int i=LEDOffset; i<ERS7Info::FaceLEDPanelOffset; i++)
+				if(open[i]) {
+					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumFrames; frame++)
+						jval[frame].led = calcLEDValue(i-LEDOffset,outputs[frame][i]);
+					used++;
+				}
+			// for instance, this virtual mode thing, which is global to all the affected LEDs
+			OLED3Mode curMode[NumFrames];
+			for(unsigned int frame=0; frame<NumFrames; frame++)
+				curMode[frame]=(calcLEDValue(ERS7Info::LEDABModeOffset-LEDOffset,sqrt(clipRange01(outputs[frame][ERS7Info::LEDABModeOffset])))==oledON?oled3_MODE_B:oled3_MODE_A);
+			for(unsigned int i=ERS7Info::FaceLEDPanelOffset; i<LEDOffset+NumLEDs; i++)
+				if(open[i]) {
+					OLEDCommandValue3* jval = reinterpret_cast<OLEDCommandValue3*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumFrames; frame++) {
+						jval[frame].intensity = static_cast<sword>(255*clipRange01(outputs[frame][i]));
+						jval[frame].mode=curMode[frame];
+					}
+					used++;
+				}
+			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
+				if(open[i]) {
+					OJointCommandValue4* jval = reinterpret_cast<OJointCommandValue4*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
+						jval[frame].value = (outputs[frame][i]<.5?ojoint4_STATE0:ojoint4_STATE1);
+					used++;
+				}
+		} else {
+			for(unsigned int i=LEDOffset; i<LEDOffset+NumLEDs; i++)
+				if(open[i]) {
+					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumFrames; frame++)
+						jval[frame].led = calcLEDValue(i-LEDOffset,outputs[frame][i]);
+					used++;
+				}
+			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
+				if(open[i]) {
+					OJointCommandValue3* jval = reinterpret_cast<OJointCommandValue3*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
+						jval[frame].value = (outputs[frame][i]<.5?ojoint3_STATE1:ojoint3_STATE0);
+					used++;
+				}
+		}
+	}	else if(ProcessID::getID()==ProcessID::MainProcess) {
+		// Just copy over the current ear state from WorldState
+		unsigned int used=0; //but only copy open joints (so main does ears, motion does everything else)
+		if(isERS7) {
+			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
+				if(open[i]) {
+					OJointCommandValue4* jval = reinterpret_cast<OJointCommandValue4*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
+						jval[frame].value = (state->outputs[i]<.5?ojoint4_STATE0:ojoint4_STATE1);
+					used++;
+				}
+		} else {
+			for(unsigned int i=BinJointOffset; i<BinJointOffset+NumBinJoints; i++)
+				if(open[i]) {
+					OJointCommandValue3* jval = reinterpret_cast<OJointCommandValue3*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumSlowFrames; frame++)
+						jval[frame].value = (state->outputs[i]<.5?ojoint3_STATE1:ojoint3_STATE0);
+					used++;
+				}
+		}
+	}
+
+	// Send outputs to system
+	subject[sbjMoveJoint]->SetData(rgn);
+
+	// The first time this is called, we actually need to send *two* buffers
+	// in order to get the double buffering going... (well, actually generalized
+	// for NUM_COMMAND_VECTOR level buffering)
+	static unsigned int initCount=1;
+	if(initCount<NUM_COMMAND_VECTOR) {
+		initCount++;
+		ReadySendJoints(sysevent);
+	} else //recursive base case
+		subject[sbjMoveJoint]->NotifyObservers();
+}
+
+void
+MMCombo::GotSensorFrame(const ONotifyEvent& event){
+	//	if(state && state->buttons[RFrPawOffset])
+	//	cout << "SENSOR..."<<flush;
+	if(isStopped) {
+		//cout << "BAH!GotSensorFrame" << endl;
+		return;
+	}
+
+	PROFSECTION("GotSensorFrame()",state->mainProfile);
+
+  OSensorFrameVectorData* rawsensor = reinterpret_cast<OSensorFrameVectorData*>(event.RCData(0)->Base());
+	state->read(rawsensor[0],erouter);
+	erouter->processTimers();
+	static unsigned int throwaway=1; //i thought the first few sensor updates might be flakey, but now i think not.  But a good way to delay startup.
+	if(throwaway!=0) {
+		throwaway--;
+		if(throwaway==0) {
+			//seed the random number generator with time value and sensor noise
+			if(config->main.seed_rng) {
+				double t=TimeET().Value(); //current time with nanosecond resolution
+				unsigned int * tm=reinterpret_cast<unsigned int*>(&t);
+				unsigned int seed=tm[0]+tm[1];
+				for(unsigned int i=0; i<NumPIDJoints; i++) { //joint positions
+					unsigned int * x=reinterpret_cast<unsigned int*>(&state->outputs[i]);
+					seed+=(*x)<<((i%sizeof(unsigned int))*8);
+				}
+				for(unsigned int i=0; i<NumPIDJoints; i++) { //joint forces
+					unsigned int * x=reinterpret_cast<unsigned int*>(&state->pidduties[i]);
+					seed+=(*x)<<((i%sizeof(unsigned int))*8);
+				}
+				for(unsigned int i=0; i<NumSensors; i++) {
+					unsigned int * x=reinterpret_cast<unsigned int*>(&state->sensors[i]);
+					seed+=(*x)<<((i%sizeof(unsigned int))*8); //sensor values
+				}
+				cout << "RNG seed=" << seed << endl;;
+				srand(seed);
+			}
+			addRunLevel();
+		}
+	}
+  observer[obsSensorFrame]->AssertReady();
+	//	if(state && state->buttons[RFrPawOffset])
+	//	cout << "done" << endl;
+}
+
+void
+MMCombo::GotImage(const ONotifyEvent& event){
+	if(isStopped) {
+		//cout << "BAH!GotImage" << endl;
+		return;
+	}
+
+	PROFSECTION("GotImage()",state->mainProfile);
+
+  erouter->processTimers();
+  
+	WMvari(int, frame_counter, 0);
+	++frame_counter;
+	
+	erouter->postEvent(new DataEvent<const OFbkImageVectorData*>(reinterpret_cast<const OFbkImageVectorData*>(event.Data(0)),EventBase::visOFbkEGID,0,EventBase::activateETID));
+	erouter->postEvent(new DataEvent<const OFbkImageVectorData*>(reinterpret_cast<const OFbkImageVectorData*>(event.Data(0)),EventBase::visOFbkEGID,0,EventBase::statusETID));
+	erouter->postEvent(new DataEvent<const OFbkImageVectorData*>(reinterpret_cast<const OFbkImageVectorData*>(event.Data(0)),EventBase::visOFbkEGID,0,EventBase::deactivateETID));
+	
+  erouter->processTimers();
+  
+  observer[obsImage]->AssertReady();
+}
+
+void
+MMCombo::GotAudio(const ONotifyEvent& event){
+	if(isStopped) {
+		//cout << "BAH!GotAudio" << endl;
+		return;
+	}
+
+	PROFSECTION("GotAudio()",state->mainProfile);
+
+	for (int i = 0; i < event.NumOfData(); i++) {
+		erouter->postEvent(new DataEvent<const OSoundVectorData*>(reinterpret_cast<const OSoundVectorData*>(event.Data(i)),EventBase::micOSndEGID,0,EventBase::statusETID));
+		erouter->processTimers();
+	}
+  
+  observer[obsMic]->AssertReady();
+}
+
+void
+MMCombo::GotPowerEvent(void * msg){
+	if(isStopped) {
+		//cout << "BAH!GotPowerEvent" << endl;
+		return;
+	}
+
+	//	cout << "POWER..."<<flush;
+	PROFSECTION("PowerEvent()",state->mainProfile);
+
+	static bool first=true;
+	if(first) {
+		addRunLevel();
+		first=false;
+	}
+	const OPowerStatus* result = &static_cast<OPowerStatusMessage*>(msg)->powerStatus;
+	state->read(*result,erouter);
+	erouter->processTimers();
+	// this part watches to see if the power button is pressed to shutdown the robot
+	// i'm leaving this low-level because there's not much else you can do anyway...
+	// the hardware kills power to the motors, and as far as we can tell, you can't
+	// turn them back on.
+	if(state->powerFlags[PowerSourceID::PauseSID]) {
+		cout << "%%%%%%%  Pause button was pushed! %%%%%%%" << endl;
+		OBootCondition bc(0);
+		OPENR::Shutdown(bc);
+	}
+	//	cout << "done" << endl;
+}
+
+void
+MMCombo::GotMotionMsg(const ONotifyEvent& event){
+	if(isStopped) {
+		//cout << "BAH!GotMotionMsg" << endl;
+		return;
+	}
+
+	//	cout << "RECEIVE..."<<flush;
+	if(motman!=NULL)
+		motman->receivedMsg(event);
+	else
+		cout << "*** WARNING Main dropping MotionCommand (motman not ready) " << endl;
+	observer[obsMotionManagerComm]->AssertReady();
+	//	cout << "done" << endl;
+}
+
+void
+MMCombo::GotSoundManager(const ONotifyEvent& event) {
+	cout << objectName << "-GOTSOUNDMANAGER..." << flush;
+	//	PROFSECTION("GotMemRegion()",state->mainProfile);
+	ASSERT(event.NumOfData()==1,"Too many SoundManagers");
+	soundManagerMemRgn = event.RCData(0);
+	soundManagerMemRgn->AddReference();
+	sndman = reinterpret_cast<SoundManager*>(soundManagerMemRgn->Base());
+  observer[obsReceiveSoundManager]->AssertReady();
+	sndman->InitAccess(subject[sbjSoundManagerComm]);
+	addRunLevel();
+	cout << "done" << endl;
+}
+
+void
+MMCombo::OpenPrimitives()
+{
+	for(unsigned int i=0; i<NumOutputs; i++)
+		if(open[i]) {
+			OStatus result = OPENR::OpenPrimitive(PrimitiveName[i], &primIDs[i]);
+			if (result != oSUCCESS)
+				OSYSLOG1((osyslogERROR, "%s : %s %d","MMCombo::DoInit()","OPENR::OpenPrimitive() FAILED", result));
+		}
+}
+
+void
+MMCombo::SetupOutputs(const bool to_open[NumOutputs])
+{
+	char robotDesignStr[orobotdesignNAME_MAX + 1];
+	memset(robotDesignStr, 0, sizeof(robotDesignStr));
+	if (OPENR::GetRobotDesign(robotDesignStr) != oSUCCESS) {
+		cout << objectName << "::SetupOutputs - OPENR::GetRobotDesign() failed." << endl;
+		return;
+	} else {
+		if(strcmp(robotDesignStr,"ERS-210")==0) {
+			for(unsigned int j=0; j<NumOutputs; j++)
+				open[j]=to_open[j] && ERS210Info::IsRealERS210[j];
+		} else if(strcmp(robotDesignStr,"ERS-220")==0) {
+			for(unsigned int j=0; j<NumOutputs; j++)
+				open[j]=to_open[j] && ERS220Info::IsRealERS220[j];
+		} else if(strcmp(robotDesignStr,"ERS-7")==0) {
+			for(unsigned int j=0; j<NumOutputs; j++)
+				open[j]=to_open[j] && ERS7Info::IsRealERS7[j];
+		} else {
+			cout << "MMCombo::SetupOutputs - ERROR: Unrecognized model: "<<robotDesignStr<<"\nSorry..."<<endl;
+			return;
+		}
+	}
+	
+	// count how many we're opening
+	for(unsigned int j=0; j<NumOutputs; j++)
+		if(open[j])
+			num_open++;
+
+	if(num_open==0) //If we don't have any joints to open, leave now. (i.e. MainObj on a 220, has no ears, and on ERS-7, all joints are full speed)
+		return;
+
+	OpenPrimitives();
+
+	// request memory regions
+	for (unsigned int i = 0; i < NUM_COMMAND_VECTOR; i++) {
+		MemoryRegionID      cmdVecDataID;
+		OCommandVectorData* cmdVecData;
+		OStatus result = OPENR::NewCommandVectorData(num_open,&cmdVecDataID,&cmdVecData);
+		if (result != oSUCCESS)
+			OSYSLOG1((osyslogERROR, "%s : %s %d","MMCombo::NewCommandVectorData()","OPENR::NewCommandVectorData() FAILED", result));
+		region[i] = new RCRegion(cmdVecData->vectorInfo.memRegionID,cmdVecData->vectorInfo.offset,(void*)cmdVecData,cmdVecData->vectorInfo.totalSize);
+		cmdVecData->SetNumData(num_open);
+
+		// initialize the outputs we just opened
+		unsigned int used=0;
+		ASSERT(cmdVecData==reinterpret_cast<OCommandVectorData*>(region[i]->Base())," should be equal!?");
+		for(unsigned int j=PIDJointOffset; j<PIDJointOffset+NumPIDJoints; j++)
+			if(open[j]) {
+				OCommandInfo* info = cmdVecData->GetInfo(used++);
+				info->Set(odataJOINT_COMMAND2, primIDs[j], NumFrames);
+			}
+		if(strcmp(robotDesignStr,"ERS-7")==0) {
+			// this part's the same as usual, except stop when we get to face leds
+			for(unsigned int j=LEDOffset; j<ERS7Info::FaceLEDPanelOffset; j++)
+				if(open[j]) {
+					OCommandInfo* info = cmdVecData->GetInfo(used);
+					info->Set(odataLED_COMMAND2, primIDs[j], NumFrames);
+					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumFrames; frame++)
+						jval[frame].period = 1;
+					used++;
+				}
+			//we have to use OLEDCommandValue3 on the face and back LEDs if it's an ERS-7
+			for(unsigned int j=ERS7Info::FaceLEDPanelOffset; j<LEDOffset+NumLEDs; j++)
+				if(open[j]) {
+					OCommandInfo* info = cmdVecData->GetInfo(used);
+					info->Set(odataLED_COMMAND3, primIDs[j], NumFrames);
+					OLEDCommandValue3* jval = reinterpret_cast<OLEDCommandValue3*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumFrames; frame++)
+						jval[frame].period = 1;
+					used++;
+				}
+			//also have to use OJointCommandValue4 on the ears now
+			for(unsigned int j=BinJointOffset; j<BinJointOffset+NumBinJoints; j++)
+				if(open[j]) {
+					OCommandInfo* info = cmdVecData->GetInfo(used);
+					info->Set(odataJOINT_COMMAND4, primIDs[j], NumSlowFrames);
+					OJointCommandValue4* jval = reinterpret_cast<OJointCommandValue4*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumFrames; frame++)
+						jval[frame].period = 1;
+					used++;
+				}
+		} else {
+			for(unsigned int j=LEDOffset; j<LEDOffset+NumLEDs; j++)
+				if(open[j]) {
+					OCommandInfo* info = cmdVecData->GetInfo(used);
+					info->Set(odataLED_COMMAND2, primIDs[j], NumFrames);
+					OLEDCommandValue2* jval = reinterpret_cast<OLEDCommandValue2*>(cmdVecData->GetData(used)->value);
+					for(unsigned int frame=0; frame<NumFrames; frame++)
+						jval[frame].period = 1;
+					used++;
+				}
+			for(unsigned int j=BinJointOffset; j<BinJointOffset+NumBinJoints; j++)
+				if(open[j]) {
+					OCommandInfo* info = cmdVecData->GetInfo(used);
+					info->Set(odataJOINT_COMMAND3, primIDs[j], NumSlowFrames);
+					used++;
+				}
+		}
+	}
+}
+
+/*! Will round up size to the nearest page */
+RCRegion*
+MMCombo::InitRegion(unsigned int size) {
+	unsigned int pagesize=4096;
+	sError err=GetPageSize(&pagesize);
+	ASSERT(err==sSUCCESS,"Error "<<err<<" getting page size");
+	unsigned int pages=(size+pagesize-1)/pagesize;
+	return new RCRegion(pages*pagesize);
+}
+
+void
+MMCombo::addRunLevel() {
+	runLevel++;
+	if(runLevel==readyLevel) {
+		cout << "START UP BEHAVIOR..." << flush;
+		ProjectInterface::startupBehavior().DoStart();
+		cout << "START UP BEHAVIOR-DONE" << endl;
+	}
+}
+
+
+/*! @file
+ * @brief Implements MMCombo, the OObject which "forks" (sort of) into Main and Motion processes
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
+ * $State: Exp $
+ * $Date: 2005/08/04 21:10:11 $
+ */
+
+
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/MMCombo.h ./aperios/MMCombo/MMCombo.h
--- ../Tekkotsu_2.3/aperios/MMCombo/MMCombo.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/MMCombo.h	Wed Jun 29 18:06:33 2005
@@ -0,0 +1,142 @@
+//-*-c++-*-
+#ifndef INCLUDED_MMCombo_h_
+#define INCLUDED_MMCombo_h_
+
+#include "Shared/debuget.h"
+#include "Shared/RobotInfo.h"
+#include "Wireless/Wireless.h"
+#include "Events/EventTranslator.h"
+
+#include <OPENR/OObject.h>
+#include <OPENR/OSubject.h>
+#include <OPENR/OObserver.h>
+#include "aperios/MMCombo/def.h"
+
+//! Contains code for both MainObj and MotoObj processes
+/*! Why go to all this trouble?  Virtual functions and polymorphism!  Instead
+ *  of writing my own object typing and serialization system, I would rather
+ *  just use C++'s.  But function lookups of the run time type information (RTTI)
+ *  will break unless the object that created the object and the object that's
+ *  actually calling the function agree on what object A's information is.
+ *
+ *  The easiest way to guarantee this is to compile them as one object, and
+ *  then replace the strings in the source binary with strings for each of
+ *  the final objects so they'll each have their own identity, but share
+ *  the same code.
+ *
+ *  This is as close as I can get to a "fork", which is what i really want.
+ */
+class MMCombo : public OObject {
+public:
+	//! constructor
+	MMCombo();
+	virtual ~MMCombo() {} //!< destructor
+	
+	OSubject*    subject[numOfSubject];   //!< holds information for each of our subjects (data we provide)
+	OObserver*   observer[numOfObserver]; //!< holds information for each of the sources we're observing
+	
+	virtual OStatus DoInit   (const OSystemEvent&);      //!< first call (after constructor), set up memory
+	virtual OStatus DoStart  (const OSystemEvent&);      //!< second call, ask for messages
+	virtual OStatus DoStop   (const OSystemEvent&);      //!< next to last call, stop sending and receiving messages
+	virtual OStatus DoDestroy(const OSystemEvent&);      //!< last call (before destructor), clean up memory here
+	
+	void ReadyRegisterWorldState(const OReadyEvent&);    //!< main only, send out the state global
+	void GotWorldState(const ONotifyEvent& event);       //!< motion only, called when state global is received
+	void ReadyRegisterMotionManager(const OReadyEvent&); //!< motion only, send out motman global
+	void GotMotionManager(const ONotifyEvent& event);    //!< main only, called when motman global is received
+	void GotInterProcessEvent(const ONotifyEvent& event);//!< main only, called when another process sends an event
+	
+	void ReadySendJoints(const OReadyEvent& event);      //!< motion only (until main does ears again, then both) calls SendJoints, if DoStart has already been called
+	void GotSensorFrame(const ONotifyEvent& event);      //!< main only, called when new sensor information is available
+	void GotImage(const ONotifyEvent& event);            //!< main only, called when a new image is available
+	void GotAudio(const ONotifyEvent& event);            //!< main only, called when a new audio buffer is available
+	void GotPowerEvent(void * msg);                      //!< main only, called when a power event occurs (can be just status events)
+	
+	void GotMotionMsg(const ONotifyEvent& event);        //!< both, called when a new MotionManagerMsg has been received
+	
+	void GotSoundManager(const ONotifyEvent& event);     //!< both, called when the sndman global is received
+
+	void ListenCont (void* msg) { wireless->ListenCont(msg); }  //!< main only, called when //ALTODO
+	void BindCont   (void* msg) { wireless->BindCont(msg); }    //!< main only, called when //ALTODO
+	void ConnectCont(void* msg) { wireless->ConnectCont(msg); } //!< main only, called when //ALTODO
+	void SendCont   (void* msg) { wireless->SendCont(msg); }    //!< main only, called when //ALTODO
+	void ReceiveCont(void* msg) { wireless->ReceiveCont(msg); } //!< main only, called when //ALTODO
+	void CloseCont  (void* msg) { wireless->CloseCont(msg); }   //!< main only, called when //ALTODO
+
+protected:
+	void OpenPrimitives();                               //!< both, called from SetupOutputs() (mostly for motion, but main does ears), uses #open to tell which to open
+	void SetupOutputs(const bool to_open[NumOutputs]);   //!< both, called from DoInit() (mostly for motion, but main does ears)
+	RCRegion* InitRegion(unsigned int size);             //!< both, called to set up a shared memory region of a given size
+
+	RCRegion * motmanMemRgn;     //!< Motion creates, Main receives
+	RCRegion * worldStateMemRgn; //!< Main creates, Motion receives
+	RCRegion * soundManagerMemRgn; //!< SoundPlay creates, Main & Motion receives
+
+	OPrimitiveID primIDs[NumOutputs];    //!< both, Main ears only, Motion the rest
+	static const unsigned int NUM_COMMAND_VECTOR=2; //!< both, for double buffering
+	RCRegion*    region[NUM_COMMAND_VECTOR]; //!< both, the actual buffers
+
+	float  ledActivation[NumLEDs]; //!< Motion, used for partial LED activation
+
+	unsigned int runLevel;           //!< Main, incremented until all sections are ready
+	static const unsigned int readyLevel=5; //!< Main, runLevel at which StartBehavior is created. (1st power event, 1st sensor event, motman init, sndman init, MainObj::DoStart())
+	void addRunLevel();              //!< Main, checks runLevel and creates StartBehavior when ready
+
+	bool open[NumOutputs];    //!< both, holds information regarding which outputs are open in ("controlled by") this process
+	unsigned int num_open;  //!< both, count of how many are open
+
+	EventTranslator * etrans; //!< both, allows events to be sent between processes (from other processes besides these two too)
+
+	bool isStopped; //!< true if we've received a DoStart and no DoStop - we need this because sometimes an extra message seems to slip in after we've been told to stop, in which case we should ignore it
+
+	//! Motion only, maintains the activation level of the LEDs, returns whether it should be 'fired'
+	inline OLEDValue calcLEDValue(unsigned int i,float x) {
+		if(x<=0.0) {
+			ledActivation[i]*=.9; //decay activation... resets to keeps LEDs in sync, looks a little better
+			return oledOFF;
+		} else if(x>=1.0) {
+			return oledON;
+		} else {
+			x*=x; // squared to "gamma correct" - we can see a single pulse better than a single flicker - after image and all that
+			ledActivation[i]+=x;
+			if(ledActivation[i]>=1.0) {
+				ledActivation[i]-=1.0;
+				return oledON;
+			} else {
+				return oledOFF;
+			}						
+		}
+	}
+
+	//! returns @a f clipped to be between 0 and 1
+	inline static float clipRange01(float f) {
+		if(f>1)
+			return 1;
+		if(f<0)
+			return 0;
+		return f;
+	}
+
+private:
+//	WorldStateSerializer* wstateserializer;
+	MMCombo(const MMCombo&); //!< should never be called...
+	MMCombo& operator=(const MMCombo&); //!< should never be called...
+};
+
+/*! @file
+ * @brief Describes MMCombo, the OObject which "forks" (sort of) into Main and Motion processes
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:06:33 $
+ */
+
+#endif
+
+
+
+
+
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/MMCombo.ocf ./aperios/MMCombo/MMCombo.ocf
--- ../Tekkotsu_2.3/aperios/MMCombo/MMCombo.ocf	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/MMCombo.ocf	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,3 @@
+object MMCombo 16384 16384 128 cache notlb kernel
+#as opposed to: object mmcombo 3072 16384 128 cache tlb user
+#if we were using protected memory
diff -urdN ../Tekkotsu_2.3/aperios/MMCombo/stub.cfg ./aperios/MMCombo/stub.cfg
--- ../Tekkotsu_2.3/aperios/MMCombo/stub.cfg	Wed Dec 31 19:00:00 1969
+++ ./aperios/MMCombo/stub.cfg	Wed Jun 29 18:06:33 2005
@@ -0,0 +1,25 @@
+ObjectName : MMCombo
+NumOfSubject   : 6
+NumOfObserver  : 8
+Service : "MMCombo.RegisterWorldState.WorldState.S"          , null, ReadyRegisterWorldState()
+Service : "MMCombo.ReceiveWorldState.WorldState.O"           , null, GotWorldState()
+Service : "MMCombo.RegisterMotionManager.MotionManager.S"    , null, ReadyRegisterMotionManager()
+Service : "MMCombo.ReceiveMotionManager.MotionManager.O"     , null, GotMotionManager()
+Service : "MMCombo.EventTranslatorComm.EventBase.S"          , null, null
+Service : "MMCombo.EventTranslatorComm.EventBase.O"          , null, GotInterProcessEvent()
+Service : "MMCombo.MoveJoint.OCommandVectorData.S"           , null, ReadySendJoints()
+Service : "MMCombo.SensorFrame.OSensorFrameVectorData.O"     , null, GotSensorFrame()
+Service : "MMCombo.Image.OFbkImageVectorData.O"              , null, GotImage()
+Service : "MMCombo.Mic.OSoundVectorData.O"                   , null, GotAudio()
+Service : "MMCombo.MotionManagerComm.MotionManagerMsg.S"     , null, null
+Service : "MMCombo.MotionManagerComm.MotionManagerMsg.O"     , null, GotMotionMsg()
+Service : "MMCombo.ReceiveSoundManager.SoundManager.O"       , null, GotSoundManager()
+Service : "MMCombo.SoundManagerComm.SoundManagerMsg.S"       , null, null
+
+Extra : GotPowerEvent()
+Extra : ListenCont()
+Extra : BindCont()
+Extra : ConnectCont()
+Extra : SendCont()
+Extra : ReceiveCont()
+Extra : CloseCont()
diff -urdN ../Tekkotsu_2.3/aperios/Makefile.aperios ./aperios/Makefile.aperios
--- ../Tekkotsu_2.3/aperios/Makefile.aperios	Wed Dec 31 19:00:00 1969
+++ ./aperios/Makefile.aperios	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,47 @@
+ifeq ($(TEKKOTSU_ENVIRONMENT_CONFIGURATION),)
+$(error This makefile is not meant to be run directly.  It is intended to contain local-specific build instructions.  Please run 'make' from the main project directory.);
+endif
+
+.PHONY: 
+
+#Each directory represents a separate OObject aka process/thread
+OOBJECTS:=$(filter-out CVS bin include lib share man,$(subst aperios/,,$(shell find aperios -mindepth 1 -maxdepth 1 -type d -prune)))
+
+$(TK_BD)/aperios/aperios.d: $(shell find aperios -name "*$(SRCSUFFIX)")
+	@echo Generating $@...
+	@mkdir -p $(dir $@)
+	@rm -f $@;
+	@tk=`pwd`; \
+	for dir in $(OOBJECTS) ; do \
+		echo "$$tk/aperios/$$dir/$${dir}Stub.h $$tk/aperios/$$dir/$${dir}Stub.cc $$tk/aperios/$$dir/def.h $$tk/aperios/$$dir/entry.h: $$tk/aperios/$$dir/stub.cfg" >> $@ ; \
+		echo '	cd $$(dir $$@) && $$(STUBGEN) stub.cfg' >> $@ ;\
+		echo >> $@ ; \
+		echo "$(TK_BD)/aperios/$$dir/$${dir}Stub.o $(TK_BD)/aperios/$$dir/$${dir}Stub.d : $$tk/aperios/$$dir/$${dir}Stub.h $$tk/aperios/$$dir/$${dir}Stub.cc" >> $@ ; \
+		echo >> $@ ; \
+	done;
+
+OSRCS:=$(shell find aperios -name "*$(SRCSUFFIX)") $(foreach x,$(OOBJECTS),aperios/$(x)/$(x)Stub.cc)
+DEPENDS:=$(DEPENDS) $(addprefix $(TK_BD)/,$(OSRCS:$(SRCSUFFIX)=.d))
+
+#The "fork" we do of MMCombo into MainObj and MotoObj
+#crashes with optimization turned on... not sure why, but it's
+#not a big loss, just turn it off for these files
+$(TK_BD)/aperios/MMCombo/MMCombo.o $(TK_BD)/aperios/MMCombo/MMComboStub.o: %.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(TK_BD)/%,%,$@)); \
+	echo "Compiling $$src... (no -O2)"; \
+	$(CXX) $(filter-out -O2,$(CXXFLAGS)) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0; \
+
+$(TK_BD)/aperios/TinyFTPD/%.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(TK_BD)/%,%,$@)); \
+	echo "Compiling $$src... (filter-out -Weffc++ -DOPENR_DEBUG)"; \
+	$(CXX) $(filter-out -Weffc++ -DOPENR_DEBUG,$(CXXFLAGS)) -o $@ -c $$src > $(TK_BD)/aperios/TinyFTPD/$*.log 2>&1; \
+	retval=$$?; \
+	cat $(TK_BD)/aperios/TinyFTPD/$*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0;
+
+platformBuild: $(addprefix $(TK_BD)/,$(OSRCS:$(SRCSUFFIX)=.o)) $(TK_BD)/libtekkotsu.a
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/CVS/Entries ./aperios/SndPlay/CVS/Entries
--- ../Tekkotsu_2.3/aperios/SndPlay/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/CVS/Entries	Wed Aug 10 11:03:21 2005
@@ -0,0 +1,5 @@
+/SndPlay.cc/1.3/Wed Jun 29 22:06:37 2005//Ttekkotsu-2_4
+/SndPlay.h/1.3/Wed Jun 29 22:06:37 2005//Ttekkotsu-2_4
+/SoundPlay.ocf/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/stub.cfg/1.3/Wed Jun 29 22:06:37 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/CVS/Repository ./aperios/SndPlay/CVS/Repository
--- ../Tekkotsu_2.3/aperios/SndPlay/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/SndPlay
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/CVS/Root ./aperios/SndPlay/CVS/Root
--- ../Tekkotsu_2.3/aperios/SndPlay/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/CVS/Tag ./aperios/SndPlay/CVS/Tag
--- ../Tekkotsu_2.3/aperios/SndPlay/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/CVS/Tag	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/SndPlay.cc ./aperios/SndPlay/SndPlay.cc
--- ../Tekkotsu_2.3/aperios/SndPlay/SndPlay.cc	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/SndPlay.cc	Wed Jun 29 18:06:37 2005
@@ -0,0 +1,268 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+// Additional modifications for Tekkotsu framework
+
+#include <OPENR/OPENRAPI.h>
+#include <OPENR/OSyslog.h>
+#include <OPENR/core_macro.h>
+#include "aperios/SndPlay/entry.h"
+#include "SndPlay.h"
+
+#include <iostream>
+#include "Sound/SoundManager.h"
+#include "Shared/RobotInfo.h"
+#include "Shared/Config.h"
+#include "Shared/debuget.h"
+#include "Events/EventRouter.h"
+
+SndPlay::SndPlay()
+	: active(0), soundManagerMemRgn(NULL), etrans(NULL), speakerID(oprimitiveID_UNDEF)
+{
+	for (unsigned int i = 0; i < SOUND_NUM_BUFFER; i++)
+		region[i] = 0;
+
+	//need to register any events which we might be sending
+	EventTranslator::registerPrototype<EventBase>(); //Sound only sends the basic event type
+}
+
+OStatus
+SndPlay::DoInit(const OSystemEvent&)
+{
+	//OSYSDEBUG(("SndPlay::DoInit()\n"));
+
+	NEW_ALL_SUBJECT_AND_OBSERVER;
+	REGISTER_ALL_ENTRY;
+	SET_ALL_READY_AND_NOTIFY_ENTRY;
+
+	observer[obsSoundManagerComm]->SetBufCtrlParam(0,1,SoundManager::MAX_SND+1);
+	//+1 to MAX_SND so that we can still get a delete message after we've filled up
+
+	//Set process ID
+	ProcessID::setID(ProcessID::SoundProcess);
+
+	//Read config file
+	config=new Config("/ms/config/tekkotsu.cfg");
+
+	erouter = new EventRouter;
+	etrans=new IPCEventTranslator(*subject[sbjEventTranslatorComm]);
+
+	//soundManagerMemRgn -> sndman setup
+	soundManagerMemRgn = InitRegion(sizeof(SoundManager));
+	sndman=new ((SoundManager*)soundManagerMemRgn->Base()) SoundManager;
+	sndman->InitAccess(subject[sbjSoundManagerComm]);
+	for(unsigned int i=0; i<config->sound.preload.size(); i++)
+		sndman->LoadFile(config->sound.preload[i]);
+
+	OpenSpeaker();
+	NewSoundVectorData();
+	SetPowerAndVolume();
+	return oSUCCESS;
+}
+
+OStatus
+SndPlay::DoStart(const OSystemEvent&)
+{
+  //OSYSDEBUG(("SndPlay::DoStart()\n"));
+
+	ENABLE_ALL_SUBJECT;
+	ASSERT_READY_TO_ALL_OBSERVER;
+	return oSUCCESS;
+}
+
+OStatus
+SndPlay::DoStop(const OSystemEvent&)
+{
+	//OSYSDEBUG(("SndPlay::DoStop()\n"));
+
+	sndman->StopPlay();
+
+	DISABLE_ALL_SUBJECT;
+	DEASSERT_READY_TO_ALL_OBSERVER;
+
+	return oSUCCESS;
+}
+
+OStatus
+SndPlay::DoDestroy(const OSystemEvent&)
+{
+	for(unsigned int i=0; i<config->sound.preload.size(); i++)
+		sndman->ReleaseFile(config->sound.preload[i]);
+	delete etrans;
+	etrans=NULL;
+	delete erouter;
+	DELETE_ALL_SUBJECT_AND_OBSERVER;
+	return oSUCCESS;
+}
+
+void
+SndPlay::ReadySendSound(const OReadyEvent&)
+{
+	//	OSYSDEBUG(("SndPlay::Ready()\n"));
+	doSendSound();
+}
+
+void
+SndPlay::ReadyRegisterSoundManager(const OReadyEvent&) {
+	static bool is_init=true;
+	if(is_init) {
+		is_init=false;
+		cout << objectName << " Registering SoundManager" << endl;
+		subject[sbjRegisterSoundManager]->SetData(soundManagerMemRgn);
+		subject[sbjRegisterSoundManager]->NotifyObservers();
+	}
+}
+
+void
+SndPlay::GotSoundMsg(const ONotifyEvent& event) {
+	//	OSYSDEBUG(("SndPlay::GotSoundMsg()\n"));
+	sndman->ReceivedMsg(event);
+	unsigned int curact=sndman->GetNumPlaying();
+	//	std::cout << "got-active=" << active << " cur=" << curact << std::endl;
+	if(active==0 && curact>0) {
+		active=curact;
+		doSendSound();
+	}
+	observer[obsSoundManagerComm]->AssertReady();
+}
+
+void
+SndPlay::doSendSound() {
+	//	std::cout << "do-active=" << active << std::endl;
+	static unsigned int bufInUse=0;
+
+	active=sndman->GetNumPlaying();
+	if(active==0) { //if we don't have any active channels, don't send a buffer
+		if(bufInUse>0)
+			bufInUse--;
+		return;
+	}
+
+	RCRegion* rgn = FindFreeRegion();
+	if(rgn==NULL) //this can happen if a wakeup message comes in right after a sound stopped
+		return;
+	active=sndman->CopyTo(reinterpret_cast<OSoundVectorData*>(rgn->Base()));
+	subject[sbjSpeaker]->SetData(rgn);
+
+	if(bufInUse<SOUND_NUM_BUFFER-1) {
+		bufInUse++;
+		doSendSound();
+	} else //recursive base case
+		subject[sbjSpeaker]->NotifyObservers();
+}
+
+void
+SndPlay::OpenSpeaker()
+{
+	OStatus result = OPENR::OpenPrimitive(SpeakerLocator, &speakerID);
+	if (result != oSUCCESS)
+		OSYSLOG1((osyslogERROR, "%s : %s %d","SndPlay::OpenSpeaker()","OPENR::OpenPrimitive() FAILED", result));
+}
+
+void
+SndPlay::NewSoundVectorData()
+{
+	OStatus result;
+	MemoryRegionID    soundVecDataID;
+	OSoundVectorData* soundVecData;
+
+	/*soundUnitSize (bytes/buffer) = sample_rate (samples/sec)
+	 *                               * sample_bits (bits/sample)
+	 *                               * [1/8] (bytes/bit)
+	 *                               * SoundBufferTime (ms/buffer)
+	 *                               * [1/1000] (sec/ms)
+	 */
+	size_t soundUnitSize = config->sound.sample_rate*config->sound.sample_bits/8*SoundBufferTime/1000;
+
+	for (unsigned int i = 0; i < SOUND_NUM_BUFFER; i++) {
+		result = OPENR::NewSoundVectorData(1, soundUnitSize,&soundVecDataID, &soundVecData);
+		if (result != oSUCCESS) {
+			OSYSLOG1((osyslogERROR, "%s : %s %d","SndPlay::NewSoundVectorData()","OPENR::NewSoundVectorData() FAILED", result));
+			return;
+		}
+
+		soundVecData->SetNumData(1);
+		OSoundInfo* sinfo = soundVecData->GetInfo(0);
+		sinfo->Set(odataSOUND_VECTOR,speakerID,soundUnitSize);
+		sinfo->dataSize      = soundUnitSize;
+		sinfo->format        = osoundformatPCM;
+		sinfo->channel       = osoundchannelMONO;
+		sinfo->samplingRate  = config->sound.sample_rate;
+		sinfo->bitsPerSample = config->sound.sample_bits;
+
+		region[i] = new RCRegion(soundVecData->vectorInfo.memRegionID,soundVecData->vectorInfo.offset,(void*)soundVecData,soundVecData->vectorInfo.totalSize);
+	}
+}
+
+void
+SndPlay::SetPowerAndVolume()
+{
+	OStatus result;
+
+	result = OPENR::ControlPrimitive(speakerID,oprmreqSPEAKER_MUTE_OFF, 0, 0, 0, 0);
+	if (result != oSUCCESS)
+		OSYSLOG1((osyslogERROR, "%s : %s %d","SndPlay::SetPowerAndVolume()","OPENR::ControlPrimitive(SPEAKER_MUTE_OFF) FAILED", result));
+
+	OPrimitiveControl_SpeakerVolume volume(config->sound.volume);
+	result = OPENR::ControlPrimitive(speakerID,oprmreqSPEAKER_SET_VOLUME,&volume, sizeof(volume), 0, 0);
+	if (result != oSUCCESS)
+		OSYSLOG1((osyslogERROR, "%s : %s %d","SndPlay::SetPowerAndVolume()","OPENR::ControlPrimitive(SPEAKER_SET_VOLUME) FAILED",result));
+
+	if (config->sound.sample_rate == 16000 && config->sound.sample_bits == 16) {
+		OPrimitiveControl_SpeakerSoundType soundType(ospksndMONO16K16B);
+		result = OPENR::ControlPrimitive(speakerID,oprmreqSPEAKER_SET_SOUND_TYPE,&soundType, sizeof(soundType), 0, 0);
+		if (result != oSUCCESS)
+			OSYSLOG1((osyslogERROR, "%s : %s %d","SndPlay::SetPowerAndVolume()","OPENR::ControlPrimitive(SPEAKER_SET_SOUND_TYPE) FAILED",result));
+	}
+}
+
+/*! Will round up size to the nearest page */
+RCRegion*
+SndPlay::InitRegion(unsigned int size) {
+	unsigned int pagesize=4096;
+	sError err=GetPageSize(&pagesize);
+	ASSERT(err==sSUCCESS,"Error "<<err<<" getting page size");
+	unsigned int pages=(size+pagesize-1)/pagesize;
+	return new RCRegion(pages*pagesize);
+}
+
+RCRegion*
+SndPlay::FindFreeRegion()
+{
+	for (unsigned int i = 0; i < SOUND_NUM_BUFFER; i++)
+		if (region[i]->NumberOfReference() == 1)
+			return region[i];
+	return 0;
+}
+
+/*! @file
+ * @brief Implements the SndPlay process (a.k.a. OObject), which is responsible for sending sound buffers to the system to play
+ * @author Sony (Creator)
+ *
+ * This is basically the SoundPlay example from the Sony code, with a few modifications.
+ * Here's the license Sony provided with it:
+ *
+ * Copyright 2002,2003 Sony Corporation 
+ *
+ * Permission to use, copy, modify, and redistribute this software for
+ * non-commercial use is hereby granted.
+ *
+ * This software is provided "as is" without warranty of any kind,
+ * either expressed or implied, including but not limited to the
+ * implied warranties of fitness for a particular purpose.
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:06:37 $
+ */
+
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/SndPlay.h ./aperios/SndPlay/SndPlay.h
--- ../Tekkotsu_2.3/aperios/SndPlay/SndPlay.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/SndPlay.h	Wed Jun 29 18:06:37 2005
@@ -0,0 +1,91 @@
+#ifndef INCLUDED_SndPlay_h_
+#define INCLUDED_SndPlay_h_
+
+#include <OPENR/OObject.h>
+#include <OPENR/OSubject.h>
+#include <OPENR/OObserver.h>
+#include "aperios/MMCombo/def.h"
+
+#include "Events/EventTranslator.h"
+
+//! The process (a.k.a. OObject), which is responsible for sending sound buffers to the system to play
+/*! This sound process will purposely starve the system of sound buffers when nothing is
+ *  playing, both to eliminate needless zeroing of entire buffers, as well as to reduce system
+ *  overhead of playing empty buffers.
+ *
+ *  If you want to know how to play sounds, you should be looking at SoundManager's documentation.
+ *  
+ *  Basically a slightly modified version of the SoundPlay example code from Sony.  Here's their license:
+ *  Copyright 2002,2003 Sony Corporation 
+ *
+ *  Permission to use, copy, modify, and redistribute this software for
+ *  non-commercial use is hereby granted.
+ *
+ *  This software is provided "as is" without warranty of any kind,
+ *  either expressed or implied, including but not limited to the
+ *  implied warranties of fitness for a particular purpose.
+ */
+class SndPlay : public OObject {
+ public:
+	SndPlay();            //!< constructor
+	virtual ~SndPlay() {} //!< destructor
+
+	virtual OStatus DoInit   (const OSystemEvent& event); //!< called by system when time to do init
+	virtual OStatus DoStart  (const OSystemEvent& event); //!< called by system when time to start running
+	virtual OStatus DoStop   (const OSystemEvent& event); //!< called by system when time to stop running
+	virtual OStatus DoDestroy(const OSystemEvent& event); //!< called by system when time to free
+
+	void ReadySendSound(const OReadyEvent& event);            //!< called by system when it's ready for another sound buffer
+	void ReadyRegisterSoundManager(const OReadyEvent& event); //!< called by system when observers are ready to receive the SoundManager
+
+	void GotSoundMsg(const ONotifyEvent& event); //!< called by system when SoundManager has sent itself a message on a different process (either to add or remove sounds from memory)
+
+	OSubject*  subject[numOfSubject];   //!< array of subject IDs, used to identify outgoing data
+	OObserver* observer[numOfObserver]; //!< array of observer IDs, used to identify what's ready
+
+ private:
+	void      doSendSound();                 //!< called to send sound buffer(s) to system
+	void      OpenSpeaker();                 //!< initializes speaker
+	void      NewSoundVectorData();          //!< sets up sound buffers
+	void      SetPowerAndVolume();           //!< sets volume to max
+	RCRegion* InitRegion(unsigned int size); //!< inits each buffer
+	RCRegion* FindFreeRegion();              //!< finds the first sound buffer which system isn't using (buffers are recycled)
+		
+	static const size_t SOUND_NUM_BUFFER = 2;                                    //!< number of buffers to use
+	
+	unsigned int active; //!< number of active sound channels - if it's 0, we'll purposely starve system of sound buffers
+
+	RCRegion*      soundManagerMemRgn; //!< SndPlay creates, Main & Motion receive - Shared region used by SoundManager
+	EventTranslator * etrans; //!< will be given all events created by SoundManager to be forwarded to Main
+
+	OPrimitiveID   speakerID;  //!< ID returned to system after opening SPEAKER_LOCATOR
+	RCRegion*      region[SOUND_NUM_BUFFER]; //!< holds references to shared regions holding sound clips
+
+	SndPlay(const SndPlay&); //!< don't call
+	SndPlay& operator=(const SndPlay&); //!< don't call
+};
+
+/*! @file
+ * @brief Describes the SndPlay process (a.k.a. OObject), which is responsible for sending sound buffers to the system to play
+ * @author Sony (Creator)
+ *
+ * This is basically the SoundPlay example from the Sony code, with a few modifications.
+ * Here's the license Sony provided with it:
+ *
+ * Copyright 2002,2003 Sony Corporation 
+ *
+ * Permission to use, copy, modify, and redistribute this software for
+ * non-commercial use is hereby granted.
+ *
+ * This software is provided "as is" without warranty of any kind,
+ * either expressed or implied, including but not limited to the
+ * implied warranties of fitness for a particular purpose.
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:06:37 $
+ */
+
+#endif // SndPlay_h_DEFINED
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/SoundPlay.ocf ./aperios/SndPlay/SoundPlay.ocf
--- ../Tekkotsu_2.3/aperios/SndPlay/SoundPlay.ocf	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/SoundPlay.ocf	Wed Jun  1 01:47:59 2005
@@ -0,0 +1 @@
+object SoundPlay 3072 16384 128 cache notlb kernel
diff -urdN ../Tekkotsu_2.3/aperios/SndPlay/stub.cfg ./aperios/SndPlay/stub.cfg
--- ../Tekkotsu_2.3/aperios/SndPlay/stub.cfg	Wed Dec 31 19:00:00 1969
+++ ./aperios/SndPlay/stub.cfg	Wed Jun 29 18:06:37 2005
@@ -0,0 +1,8 @@
+ObjectName : SndPlay
+NumOfOSubject   : 4
+NumOfOObserver  : 1
+Service : "SndPlay.Speaker.OSoundVectorData.S", null, ReadySendSound()
+Service : "SndPlay.RegisterSoundManager.SoundManager.S", null, ReadyRegisterSoundManager()
+Service : "SndPlay.SoundManagerComm.SoundManagerMsg.O", null, GotSoundMsg()
+Service : "SndPlay.SoundManagerComm.SoundManagerMsg.S", null, null
+Service : "SndPlay.EventTranslatorComm.EventBase.S" , null, null
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Entries ./aperios/TinyFTPD/CVS/Entries
--- ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/CVS/Entries	Wed Aug 10 11:03:21 2005
@@ -0,0 +1,13 @@
+/FtpConfig.h/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/FtpDTP.cc/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/FtpDTP.h/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/FtpMethod.cc/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/FtpPI.cc/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/FtpPI.h/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/FtpRequest.cc/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/TCPConnection.h/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/TinyFTPD.cc/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/TinyFTPD.h/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/TinyFTPD.ocf/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/stub.cfg/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Repository ./aperios/TinyFTPD/CVS/Repository
--- ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/TinyFTPD
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Root ./aperios/TinyFTPD/CVS/Root
--- ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Tag ./aperios/TinyFTPD/CVS/Tag
--- ../Tekkotsu_2.3/aperios/TinyFTPD/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/CVS/Tag	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/FtpConfig.h ./aperios/TinyFTPD/FtpConfig.h
--- ../Tekkotsu_2.3/aperios/TinyFTPD/FtpConfig.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/FtpConfig.h	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,132 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#ifndef _FtpConfig_h_DEFINED
+#define _FtpConfig_h_DEFINED
+
+#define FTP_LISTEN_PORT    21
+#define FTP_DATA_PORT      20
+#define FTP_PASV_DATA_PORT 3000
+#define FTP_CONNECTION_MAX 4
+#define FTP_BUFFER_SIZE    8192
+#define FTP_PASSWD_PATH    "/MS/OPEN-R/MW/CONF/PASSWD"
+#define MAX_STRING_LENGTH  128
+#define MAX_LOGIN          8
+
+// some character constants
+// ---------------------------------------
+
+#define CR 13   // carriage return
+#define LF 10   // line feed
+#define HT 9    // horizontal tab
+#define SP 32   // space
+
+struct Passwd {
+    char user[MAX_STRING_LENGTH];
+    char pass[MAX_STRING_LENGTH];
+    char home[MAX_STRING_LENGTH];
+
+    Passwd() {
+        user[0] = '\0';
+        pass[0] = '\0';
+        home[0] = '\0';
+    }
+};
+
+enum FTPLoginState {
+    FTP_NOT_LOGIN,
+    FTP_LOGIN,
+    FTP_GET_REQUEST,
+    FTP_UNDEF
+};
+
+enum FTPDataType {
+    FTP_DATA_I,
+    FTP_DATA_A
+};
+
+// FTP Method
+// --------------------------------------------------------
+enum FTPMethod {
+    FTP_METHOD_USER,
+    FTP_METHOD_PASS,
+    FTP_METHOD_PORT,
+    FTP_METHOD_PASV,
+    FTP_METHOD_TYPE,
+    FTP_METHOD_MODE,
+    FTP_METHOD_STRU,
+    FTP_METHOD_RETR,
+    FTP_METHOD_STOR,
+    FTP_METHOD_APPE,
+    FTP_METHOD_RNFR,
+    FTP_METHOD_RNTO,
+    FTP_METHOD_DELE,
+    FTP_METHOD_CWD,
+    FTP_METHOD_CDUP,
+    FTP_METHOD_RMD,
+    FTP_METHOD_MKD,
+    FTP_METHOD_PWD,
+    FTP_METHOD_LIST,
+    FTP_METHOD_NLST,
+    FTP_METHOD_SYST,
+    FTP_METHOD_STAT,
+    FTP_METHOD_HELP,
+    FTP_METHOD_NOOP,
+    FTP_METHOD_QUIT,
+    FTP_METHOD_UNSUPPORTED
+};
+
+// FTP Status
+// --------------------------------------------------------
+enum FTPReplyCode
+{
+    // Positive Preliminary reply
+    FTP_REPLY_RESTART_MARKER  = 110,
+    FTP_REPLY_SERVER_READY    = 120,
+    FTP_REPLY_TRANSFER_START  = 125,
+    FTP_REPLY_OPEN_CONNECTION = 150,
+
+    // Positive Completion reply
+    FTP_REPLY_COMMAND_OK      = 200,
+    FTP_REPLY_SUPERFLUOUS     = 202,
+    FTP_REPLY_SYSTEM_STATUS   = 211,
+    FTP_REPLY_HELP_MESSAGE    = 214,
+    FTP_REPLY_SYSTEM_TYPE     = 215,
+    FTP_REPLY_SERVICE_READY   = 220,
+    FTP_REPLY_SERVICE_CLOSE   = 221,
+    FTP_REPLY_CLOSE_DATA      = 226,
+    FTP_REPLY_ENTER_PASSIVE   = 227,
+    FTP_REPLY_USER_LOGIN      = 230,
+    FTP_REPLY_FILE_ACTION_OK  = 250,
+    FTP_REPLY_PATH_CREATED    = 257,
+
+    // Positive Intermediate reply
+    FTP_REPLY_NEED_PASSWD     = 331,
+    FTP_REPLY_REQUESTED_FILE  = 350,
+
+    // Transient Negative Completion reply
+    FTP_REPLY_NOT_AVAILABLE   = 421,
+    FTP_REPLY_TRANSFER_ABORT  = 426,
+    FTP_REPLY_NOT_TAKEN       = 450,
+
+    // Permanent Negative Completion reply
+    FTP_REPLY_UNKNOWN_COMMAND = 500,
+    FTP_REPLY_NOT_IMPLEMENT   = 502,
+    FTP_REPLY_BAD_SEQUENCE    = 503,
+    FTP_REPLY_NOT_LOGIN       = 530,
+    FTP_REPLY_NO_FILE         = 550,
+    FTP_REPLY_NOT_TOKEN       = 553,
+
+    // Undefined Reply
+    FTP_REPLY_NONE = 999
+};
+
+#endif /* _FtpConfig_h_DEFINED*/
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/FtpDTP.cc ./aperios/TinyFTPD/FtpDTP.cc
--- ../Tekkotsu_2.3/aperios/TinyFTPD/FtpDTP.cc	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/FtpDTP.cc	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,383 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#include <OPENR/OSyslog.h>
+#include <OPENR/ODebug.h>
+#include "FtpDTP.h"
+#include "aperios/TinyFTPD/entry.h"
+
+FtpDTP::FtpDTP()
+{
+}
+
+OStatus
+FtpDTP::Initialize(const OID& myoid, const antStackRef& ipstack, void* index)
+{
+    OSYSDEBUG(("FtpDTP::Initialize()\n"));
+
+    myOID        = myoid;
+    ipstackRef   = ipstack;
+    continuation = index;
+
+    // initialize FTP connection
+    method   = FTP_METHOD_NOOP;
+    dataType = FTP_DATA_A;
+    passive  = false;
+    connectPort = FTP_DATA_PORT;
+
+    // initialize File System
+    ResetFilename();
+    strcpy(ftpDir, "/MS/");
+
+    connection.state = CONNECTION_CLOSED;
+
+    // 
+    // Allocate send buffer
+    //
+    antEnvCreateSharedBufferMsg sendBufferMsg(FTP_BUFFER_SIZE);
+
+    sendBufferMsg.Call(ipstackRef, sizeof(sendBufferMsg));
+    if (sendBufferMsg.error != ANT_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
+                  "FtpDTP::Initialize()",
+                  "Can't allocate send buffer",
+                  index, sendBufferMsg.error));
+        return oFAIL;
+    }
+
+    connection.sendBuffer = sendBufferMsg.buffer;
+    connection.sendBuffer.Map();
+    connection.sendData = (byte*)(connection.sendBuffer.GetAddress());
+
+    //
+    // Allocate receive buffer
+    //
+    antEnvCreateSharedBufferMsg recvBufferMsg(FTP_BUFFER_SIZE);
+
+    recvBufferMsg.Call(ipstackRef, sizeof(recvBufferMsg));
+    if (recvBufferMsg.error != ANT_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
+                  "FtpDTP::Initialize()",
+                  "Can't allocate receive buffer",
+                  index, recvBufferMsg.error));
+        return oFAIL;
+    }
+
+    connection.recvBuffer = recvBufferMsg.buffer;
+    connection.recvBuffer.Map();
+    connection.recvData = (byte*)(connection.recvBuffer.GetAddress());
+
+    return oSUCCESS;
+}
+
+OStatus
+FtpDTP::Listen()
+{
+    OSYSDEBUG(("FtpDTP::Listen()\n"));
+
+    if (connection.state != CONNECTION_CLOSED) return oFAIL;
+
+    //
+    // Create endpoint
+    //
+    antEnvCreateEndpointMsg tcpCreateMsg(EndpointType_TCP,
+                                         FTP_BUFFER_SIZE * 2);
+
+    tcpCreateMsg.Call(ipstackRef, sizeof(tcpCreateMsg));
+    if (tcpCreateMsg.error != ANT_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
+                  "FtpDTP::Listen()",
+                  "Can't create endpoint",
+                  (int)continuation, tcpCreateMsg.error));
+        return oFAIL;
+    }
+    connection.endpoint = tcpCreateMsg.moduleRef;
+
+    //
+    // Listen
+    //
+    TCPEndpointListenMsg listenMsg(connection.endpoint,
+                                   IP_ADDR_ANY, connectPort);
+    listenMsg.continuation = continuation;
+
+    listenMsg.Send(ipstackRef, myOID,
+                   Extra_Entry[entryListenContforDTP], sizeof(listenMsg));
+    
+    connection.state = CONNECTION_LISTENING;
+
+    return oSUCCESS;
+}
+
+OStatus
+FtpDTP::Connect()
+{
+    OSYSDEBUG(("FtpDTP::Connect()\n"));
+
+    if (connection.state != CONNECTION_CLOSED) return oFAIL;
+
+    //
+    // Create endpoint
+    //
+    antEnvCreateEndpointMsg tcpCreateMsg(EndpointType_TCP,
+                                         FTP_BUFFER_SIZE * 2);
+
+    tcpCreateMsg.Call(ipstackRef, sizeof(tcpCreateMsg));
+    if (tcpCreateMsg.error != ANT_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
+                  "FtpDTP::Connect()",
+                  "Can't create endpoint",
+                  (int)continuation, tcpCreateMsg.error));
+        return oFAIL;
+    }
+    connection.endpoint = tcpCreateMsg.moduleRef;
+
+    //
+    // Connect
+    //
+    TCPEndpointConnectMsg connectMsg(connection.endpoint,
+                                     0, FTP_DATA_PORT,
+                                     connectIP, connectPort);
+    connectMsg.continuation = continuation;
+
+    connectMsg.Send(ipstackRef, myOID,
+                    Extra_Entry[entryConnectContforDTP], sizeof(connectMsg));
+    
+    connection.state = CONNECTION_CONNECTING;
+
+    return oSUCCESS;
+}
+
+bool
+FtpDTP::ListenCont(TCPEndpointListenMsg* listenMsg)
+{
+    OSYSDEBUG(("FtpDTP::ListenCont() %x %d - %x %d\n",
+               listenMsg->lAddress,
+               listenMsg->lPort,
+               listenMsg->fAddress,
+               listenMsg->fPort
+               ));
+
+    if (listenMsg->error != TCP_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s %d",
+                  "FtpDTP::ListenCont()",
+                  "FAILED. listenMsg->error", listenMsg->error));
+        Close();
+        return false;
+    }
+
+    connection.state = CONNECTION_CONNECTED;
+
+    switch (method) {
+    case FTP_METHOD_RETR:
+        RetrieveSend();
+        break;
+
+    case FTP_METHOD_STOR:
+        connection.recvSize = 0;
+        Receive();
+        break;
+
+    case FTP_METHOD_LIST:
+        if (!ListSend()) {
+            Close();
+        }
+        break;
+    default:
+        OSYSDEBUG(("not yet\n"));
+        break;
+    }
+
+    return true;
+}
+
+bool
+FtpDTP::ConnectCont(TCPEndpointConnectMsg* connectMsg)
+{
+    OSYSDEBUG(("FtpDTP::ConnectCont()\n"));
+
+    if (connectMsg->error != TCP_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s %d",
+                  "FtpDTP::ConnectCont()",
+                  "FAILED. connectMsg->error", connectMsg->error));
+        Close();
+        return false;
+    }
+
+    connection.state = CONNECTION_CONNECTED;
+
+    switch (method) {
+    case FTP_METHOD_RETR:
+        RetrieveSend();
+        break;
+
+    case FTP_METHOD_STOR:
+        connection.recvSize = 0;
+        Receive();
+        break;
+
+    case FTP_METHOD_LIST:
+        if (!ListSend()) {
+            Close();
+        }
+        break;
+    default:;//CHANGE_ET added default case to avoid unhandled enumeration warnings
+    }
+    return true;
+}
+
+OStatus
+FtpDTP::Send()
+{
+    OSYSDEBUG(("FtpDTP::Send() "));
+
+    if (connection.state != CONNECTION_CONNECTED) return oFAIL;
+
+    OSYSDEBUG(("%d\n", connection.sendSize));
+
+    TCPEndpointSendMsg sendMsg(connection.endpoint,
+                               connection.sendData,
+                               connection.sendSize);
+    sendMsg.continuation = continuation;
+
+    sendMsg.Send(ipstackRef, myOID,
+                 Extra_Entry[entrySendContforDTP],
+                 sizeof(TCPEndpointSendMsg));
+
+    connection.state = CONNECTION_SENDING;
+    connection.sendSize = 0;
+    return oSUCCESS;
+}
+
+bool
+FtpDTP::SendCont(TCPEndpointSendMsg* sendMsg)
+{
+    OSYSDEBUG(("FtpDTP::SendCont()\n"));
+
+    if (sendMsg->error != TCP_SUCCESS) {
+        if (sendMsg->error == TCP_BUFFER_INVALID
+            && method == FTP_METHOD_NOOP) {
+            Close();
+            return true;
+        } else {
+            OSYSLOG1((osyslogERROR, "%s : %s %d",
+                      "FtpDTP::SendCont()",
+                      "FAILED. sendMsg->error", sendMsg->error));
+            Close();
+            return false;
+        }
+    }
+
+    connection.state = CONNECTION_CONNECTED;
+
+    switch (method) {
+    case FTP_METHOD_RETR:
+        if (!RetrieveSend()) {
+            Close();
+            return true;
+        }
+        break;
+
+    case FTP_METHOD_LIST:
+        if (!ListSend()) {
+            Close();
+            return true;
+        }
+        break;
+
+    default :
+        Close();
+        return true;
+    }
+    return false;
+}
+
+OStatus
+FtpDTP::Receive()
+{
+
+    if (connection.state != CONNECTION_CONNECTED
+        && connection.state != CONNECTION_SENDING) return oFAIL;
+
+    OSYSDEBUG(("FtpDTP::Receive()\n"));
+
+    TCPEndpointReceiveMsg receiveMsg(connection.endpoint,
+                                     connection.recvData,
+                                     1, FTP_BUFFER_SIZE);
+    receiveMsg.continuation = continuation;
+
+    receiveMsg.Send(ipstackRef, myOID,
+                    Extra_Entry[entryReceiveContforDTP], sizeof(receiveMsg));
+
+    connection.state = CONNECTION_RECEIVING;
+    return oSUCCESS;
+}
+
+bool
+FtpDTP::ReceiveCont(TCPEndpointReceiveMsg* receiveMsg)
+{
+    OSYSDEBUG(("FtpDTP::ReceiveCont()\n"));
+
+    connection.recvSize = receiveMsg->sizeMin;
+    if (receiveMsg->error == TCP_CONNECTION_CLOSED) {
+        Save(connection.recvData, 0);
+        Close();
+        return true;
+    }
+
+    if (receiveMsg->error != TCP_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s %d",
+                  "FtpDTP::ReceiveCont()",
+                  "FAILED. receiveMsg->error", receiveMsg->error));
+        Close();
+        return false;
+    }
+
+    // receive some more
+    Save(connection.recvData, receiveMsg->sizeMin, false);
+    connection.state = CONNECTION_CONNECTED;
+    connection.recvSize = 0;
+    Receive();
+
+    return false;
+}
+
+OStatus
+FtpDTP::Close()
+{
+    OSYSDEBUG(("FtpDTP::Close() %d\n", connection.state));
+
+    if (connection.state == CONNECTION_CLOSED
+        || connection.state == CONNECTION_CLOSING) return oFAIL;
+
+    TCPEndpointCloseMsg closeMsg(connection.endpoint);
+    closeMsg.continuation = continuation;
+
+    closeMsg.Send(ipstackRef, myOID,
+                  Extra_Entry[entryCloseContforDTP], sizeof(closeMsg));
+
+    connection.state = CONNECTION_CLOSING;
+    ResetFilename();
+    method   = FTP_METHOD_NOOP;
+    dataType = FTP_DATA_A;
+    passive  = false;
+    connectPort = FTP_DATA_PORT;
+
+    return oSUCCESS;
+}
+
+void
+FtpDTP::CloseCont(TCPEndpointCloseMsg* /*closeMsg*/) //CHANGE_ET unused parameter
+{
+    OSYSDEBUG(("FtpDTP::CloseCont()\n"));
+    
+    connection.state = CONNECTION_CLOSED;
+}
+
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/FtpDTP.h ./aperios/TinyFTPD/FtpDTP.h
--- ../Tekkotsu_2.3/aperios/TinyFTPD/FtpDTP.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/FtpDTP.h	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,103 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#ifndef _FtpDTP_h_DEFINED
+#define _FtpDTP_h_DEFINED
+
+#include <stdio.h>
+#include <dirent.h>
+#include <EndpointTypes.h>
+#include <TCPEndpointMsg.h>
+#include "TCPConnection.h"
+#include "FtpConfig.h"
+
+class FtpDTP
+{
+public:
+    FtpDTP();
+    virtual ~FtpDTP() {}
+
+    OStatus Initialize(const OID& myoid,
+                       const antStackRef& ipstack, void* index);
+    bool ListenCont (TCPEndpointListenMsg*  listenMsg);
+    bool ConnectCont(TCPEndpointConnectMsg* connectMsg);
+    bool SendCont   (TCPEndpointSendMsg*    sendMsg);
+    bool ReceiveCont(TCPEndpointReceiveMsg* receiveMsg);
+    void CloseCont  (TCPEndpointCloseMsg*   closeMsg);
+
+    OStatus Close  ();
+
+    // Set
+    void SetType(FTPDataType type) {dataType = type;};
+    void SetUser(char *user);
+    void SetHome(char *home);
+
+    // Get
+    ConnectionState GetState() {return connection.state;};
+    FTPDataType GetType() {return dataType;};
+    char * GetFilename() {return ftpFile;};
+    char * GetDirectry() {return ftpDir;};
+    size_t GetFileSize(char *name);
+    char * GetUser() {return ftpUser;};
+
+    // Method
+    Port SetIP   (IPAddress ip);
+    bool SetPort (char* ipport);
+    bool Retrieve(char* filename);
+    bool Store   (char* filename);
+    bool ChangeDir(char* dir);
+    bool MakeDir(char* dir);
+    bool RemoveDir(char* dir);
+    bool Delete(char* filename);
+    bool List    (char* dir);
+    bool RenameFrom(char *file);
+    bool RenameTo(char *file);
+    void ResetFilename();
+
+private:
+    OStatus Listen ();
+    OStatus Connect();
+    OStatus Send   ();
+    OStatus Receive();
+
+    void Save(byte *data, int length, bool end = true);
+    void DirNorm(char *dir);
+    bool RetrieveSend();
+    bool ListSend();
+
+    OID myOID;
+    antStackRef ipstackRef;
+
+    // connection info
+    IPAddress connectIP;
+    Port      connectPort;
+    FTPMethod method;
+    bool passive;
+
+    // File Info
+    FTPDataType dataType;
+    char ftpUser[MAX_STRING_LENGTH];
+    char ftpHome[MAX_STRING_LENGTH];
+    char ftpDir[MAX_STRING_LENGTH];
+    char ftpFile[MAX_STRING_LENGTH];
+    bool listLong;
+    bool total;
+    FILE* fp;
+    DIR*  dirp;
+
+    void* continuation;
+    TCPConnection connection;
+
+		FtpDTP(const FtpDTP&); //CHANGE_ET copy constructor, don't call
+		FtpDTP operator=(const FtpDTP&); //CHANGE_ET assignment operator, don't call
+};
+
+#endif /* _FtpDTP_h_DEFINED */
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/FtpMethod.cc ./aperios/TinyFTPD/FtpMethod.cc
--- ../Tekkotsu_2.3/aperios/TinyFTPD/FtpMethod.cc	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/FtpMethod.cc	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,525 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#include <sys/stat.h>
+#include <sys/unistd.h>
+#include <OPENR/OSyslog.h>
+#include <OPENR/ODebug.h>
+#include <OPENR/OCalendarTime.h>
+#include <stdlib.h>
+#include "FtpDTP.h"
+#include <stdio.h>
+
+Port 
+FtpDTP::SetIP(IPAddress ip)
+{
+    connectIP = ip;
+    connectPort = FTP_PASV_DATA_PORT + (int)continuation;
+    passive = true;
+    Listen();
+    return connectPort;
+}
+
+bool
+FtpDTP::SetPort(char* ipport)
+{
+    longword buf;
+    uint32 ip = 0;
+    uint16 port = 0;
+
+    buf = atoi(ipport);
+    ip |= (buf << 24);
+    while (*ipport++ != ',') {
+        ;
+    }
+    buf = atoi(ipport);
+    ip |= (buf << 16);
+    while (*ipport++ != ',') {
+        ;
+    }
+    buf = atoi(ipport);
+    ip |= (buf << 8);
+    while (*ipport++ != ',') {
+        ;
+    }
+    buf = atoi(ipport);
+    ip |= buf;
+    while (*ipport++ != ',') {
+        ;
+    }
+
+    buf = atoi(ipport);
+    port |= (buf << 8);
+    while (*ipport++ != ',') {
+        ;
+    }
+    buf = atoi(ipport);
+    port |= buf;
+
+    OSYSDEBUG(("FtpDTP::Port():Set IP:%x Port:%d\n", ip, port));
+    connectIP   = (IPAddress)ip;
+    connectPort = (Port)port;
+    passive = false;
+    return true;
+}
+
+bool
+FtpDTP::Store(char* filename)
+{
+    char file[MAX_STRING_LENGTH * 2];
+    method = FTP_METHOD_STOR;
+
+    if (filename[0] == '/') {
+        sprintf(file, "%s", filename);
+    } else {
+        sprintf(file, "%s%s", ftpDir, filename);
+    }
+
+    DirNorm(file);
+
+    if (!strncmp(file, ftpHome, strlen(ftpHome))) {
+        if((fp = fopen(file, "wb")) == NULL) {
+            OSYSLOG1((osyslogERROR, "Ftpd::File Open Failed %s. errno=%d", file,errno));
+            return false;
+        }
+    } else {
+        return false;
+    }
+
+    strncpy(ftpFile, filename, MAX_STRING_LENGTH);
+
+    if (passive) {
+        if (connection.state == CONNECTION_CONNECTED) {
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else {
+        Connect();
+    }
+    return true;
+}
+
+bool
+FtpDTP::Retrieve(char* filename)
+{
+    char file[MAX_STRING_LENGTH * 2];
+    method = FTP_METHOD_RETR;
+
+    if (filename[0] == '/') {
+        sprintf(file, "%s", filename);
+    } else {
+        sprintf(file, "%s%s", ftpDir, filename);
+    }
+
+    DirNorm(file);
+
+    if (!strncmp(file, ftpHome, strlen(ftpHome))) {
+        if((fp = fopen(file, "rb")) == NULL) {
+            OSYSLOG1((osyslogERROR, "FtpDTP::File Open Failed %s.", file));
+            return false;
+        }
+    } else {
+        return false;
+    }
+
+    strncpy(ftpFile, filename, MAX_STRING_LENGTH);
+
+    if (passive) {
+        if (connection.state == CONNECTION_CONNECTED) {
+            RetrieveSend();
+        }
+    } else {
+        Connect();
+    }
+    return true;
+}
+
+bool
+FtpDTP::RetrieveSend()
+{
+    if (dataType == FTP_DATA_A) {
+       connection.recvSize
+           = fread(connection.recvData, 1, FTP_BUFFER_SIZE / 2, fp);
+       if (FTP_BUFFER_SIZE / 2 > connection.recvSize) {
+            byte *cur_r = connection.recvData;
+            byte *cur_s = connection.sendData;
+            connection.sendSize = connection.recvSize;
+            for (int i = 0; i < connection.recvSize; i++, cur_r++) {
+                if (*cur_r == LF) {
+                    if ((cur_r != connection.recvData)
+                        && (*(cur_r - 1) != CR)) {
+                        *cur_s++ = CR;
+                        connection.sendSize++;
+                    }
+                    *cur_s++ = *cur_r;
+                } else {
+                    *cur_s++ = *cur_r;
+                }
+            }
+            fclose(fp);
+            method = FTP_METHOD_NOOP;
+            Send();
+        } else {
+            byte *cur_r = connection.recvData;
+            byte *cur_s = connection.sendData;
+            connection.sendSize = connection.recvSize;
+            for (int i = 0; i < connection.recvSize; i++, cur_r++) {
+                if (*cur_r == LF) {
+                    if ((cur_r != connection.recvData)
+                        && (*(cur_r - 1) != CR)) {
+                        *cur_s++ = CR;
+                        connection.sendSize++;
+                    }
+                    *cur_s++ = *cur_r;
+                } else {
+                    *cur_s++ = *cur_r;
+                }
+            }
+            Send();
+        }
+    } else {
+        connection.sendSize
+            = fread(connection.sendData, 1, FTP_BUFFER_SIZE, fp);
+        if (FTP_BUFFER_SIZE > connection.sendSize) {
+            fclose(fp);
+            method = FTP_METHOD_NOOP;
+            Send();
+        } else {
+            Send();
+        }
+    }
+    return true;
+}
+
+bool
+FtpDTP::RenameFrom(char *file)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+
+    if (file[0] == '/') {
+        sprintf(tmp, "%s", file);
+    } else {
+        sprintf(tmp, "%s%s", ftpDir, file);
+    }
+
+    DirNorm(tmp);
+
+    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
+			FILE *tfp = fopen(tmp, "r"); //CHANGE_ET rename fp to tfp to avoid shadowed variable
+        if (tfp != NULL) {
+            strncpy(ftpFile, tmp, MAX_STRING_LENGTH);
+            fclose(tfp);
+            return true;
+        }
+    }
+
+    return false;
+}
+
+bool
+FtpDTP::RenameTo(char *file)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+
+    if (file[0] == '/') {
+        sprintf(tmp, "%s", file);
+    } else {
+        sprintf(tmp, "%s%s", ftpDir, file);
+    }
+
+    DirNorm(tmp);
+
+    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
+        int ret = rename(ftpFile, tmp);
+        if (ret == 0) {
+            strcpy(ftpFile, "");
+            return true;
+        }
+    }
+
+    strcpy(ftpFile, "");
+    return false;
+}
+
+bool
+FtpDTP::List(char* dir)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+    total = true;
+
+    if ((dir[0] != '\0') && (dir[0] == '/')) {
+        sprintf(tmp, "%s/", dir);
+        listLong = false;
+    } else if ((dir[0] != '\0') && (dir[0] == '-')) {
+        sprintf(tmp, "%s", ftpDir);
+        listLong = true;
+    } else {
+        sprintf(tmp, "%s%s", ftpDir, dir);
+        listLong = false;
+    }
+
+    listLong = true;
+
+    DirNorm(tmp);
+
+    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
+			if ((dirp = opendir(tmp))) { //CHANGE_ET extra parenthesis to clarify assignment used as truth value
+            method = FTP_METHOD_LIST;
+            strcpy(ftpFile, tmp);
+            if (passive) {
+                if (connection.state == CONNECTION_CONNECTED) {
+                    if (!ListSend()) {
+                        Close();
+                    }
+                }
+            } else {
+                Connect();
+            }
+            return true;
+        }
+    }
+    return false;
+}
+
+bool
+FtpDTP::ListSend()
+{
+    dirent *entry;
+    char tmp[MAX_STRING_LENGTH];
+
+    if (total) {
+        sprintf((char *)connection.sendData,
+                "total %d\r\n", 0);
+        connection.sendSize = strlen((char *)connection.sendData);
+        Send();
+        total = false;
+        return true;
+    }
+
+    entry = readdir(dirp);
+    if (entry) {
+        struct stat statbuf;
+        sprintf(tmp, "%s/%s", ftpFile, entry->d_name);
+        DirNorm(tmp);
+        
+        stat(tmp, &statbuf); //CHANGE_ET unused variable 'ret'
+        if (listLong) {
+            sprintf((char *)connection.sendData,
+                    "%c%c%c%c%c%c%c%c%c%c %x %s %s %-d %s %d %d %s\r\n",
+                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'd' : '-',
+                    (statbuf.st_mode & S_IRUSR) ? 'r' : '-',
+                    (statbuf.st_mode & S_IWUSR) ? 'w' : '-',
+                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'x' : '-',
+                    (statbuf.st_mode & S_IRUSR) ? 'r' : '-',
+                    (statbuf.st_mode & S_IWUSR) ? 'w' : '-',
+                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'x' : '-',
+                    (statbuf.st_mode & S_IRUSR) ? 'r' : '-',
+                    (statbuf.st_mode & S_IWUSR) ? 'w' : '-',
+                    (statbuf.st_mode & S_IFMT) == S_IFDIR ? 'x' : '-',
+                    0,
+                    "AIBO",
+                    "AIBO",
+                    statbuf.st_size,
+                    "May",
+                    11,
+                    1999,
+                    entry->d_name
+                );
+        } else {
+            if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
+                sprintf((char *)connection.sendData,
+                        "%s/\r\n",
+                        entry->d_name);
+            } else {
+                sprintf((char *)connection.sendData,
+                        "%s\r\n",
+                        entry->d_name);
+            }
+        }
+        connection.sendSize = strlen((char *)connection.sendData);
+        Send();
+    } else {
+        method = FTP_METHOD_NOOP;
+        closedir(dirp);
+        return false;
+    }
+
+    return true;
+}
+
+bool
+FtpDTP::ChangeDir(char* dir)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+
+    if (dir[0] == '/') {
+        sprintf(tmp, "%s/", dir);
+    } else {
+        sprintf(tmp, "%s%s/", ftpDir, dir);
+    }
+
+    DirNorm(tmp);
+
+    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
+        DIR* tmpdirp;
+        if ((tmpdirp = opendir(tmp))) { //CHANGE_ET extra parenthesis to clarify assignment used as truth value
+            closedir(tmpdirp);
+            strcpy(ftpDir, tmp);
+            return true;
+        }
+    }
+
+    return false;
+}
+
+bool
+FtpDTP::MakeDir(char* dir)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+
+    if (dir[0] == '/') {
+        sprintf(tmp, "%s", dir);
+    } else {
+        sprintf(tmp, "%s%s", ftpDir, dir);
+    }
+
+    DirNorm(tmp);
+
+    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
+        if (!mkdir(tmp, 0777)) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+bool
+FtpDTP::RemoveDir(char* dir)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+
+    if (dir[0] == '/') {
+        sprintf(tmp, "%s", dir);
+    } else {
+        sprintf(tmp, "%s%s", ftpDir, dir);
+    }
+
+    DirNorm(tmp);
+
+    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
+        if (!rmdir(tmp)) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+bool
+FtpDTP::Delete(char* filename)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+
+    if (filename[0] == '/') {
+        sprintf(tmp, "%s", filename);
+    } else {
+        sprintf(tmp, "%s%s", ftpDir, filename);
+    }
+
+    DirNorm(tmp);
+
+    if (!strncmp(tmp, ftpHome, strlen(ftpHome))) {
+        if (!remove(tmp)) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+void
+FtpDTP::Save(byte *data, int length, bool end)
+{
+    OSYSDEBUG(("FtpDTP::Save %d %d\n", length, end));
+    if (length) fwrite(data, length, 1, fp);
+    if (end) {
+        fclose(fp);
+        strcpy(ftpFile, "");
+    }
+}
+
+size_t
+FtpDTP::GetFileSize(char *name)
+{
+    struct stat statbuf;
+    int ret = stat(name, &statbuf);
+    if (ret == 0) {
+        return statbuf.st_size;
+    } else {
+        return 0;
+    }
+}
+
+void
+FtpDTP::ResetFilename()
+{
+    strcpy(ftpFile, "");
+}
+
+void
+FtpDTP::SetUser(char *user)
+{
+    strncpy(ftpUser, user, MAX_STRING_LENGTH);
+}
+
+void
+FtpDTP::SetHome(char *home)
+{
+    sprintf(ftpHome, "%s/", home);
+
+    DirNorm(ftpHome);
+    strcpy(ftpDir, ftpHome);
+}
+
+void
+FtpDTP::DirNorm(char *dir)
+{
+    char tmp[MAX_STRING_LENGTH * 2];
+    int length = strlen(dir);
+    int cur = 0;
+
+    for (int i = 0; i < length + 1; i++) {
+        OSYSDEBUG(("DirNorm %c\n", dir[i]));
+        if (dir[i] == '.') {
+            if ((dir[i + 1] == '.') && (dir[i + 2] == '/')) {
+                cur -= 2;
+                while(tmp[cur] != '/') {
+                    cur--;
+                }
+                cur++;
+            } else if (dir[i + 1] == '/') {
+                i++;
+            } else {
+                tmp[cur++] = toupper(dir[i]);
+            }
+        } else if (dir[i] == '/') {
+            if ((cur == 0) || ((cur != 0) && (tmp[cur - 1] != '/'))) {
+                tmp[cur++] = toupper(dir[i]);
+            }
+        } else {
+            tmp[cur++] = toupper(dir[i]);
+        }
+    }
+        
+    strncpy(dir, tmp, MAX_STRING_LENGTH);
+    dir[MAX_STRING_LENGTH] = '0';
+}
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/FtpPI.cc ./aperios/TinyFTPD/FtpPI.cc
--- ../Tekkotsu_2.3/aperios/TinyFTPD/FtpPI.cc	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/FtpPI.cc	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,347 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#include <stdarg.h>
+#include <OPENR/OSyslog.h>
+#include <EndpointTypes.h>
+#include <TCPEndpointMsg.h>
+#include "FtpPI.h"
+#include "aperios/TinyFTPD/entry.h"
+
+FtpPI::FtpPI()
+{
+}
+
+OStatus
+FtpPI::Initialize(const OID& myoid, const antStackRef& ipstack,
+                  void* index, OList<Passwd, MAX_LOGIN> *pass)
+{
+    OSYSDEBUG(("FtpPI::Initialize()\n"));
+
+    myOID        = myoid;
+    ipstackRef   = ipstack;
+    continuation = index;
+    passwd       = pass;
+ 
+    state = FTP_NOT_LOGIN;
+    connection.state = CONNECTION_CLOSED;
+
+    // 
+    // Allocate send buffer
+    //
+    antEnvCreateSharedBufferMsg sendBufferMsg(FTP_BUFFER_SIZE);
+
+    sendBufferMsg.Call(ipstackRef, sizeof(sendBufferMsg));
+    if (sendBufferMsg.error != ANT_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
+                  "FtpPI::Initialize()",
+                  "Can't allocate send buffer",
+                  index, sendBufferMsg.error));
+        return oFAIL;
+    }
+
+    connection.sendBuffer = sendBufferMsg.buffer;
+    connection.sendBuffer.Map();
+    connection.sendData = (byte*)(connection.sendBuffer.GetAddress());
+
+    //
+    // Allocate receive buffer
+    //
+    antEnvCreateSharedBufferMsg recvBufferMsg(FTP_BUFFER_SIZE);
+
+    recvBufferMsg.Call(ipstackRef, sizeof(recvBufferMsg));
+    if (recvBufferMsg.error != ANT_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
+                  "FtpPI::Initialize()",
+                  "Can't allocate receive buffer",
+                  index, recvBufferMsg.error));
+        return oFAIL;
+    }
+
+    connection.recvBuffer = recvBufferMsg.buffer;
+    connection.recvBuffer.Map();
+    connection.recvData = (byte*)(connection.recvBuffer.GetAddress());
+    
+    ftpDTP.Initialize(myOID, ipstackRef, index);
+    Listen();
+
+    return oSUCCESS;
+}
+
+OStatus
+FtpPI::Listen()
+{
+    OSYSDEBUG(("FtpPI::Listen()\n"));
+
+    if (connection.state != CONNECTION_CLOSED) return oFAIL;
+
+    //
+    // Create endpoint
+    //
+    antEnvCreateEndpointMsg tcpCreateMsg(EndpointType_TCP,
+                                         FTP_BUFFER_SIZE * 2);
+
+    tcpCreateMsg.Call(ipstackRef, sizeof(tcpCreateMsg));
+    if (tcpCreateMsg.error != ANT_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s[%d] antError %d",
+                  "FtpPI::Listen()",
+                  "Can't create endpoint",
+                  (int)continuation, tcpCreateMsg.error));
+        return oFAIL;
+    }
+    connection.endpoint = tcpCreateMsg.moduleRef;
+
+    //
+    // Listen
+    //
+    TCPEndpointListenMsg listenMsg(connection.endpoint,
+                                   IP_ADDR_ANY, FTP_LISTEN_PORT);
+    listenMsg.continuation = continuation;
+
+    listenMsg.Send(ipstackRef, myOID,
+                   Extra_Entry[entryListenContforPI], sizeof(listenMsg));
+    
+    connection.state = CONNECTION_LISTENING;
+
+    return oSUCCESS;
+}
+
+void
+FtpPI::ListenCont(TCPEndpointListenMsg* listenMsg)
+{
+    OSYSDEBUG(("FtpPI::ListenCont() %x %d - %x %d\n",
+               listenMsg->lAddress,
+               listenMsg->lPort,
+               listenMsg->fAddress,
+               listenMsg->fPort));
+
+    if (listenMsg->error != TCP_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s %d",
+                  "FtpPI::ListenCont()",
+                  "FAILED. listenMsg->error", listenMsg->error));
+        Close();
+        return;
+    }
+
+    ipaddr = listenMsg->lAddress;
+
+    connection.state = CONNECTION_CONNECTED;
+    Send(FTP_REPLY_SERVICE_READY, "AIBO FTP Server ready");
+    connection.recvSize = 0;
+    Receive();
+}
+
+OStatus
+FtpPI::Send(FTPReplyCode code, char *format, ...)
+{
+    OSYSDEBUG(("FtpPI::Send()\n"));
+    
+    if (connection.state != CONNECTION_CONNECTED) return oFAIL;
+
+    char buf[MAX_STRING_LENGTH];
+    va_list ap;
+    va_start(ap, format);
+    vsprintf(buf, format, ap);
+    va_end(ap);
+
+    sprintf((char *)connection.sendData, "%03d %s\r\n", code, buf);
+
+    TCPEndpointSendMsg sendMsg(connection.endpoint,
+                               connection.sendData,
+                               strlen((char *)connection.sendData));
+    sendMsg.continuation = continuation;
+
+    sendMsg.Send(ipstackRef, myOID,
+                 Extra_Entry[entrySendContforPI], sizeof(sendMsg));
+
+    connection.state = CONNECTION_SENDING;
+    connection.sendSize = 0;
+    return oSUCCESS;
+}
+
+void
+FtpPI::SendCont(TCPEndpointSendMsg* sendMsg)
+{
+    OSYSDEBUG(("FtpPI::SendCont()\n"));
+
+    if (sendMsg->error != TCP_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s %d",
+                  "FtpPI::SendCont()",
+                  "FAILED. sendMsg->error", sendMsg->error));
+        Close();
+        return;
+    }
+
+    connection.state = CONNECTION_CONNECTED;
+}
+
+OStatus
+FtpPI::Receive()
+{
+    OSYSDEBUG(("FtpPI::Receive()\n"));
+
+    if (connection.state != CONNECTION_CONNECTED
+        && connection.state != CONNECTION_SENDING) return oFAIL;
+
+    TCPEndpointReceiveMsg receiveMsg(connection.endpoint,
+                                     connection.recvData,
+                                     1,
+                                     FTP_BUFFER_SIZE);
+    receiveMsg.continuation = continuation;
+    receiveMsg.Send(ipstackRef, myOID,
+                    Extra_Entry[entryReceiveContforPI], sizeof(receiveMsg));
+    return oSUCCESS;
+}
+
+void
+FtpPI::ReceiveCont(TCPEndpointReceiveMsg* receiveMsg)
+{
+    bool doReceive = false;
+
+    if (receiveMsg->error == TCP_CONNECTION_CLOSED) {
+        Close();
+        return;
+    }
+
+    if (receiveMsg->error != TCP_SUCCESS) {
+        OSYSLOG1((osyslogERROR, "%s : %s %d",
+                  "FtpPI::ReceiveCont()",
+                  "FAILED. receiveMsg->error", receiveMsg->error));
+        Close();
+        return;
+    }
+
+    connection.recvSize += receiveMsg->sizeMin;
+    
+    if (RequestComplete()) {
+        RequestProcess();
+    } else {
+        OSYSDEBUG(("FtpPI::Request not complete\n"));
+        doReceive = true;
+    }
+    
+    // receive some more
+    if (doReceive) {
+        if (connection.recvSize < FTP_BUFFER_SIZE) {
+            Receive();
+        } else {
+            Close();
+        }
+    }
+}
+
+OStatus
+FtpPI::Close()
+{
+    OSYSDEBUG(("FtpPI::Close()\n"));
+
+    if (connection.state == CONNECTION_CLOSED
+        || connection.state == CONNECTION_CLOSING) return oFAIL;
+
+    TCPEndpointCloseMsg closeMsg(connection.endpoint);
+    closeMsg.continuation = continuation;
+
+    closeMsg.Send(ipstackRef, myOID,
+                  Extra_Entry[entryCloseContforPI], sizeof(closeMsg));
+
+    connection.state = CONNECTION_CLOSING;
+    ftpDTP.Close();
+
+    return oSUCCESS;
+}
+
+void
+FtpPI::CloseCont(TCPEndpointCloseMsg* /*closeMsg*/) //CHANGE_ET unused variable
+{
+    OSYSDEBUG(("FtpPI::CloseCont()\n"));
+    
+    connection.state = CONNECTION_CLOSED;
+    Listen();
+}
+
+void
+FtpPI::ListenContforDTP(TCPEndpointListenMsg* listenMsg)
+{
+    if (listenMsg->error == TCP_SUCCESS) {
+        switch(ftpDTP.GetType()) {
+        case FTP_DATA_I:
+            Send(FTP_REPLY_OPEN_CONNECTION,
+                 "Binary data connection for %s.",
+                 ftpDTP.GetFilename());
+            break;
+
+        case FTP_DATA_A:
+            Send(FTP_REPLY_OPEN_CONNECTION,
+                 "ASCII data connection for %s.",
+                 ftpDTP.GetFilename());
+            break;
+        }
+    }
+    ftpDTP.ListenCont(listenMsg);
+    return;
+}
+
+void
+FtpPI::ConnectContforDTP(TCPEndpointConnectMsg* connectMsg)
+{
+    if (connectMsg->error == TCP_SUCCESS) {
+        switch(ftpDTP.GetType()) {
+        case FTP_DATA_I:
+            Send(FTP_REPLY_OPEN_CONNECTION,
+                 "Binary data connection for %s.",
+                 ftpDTP.GetFilename());
+            break;
+
+        case FTP_DATA_A:
+            Send(FTP_REPLY_OPEN_CONNECTION,
+                 "ASCII data connection for %s.",
+                 ftpDTP.GetFilename());
+            break;
+        }
+    }
+
+    ftpDTP.ConnectCont(connectMsg);
+    return;
+}
+
+void
+FtpPI::SendContforDTP(TCPEndpointSendMsg* sendMsg)
+{
+    if(ftpDTP.SendCont(sendMsg)) {
+        Send(FTP_REPLY_CLOSE_DATA, "Transfer complete.");
+        connection.recvSize = 0;
+        Receive();
+    } else if (ftpDTP.GetState() != CONNECTION_SENDING) {
+        Send(FTP_REPLY_TRANSFER_ABORT, "Transfer abort.");
+        connection.recvSize = 0;
+        Receive();
+    }
+}
+
+void
+FtpPI::ReceiveContforDTP(TCPEndpointReceiveMsg* receiveMsg)
+{
+    if (ftpDTP.ReceiveCont(receiveMsg)) {
+        Send(FTP_REPLY_CLOSE_DATA, "Transfer complete.");
+        connection.recvSize = 0;
+        Receive();
+    } else if (ftpDTP.GetState() != CONNECTION_RECEIVING) {
+        Send(FTP_REPLY_TRANSFER_ABORT, "Transfer abort.");
+        connection.recvSize = 0;
+        Receive();
+    }
+}
+
+void
+FtpPI::CloseContforDTP(TCPEndpointCloseMsg* closeMsg)
+{
+    ftpDTP.CloseCont(closeMsg);
+}
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/FtpPI.h ./aperios/TinyFTPD/FtpPI.h
--- ../Tekkotsu_2.3/aperios/TinyFTPD/FtpPI.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/FtpPI.h	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,65 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#ifndef _FtpPI_h_DEFINED
+#define _FtpPI_h_DEFINED
+
+#include <OPENR/OList.h>
+#include "TCPConnection.h"
+#include "FtpConfig.h"
+#include "FtpDTP.h"
+
+class FtpPI
+{
+public:
+    FtpPI();
+    virtual ~FtpPI() {}
+
+    OStatus Initialize(const OID& myoid, const antStackRef& ipstack,
+                       void* index, OList<Passwd, MAX_LOGIN> *pass);
+
+    void ListenCont  (TCPEndpointListenMsg*  listenMsg);
+    void SendCont    (TCPEndpointSendMsg*    sendMsg);
+    void ReceiveCont (TCPEndpointReceiveMsg* receiveMsg);
+    void CloseCont   (TCPEndpointCloseMsg*   closeMsg);
+
+    void ListenContforDTP (TCPEndpointListenMsg*  listenMsg);
+    void ConnectContforDTP(TCPEndpointConnectMsg* connectMsg);
+    void SendContforDTP   (TCPEndpointSendMsg*    sendMsg);
+    void ReceiveContforDTP(TCPEndpointReceiveMsg* receiveMsg);
+    void CloseContforDTP  (TCPEndpointCloseMsg*   closeMsg);
+
+    OStatus Close  ();
+
+private:
+    OStatus Listen ();
+    OStatus Send   (FTPReplyCode, char *format, ...);
+    OStatus Receive();
+
+    bool RequestComplete();
+    bool RequestProcess ();
+    bool CommandParser  (char **cmd, char **param);
+
+    OID myOID;
+    antStackRef ipstackRef;
+    void* continuation;
+    TCPConnection connection;
+    FTPLoginState state;
+    FtpDTP ftpDTP;
+    IPAddress ipaddr;
+
+    OList<Passwd, MAX_LOGIN> *passwd;
+
+		FtpPI(const FtpPI&); //CHANGE_ET copy constructor, don't call
+		FtpPI operator=(const FtpPI&); //CHANGE_ET assignment operator, don't call
+};
+#endif /* _FtpPI_h_DEFINED */
+
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/FtpRequest.cc ./aperios/TinyFTPD/FtpRequest.cc
--- ../Tekkotsu_2.3/aperios/TinyFTPD/FtpRequest.cc	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/FtpRequest.cc	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,428 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#include <OPENR/OPENRAPI.h>
+#include <OPENR/OSyslog.h>
+#include "FtpPI.h"
+#include "aperios/TinyFTPD/entry.h"
+
+bool
+FtpPI::RequestComplete()
+{
+    char* c = (char*)connection.recvData;
+
+    for (int i = 0; i < connection.recvSize - 1; i++) {
+        if ((c[i] == CR) && (c[i + 1] == LF)) {
+            c[i] = '\0';
+            return true;
+        }
+    }
+    
+    return false;
+}
+
+bool
+FtpPI::CommandParser(char **cmd, char **param)
+{
+    char *cur = (char *)connection.recvData;
+    *cmd = cur;
+
+    while (isalpha(*cur)) {
+        *cur = toupper(*cur);
+        cur++;
+    }
+
+    while (*cur == SP) {
+        *cur = '\0';
+        cur++;
+    }
+
+    *param = cur;
+    return true;
+}
+
+bool
+FtpPI::RequestProcess()
+{
+    //
+    // process all lines
+    //
+    char *cmd;
+    char *param;
+    CommandParser(&cmd, &param);
+    if (strlen(cmd) >= MAX_STRING_LENGTH) {
+        cmd[MAX_STRING_LENGTH - 1] = '\0';
+    }
+
+    if (strlen(param) >= MAX_STRING_LENGTH) {
+        param[MAX_STRING_LENGTH - 1] = '\0';
+    }
+
+    OSYSDEBUG(("FtpPI::RequestProcess() cmd %s : %s\n", cmd, param));
+
+    // process command
+    if (!strcmp(cmd, "USER")) {
+        state = FTP_LOGIN;
+        ftpDTP.SetUser(param);
+        Send(FTP_REPLY_NEED_PASSWD, "Password required for %s.", param);
+        connection.recvSize = 0;
+        Receive();
+    } else if (!strcmp(cmd, "PASS")) {
+        if (state == FTP_LOGIN) {
+            OList<Passwd, MAX_LOGIN>::Iterator iter = passwd->Begin();
+            OList<Passwd, MAX_LOGIN>::Iterator last = passwd->End();
+            while (iter != last) {
+                if (!strcmp((*iter).user, ftpDTP.GetUser())) {
+                    if (!strcmp((*iter).pass, param) ||
+                        !strcmp((*iter).pass, "*")) {
+                        ftpDTP.SetHome((*iter).home);
+                        state = FTP_GET_REQUEST;
+                        Send(FTP_REPLY_USER_LOGIN, "User %s logged in.",
+                             (*iter).user);
+                        connection.recvSize = 0;
+                        Receive();
+                    } else {
+                        state = FTP_NOT_LOGIN;
+                        Send(FTP_REPLY_NOT_LOGIN, "Login incorrect.");
+                        connection.recvSize = 0;
+                        Receive();
+                    }
+                    break;
+                }
+                ++iter;
+            }
+
+            if (iter == last) {
+                state = FTP_NOT_LOGIN;
+                Send(FTP_REPLY_NOT_LOGIN, "Login incorrect.");
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_BAD_SEQUENCE, "Login with USER first.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "TYPE")) {
+        switch(*param) {
+        case 'I':
+            ftpDTP.SetType(FTP_DATA_I);
+            Send(FTP_REPLY_COMMAND_OK, "TYPE set to %s.", param);
+            break;
+
+        case 'A':
+            ftpDTP.SetType(FTP_DATA_A);
+            Send(FTP_REPLY_COMMAND_OK, "TYPE set to %s.", param);
+            break;
+
+        default:
+            Send(FTP_REPLY_NOT_IMPLEMENT, "TYPE set to %s.", param);
+            break;
+        }
+        connection.recvSize = 0;
+        Receive();
+    } else if (!strcmp(cmd, "PORT")) {
+        if (state == FTP_GET_REQUEST) {
+            if (ftpDTP.SetPort(param)) {
+                Send(FTP_REPLY_COMMAND_OK, "PORT command successful.");
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "PASV")) {
+        if (state == FTP_GET_REQUEST) {
+            Port port = ftpDTP.SetIP(ipaddr);
+            if (port){
+                Send(FTP_REPLY_ENTER_PASSIVE,
+                     "Entering Passive Mode. %d,%d,%d,%d,%d,%d",
+                     (ipaddr.Address() & 0xff000000) >> 24,
+                     (ipaddr.Address() & 0x00ff0000) >> 16,
+                     (ipaddr.Address() & 0x0000ff00) >>  8,
+                     (ipaddr.Address() & 0x000000ff),
+                     (port & 0xff00) >>  8,
+                     (port & 0x00ff));
+                connection.recvSize = 0;
+                Receive();
+            }else {
+                Send(FTP_REPLY_NOT_AVAILABLE, "Passive Mode Fail.");
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "RETR")) {
+        if (state == FTP_GET_REQUEST) {
+            if (!ftpDTP.Retrieve(param)) {
+                Send(FTP_REPLY_NO_FILE, "No such file.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                return true;
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "STOR")) {
+        if (state == FTP_GET_REQUEST) {
+            if (!ftpDTP.Store(param)) {
+                Send(FTP_REPLY_NOT_TOKEN, "error.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                return true;
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "RNFR")) {
+        if (state == FTP_GET_REQUEST) {
+            if (ftpDTP.RenameFrom(param)) {
+                Send(FTP_REPLY_REQUESTED_FILE,
+                     "File exists, ready for destination name");
+                connection.recvSize = 0;
+                Receive();
+                return true;
+            } else {
+                Send(FTP_REPLY_NO_FILE, "%s : No such file or directory",
+                     param);
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "RNTO")) {
+        if (state == FTP_GET_REQUEST) {
+            char *tmp = ftpDTP.GetFilename();
+            if (*tmp) {
+                if (ftpDTP.RenameTo(param)) {
+                    Send(FTP_REPLY_FILE_ACTION_OK, "RNTO command successful.");
+                    connection.recvSize = 0;
+                    Receive();
+                } else {
+                    Send(FTP_REPLY_NO_FILE, "%s : No such file or directory",
+                         param);
+                    connection.recvSize = 0;
+                    Receive();
+                }
+            } else {
+                Send(FTP_REPLY_BAD_SEQUENCE, "Bad sequence of commands.");
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "LIST")) {
+        if (state == FTP_GET_REQUEST) {
+            if (!ftpDTP.List(param)) {
+                Send(FTP_REPLY_NOT_TAKEN, "Not taken.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                return true;
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "NLST")) {
+        if (state == FTP_GET_REQUEST) {
+            if (!ftpDTP.List(param)) {
+                Send(FTP_REPLY_NOT_TAKEN, "Not taken.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                return true;
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "CWD")) {
+        if (state == FTP_GET_REQUEST) {
+            if (ftpDTP.ChangeDir(param)) {
+                Send(FTP_REPLY_FILE_ACTION_OK, "CWD command successful.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                Send(FTP_REPLY_NO_FILE, "%s: No such file or directory.",
+                     param);
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "CDUP")) {
+        if (state == FTP_GET_REQUEST) {
+            if (ftpDTP.ChangeDir("../")) {
+                Send(FTP_REPLY_FILE_ACTION_OK, "CWD command successful.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                Send(FTP_REPLY_NO_FILE, "%s: No such file or directory.",
+                     param);
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "PWD")) {
+        if (state == FTP_GET_REQUEST) {
+            Send(FTP_REPLY_PATH_CREATED, "\"%s\" is current directory.",
+                 ftpDTP.GetDirectry());
+            connection.recvSize = 0;
+            Receive();
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "MKD")) {
+        if (state == FTP_GET_REQUEST) {
+             if (ftpDTP.MakeDir(param)) {
+                Send(FTP_REPLY_PATH_CREATED, "MKD command successful.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                Send(FTP_REPLY_NO_FILE, "MKD command Failed.");
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "RMD")) {
+        if (state == FTP_GET_REQUEST) {
+             if (ftpDTP.RemoveDir(param)) {
+                Send(FTP_REPLY_FILE_ACTION_OK, "RMD command successful.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                Send(FTP_REPLY_NO_FILE, "RMD command Failed.");
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "DELE")) {
+        if (state == FTP_GET_REQUEST) {
+            if (ftpDTP.Delete(param)) {
+                Send(FTP_REPLY_FILE_ACTION_OK, "DELE command successful.");
+                connection.recvSize = 0;
+                Receive();
+            } else {
+                Send(FTP_REPLY_NO_FILE, "DELE command Failed.");
+                connection.recvSize = 0;
+                Receive();
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "REBT")) {
+        if (state == FTP_GET_REQUEST) {
+            Send(FTP_REPLY_COMMAND_OK, "REBT command successful.");
+            Close();
+            OBootCondition bootCond(obcbBOOT_TIMER, 0, obcbttRELATIVE);
+            OStatus result = OPENR::Shutdown(bootCond);
+            if (result != oSUCCESS) {
+                OSYSLOG1((osyslogWARNING, "System shutdown... failed" ));
+                return false;
+            }
+        } else {
+            Send(FTP_REPLY_NOT_LOGIN, "Please login with USER and PASS.");
+            connection.recvSize = 0;
+            Receive();
+        }
+    } else if (!strcmp(cmd, "SYST")) {
+        sprintf((char *)connection.sendData,
+                "%03d Aperios system type.\r\n",
+                FTP_REPLY_SYSTEM_TYPE);
+        TCPEndpointSendMsg sendMsg(connection.endpoint,
+                                   connection.sendData,
+                                   strlen((char *)connection.sendData));
+            
+        sendMsg.continuation = continuation;
+        sendMsg.Send(ipstackRef,
+                     myOID, Extra_Entry[entrySendContforPI],
+                     sizeof(TCPEndpointSendMsg));
+        connection.recvSize = 0;
+        Receive();
+    } else if (!strcmp(cmd, "HELP")) {
+        sprintf((char *)connection.sendData,
+                "%03d-%s\r\n%s\r\n%s\r\n%s\r\n%s\r\n%s\r\n%03d %s\r\n",
+                FTP_REPLY_HELP_MESSAGE,
+                "The following commands are recognized:",
+                "   USER    PORT    RETR    MSND*   ALLO*   DELE    SITE*   XMKD*   CDUP",
+                "   PASS    PASV    STOR    MSOM*   REST*   CWD     STAT*   RMD     XCUP*",
+                "   ACCT*   TYPE    APPE*   MSAM*   RNFR*   XCWD*   HELP    XRMD*   STOU*",
+                "   REIN*   STRU*   MLFL*   MRSQ*   RNTO*   LIST    NOOP    PWD ",
+                "   QUIT    MODE*   MAIL*   MRCP*   ABOR*   NLST*   MKD     XPWD*   REBT",
+                FTP_REPLY_HELP_MESSAGE,
+                "(*'s => unimplemented)");
+        
+        TCPEndpointSendMsg sendMsg(connection.endpoint,
+                                   connection.sendData,
+                                   strlen((char *)connection.sendData));
+        
+        sendMsg.continuation = continuation;
+        sendMsg.Send(ipstackRef,
+                     myOID, Extra_Entry[entrySendContforPI],
+                     sizeof(TCPEndpointSendMsg));
+        connection.recvSize = 0;
+        Receive();
+    } else if (!strcmp(cmd, "NOOP")) {
+        Send(FTP_REPLY_COMMAND_OK, "NOOP command successful.");
+        Receive();
+    } else if (!strcmp(cmd, "QUIT")) {
+        Send(FTP_REPLY_SERVICE_CLOSE,
+             "Goodbye. Thanks for using the AIBO FTP Server.");
+        Close();
+    } else {
+        Send(FTP_REPLY_UNKNOWN_COMMAND,
+             "'%s %s': command not understood.", cmd, param);
+        connection.recvSize = 0;
+        Receive();
+    }
+
+    ftpDTP.ResetFilename();    
+    return true;
+}
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/TCPConnection.h ./aperios/TinyFTPD/TCPConnection.h
--- ../Tekkotsu_2.3/aperios/TinyFTPD/TCPConnection.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/TCPConnection.h	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,42 @@
+//
+// Copyright 2002 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#ifndef TCPConnection_h_DEFINED
+#define TCPConnection_h_DEFINED
+
+#include <ant.h>
+
+enum ConnectionState {
+    CONNECTION_CLOSED,
+    CONNECTION_CONNECTING,
+    CONNECTION_CONNECTED,
+    CONNECTION_LISTENING,
+    CONNECTION_SENDING,
+    CONNECTION_RECEIVING,
+    CONNECTION_CLOSING
+};
+
+struct TCPConnection {
+    antModuleRef     endpoint;
+    ConnectionState  state;
+
+    // send buffer
+    antSharedBuffer  sendBuffer;
+    byte*            sendData;
+    int              sendSize;
+    
+    // receive buffer
+    antSharedBuffer  recvBuffer;
+    byte*            recvData;
+    int              recvSize;
+};
+
+#endif // TCPConnection_h_DEFINED
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/TinyFTPD.cc ./aperios/TinyFTPD/TinyFTPD.cc
--- ../Tekkotsu_2.3/aperios/TinyFTPD/TinyFTPD.cc	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/TinyFTPD.cc	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,251 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#include <sys/stat.h>
+#include <OPENR/OSyslog.h>
+#include <EndpointTypes.h>
+#include <TCPEndpointMsg.h>
+#include "TinyFTPD.h"
+
+TinyFTPD::TinyFTPD() : passwd()
+{
+}
+
+OStatus
+TinyFTPD::DoInit(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
+{
+    OSYSDEBUG(("TinyFTPD::DoInit()\n"));
+    return oSUCCESS;
+}
+
+OStatus
+TinyFTPD::DoStart(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
+{
+    OSYSDEBUG(("TinyFTPD::DoStart()\n"));
+
+    ipstackRef = antStackRef("IPStack");
+
+    // Get Passwd
+    OStatus status = LoadPasswd();
+    if (oSUCCESS != status) {
+        OSYSLOG1((osyslogERROR, "TinyFTPD::Load Fail %d", status));
+        return oFAIL;
+    }
+
+    // initialize connection
+    for(int index = 0; index < FTP_CONNECTION_MAX; index++) {
+        ftpPI[index].Initialize(myOID_, ipstackRef, (void*)index, &passwd);
+    }
+
+    return oSUCCESS;
+}
+
+OStatus
+TinyFTPD::DoStop(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
+{
+    OSYSDEBUG(("TinyFTPD::DoStop()\n"));
+    for(int index = 0; index < FTP_CONNECTION_MAX; index++) {
+        ftpPI[index].Close();
+    }
+    return oSUCCESS;
+}
+
+OStatus
+TinyFTPD::DoDestroy(const OSystemEvent& /*event*/) //CHANGE_ET unused parameter
+{
+    OSYSDEBUG(("TinyFTPD::DoDestroy()\n"));
+    return oSUCCESS;
+}
+
+void
+TinyFTPD::ListenContforPI(ANTENVMSG msg)
+{
+    TCPEndpointListenMsg* listenMsg
+        = (TCPEndpointListenMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(listenMsg->continuation);
+
+    ftpPI[index].ListenCont(listenMsg);
+}
+
+void
+TinyFTPD::SendContforPI(ANTENVMSG msg)
+{
+    TCPEndpointSendMsg* sendMsg = (TCPEndpointSendMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(sendMsg->continuation);
+
+    ftpPI[index].SendCont(sendMsg);
+}
+
+void
+TinyFTPD::ReceiveContforPI(ANTENVMSG msg)
+{
+    TCPEndpointReceiveMsg* receiveMsg
+        = (TCPEndpointReceiveMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(receiveMsg->continuation);
+
+    ftpPI[index].ReceiveCont(receiveMsg);
+}
+
+void
+TinyFTPD::CloseContforPI(ANTENVMSG msg)
+{
+    TCPEndpointCloseMsg* closeMsg
+        = (TCPEndpointCloseMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(closeMsg->continuation);
+   
+    ftpPI[index].CloseCont(closeMsg);
+}
+
+void
+TinyFTPD::ListenContforDTP(ANTENVMSG msg)
+{
+    TCPEndpointListenMsg* listenMsg
+        = (TCPEndpointListenMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(listenMsg->continuation);
+
+    ftpPI[index].ListenContforDTP(listenMsg);
+}
+
+void
+TinyFTPD::ConnectContforDTP(ANTENVMSG msg)
+{
+    TCPEndpointConnectMsg* connectMsg
+        = (TCPEndpointConnectMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(connectMsg->continuation);
+
+    ftpPI[index].ConnectContforDTP(connectMsg);
+}
+
+void
+TinyFTPD::SendContforDTP(ANTENVMSG msg)
+{
+    TCPEndpointSendMsg* sendMsg
+        = (TCPEndpointSendMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(sendMsg->continuation);
+
+    ftpPI[index].SendContforDTP(sendMsg);
+}
+
+void
+TinyFTPD::ReceiveContforDTP(ANTENVMSG msg)
+{
+    TCPEndpointReceiveMsg* receiveMsg
+        = (TCPEndpointReceiveMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(receiveMsg->continuation);
+
+    ftpPI[index].ReceiveContforDTP(receiveMsg);
+}
+
+void
+TinyFTPD::CloseContforDTP(ANTENVMSG msg)
+{
+    TCPEndpointCloseMsg* closeMsg
+        = (TCPEndpointCloseMsg*)antEnvMsg::Receive(msg);
+    int index = (int)(closeMsg->continuation);
+
+    ftpPI[index].CloseContforDTP(closeMsg);
+}
+
+OStatus
+TinyFTPD::LoadPasswd()
+{
+    OSYSDEBUG(("TinyFTPD::LoadPasswd()\n"));
+
+    size_t bufsize;
+    char* buf;
+
+    OStatus result = Load(FTP_PASSWD_PATH, (byte**)&buf, &bufsize);
+    if (result != oSUCCESS) {
+        return result;
+    }
+
+    char* end = buf + bufsize;
+    char* cur = buf;
+    char* head = buf;
+    Passwd pass;
+
+    while (cur < end) {
+        if(*cur=='#') { // CHANGE_ET lets us put commented lines in the passwd file
+					while(*cur!='\n' && *cur!='\r' && cur<end)
+						cur++;
+					while((*cur=='\n' || *cur=='\r') && cur<end)
+						cur++;
+					continue;
+				}
+        while (isspace(*cur)) cur++;
+        head = cur;
+        while (!isspace(*cur) && (cur < end)) cur++;
+        if (cur >= end) break;
+        *cur++ = '\0';
+        strcpy(pass.user, head);
+
+        while (isspace(*cur)) cur++;
+        head = cur;
+        while (!isspace(*cur) && (cur < end)) cur++;
+        if (cur >= end) break;
+        *cur++ = '\0';
+        strcpy(pass.pass, head);
+
+        while (isspace(*cur)) cur++;
+        head = cur;
+        while (!isspace(*cur) && (cur < end)) cur++;
+        if (cur >= end) break;
+        *cur++ = '\0';
+        strcpy(pass.home, head);
+
+        if (passwd.PushBack(pass)) break;
+    }
+
+    DeleteRegion(buf);
+    return oSUCCESS;
+}
+
+OStatus
+TinyFTPD::Load(char* path, byte** data, size_t* size)
+{
+    FILE* fp;
+    byte* readBuf = 0;
+    int readBufSize;
+    
+    *data = 0;
+    *size = 0;
+
+    struct stat statbuf;
+    int ret = stat(path, &statbuf);
+    if (ret != 0) return oNOT_FOUND;
+
+    readBufSize = statbuf.st_size;
+
+    OSYSDEBUG(("%s size %d readBufSize %d\n",
+               path, statbuf.st_size, readBufSize));
+
+    readBuf = (byte*)malloc(readBufSize);
+    if (readBuf == NULL) return oNO_MEMORY;
+
+    fp = fopen(path, "r");
+    if (fp == 0) {
+        free(readBuf);
+        return oFAIL;
+    }
+
+    ret = fread(readBuf, 1, statbuf.st_size, fp);    
+    fclose(fp);
+
+    if (ret != statbuf.st_size) {
+        free(readBuf);
+        return oFAIL;
+    }
+    
+	*data = readBuf;
+	*size = statbuf.st_size;
+
+    return oSUCCESS;
+}
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/TinyFTPD.h ./aperios/TinyFTPD/TinyFTPD.h
--- ../Tekkotsu_2.3/aperios/TinyFTPD/TinyFTPD.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/TinyFTPD.h	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,60 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+#ifndef _TinyFTPD_h_DEFINED
+#define _TinyFTPD_h_DEFINED
+
+#include <OPENR/OObject.h>
+#include <OPENR/OSubject.h>
+#include <OPENR/OObserver.h>
+#include <OPENR/OList.h>
+#include "FtpConfig.h"
+#include "FtpPI.h"
+#include "aperios/TinyFTPD/def.h"
+
+class TinyFTPD : public OObject
+{
+public:
+    TinyFTPD();
+    virtual ~TinyFTPD() {}
+
+    OSubject*   subject[numOfSubject];
+    OObserver*  observer[numOfObserver];     
+
+    virtual OStatus DoInit   (const OSystemEvent& event);
+    virtual OStatus DoStart  (const OSystemEvent& event);
+    virtual OStatus DoStop   (const OSystemEvent& event);
+    virtual OStatus DoDestroy(const OSystemEvent& event);
+
+    void ListenContforPI  (ANTENVMSG msg);
+    void SendContforPI    (ANTENVMSG msg);
+    void ReceiveContforPI (ANTENVMSG msg);
+    void CloseContforPI   (ANTENVMSG msg);
+    void ListenContforDTP (ANTENVMSG msg);
+    void ConnectContforDTP(ANTENVMSG msg);
+    void SendContforDTP   (ANTENVMSG msg);
+    void ReceiveContforDTP(ANTENVMSG msg);
+    void CloseContforDTP  (ANTENVMSG msg);
+
+private:
+    OStatus LoadPasswd();
+    OStatus Load(char* path, byte** data, size_t* size);
+
+    antStackRef ipstackRef;
+    FtpPI ftpPI[FTP_CONNECTION_MAX];
+
+    OList<Passwd, MAX_LOGIN> passwd;
+
+		TinyFTPD(const TinyFTPD&); //CHANGE_ET copy constructor, don't call
+		TinyFTPD operator=(const TinyFTPD&); //CHANGE_ET assignment operator, don't call
+};
+
+#endif /* _TinyFTPD_h_DEFINED */
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/TinyFTPD.ocf ./aperios/TinyFTPD/TinyFTPD.ocf
--- ../Tekkotsu_2.3/aperios/TinyFTPD/TinyFTPD.ocf	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/TinyFTPD.ocf	Wed Jun  1 01:47:59 2005
@@ -0,0 +1 @@
+object TinyFTPD 3072 16386 128 cache notlb kernel
diff -urdN ../Tekkotsu_2.3/aperios/TinyFTPD/stub.cfg ./aperios/TinyFTPD/stub.cfg
--- ../Tekkotsu_2.3/aperios/TinyFTPD/stub.cfg	Wed Dec 31 19:00:00 1969
+++ ./aperios/TinyFTPD/stub.cfg	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,26 @@
+//
+// Copyright 2002,2003 Sony Corporation 
+//
+// Permission to use, copy, modify, and redistribute this software for
+// non-commercial use is hereby granted.
+//
+// This software is provided "as is" without warranty of any kind,
+// either expressed or implied, including but not limited to the
+// implied warranties of fitness for a particular purpose.
+//
+
+ObjectName : TinyFTPD
+NumOfOSubject   : 1
+NumOfOObserver  : 1
+Service : "TinyFTPD.DummySubject.DoNotConnect.S", null, null
+Service : "TinyFTPD.DummyObserver.DoNotConnect.O", null, null
+
+Extra : ListenContforPI()
+Extra : SendContforPI()
+Extra : ReceiveContforPI()
+Extra : CloseContforPI()
+Extra : ListenContforDTP()
+Extra : ConnectContforDTP()
+Extra : SendContforDTP()
+Extra : ReceiveContforDTP()
+Extra : CloseContforDTP()
diff -urdN ../Tekkotsu_2.3/aperios/bin/CVS/Entries ./aperios/bin/CVS/Entries
--- ../Tekkotsu_2.3/aperios/bin/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/bin/CVS/Entries	Wed Aug 10 11:03:21 2005
@@ -0,0 +1,4 @@
+/libpng-config/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/libpng12-config/1.2/Wed Jun  1 05:47:59 2005//Ttekkotsu-2_4
+/xml2-config/1.3/Tue Jun  7 23:22:31 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/bin/CVS/Repository ./aperios/bin/CVS/Repository
--- ../Tekkotsu_2.3/aperios/bin/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/bin/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/bin
diff -urdN ../Tekkotsu_2.3/aperios/bin/CVS/Root ./aperios/bin/CVS/Root
--- ../Tekkotsu_2.3/aperios/bin/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/bin/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/bin/CVS/Tag ./aperios/bin/CVS/Tag
--- ../Tekkotsu_2.3/aperios/bin/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/bin/CVS/Tag	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/bin/libpng-config ./aperios/bin/libpng-config
--- ../Tekkotsu_2.3/aperios/bin/libpng-config	Wed Dec 31 19:00:00 1969
+++ ./aperios/bin/libpng-config	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,122 @@
+#! /bin/sh
+
+# libpng-config
+# provides configuration info for libpng.
+
+# Copyright (C) 2002 Glenn Randers-Pehrson
+# For conditions of distribution and use, see copyright notice in png.h
+
+# Modeled after libxml-config.
+
+version=1.2.8
+prefix=""
+libdir=""
+libs=""
+I_opts=""
+L_opts=""
+R_opts=""
+cppflags=""
+ccopts=""
+ldopts=""
+
+prefix="/usr0/ejt/TekkotsuSim/aperios"
+I_opts="-I/usr0/ejt/TekkotsuSim/aperios/include/libpng12"
+L_opts="-L/usr0/ejt/TekkotsuSim/aperios/lib"
+R_opts="-Wl,-rpath,/usr0/ejt/TekkotsuSim/aperios/lib"
+libs="-lpng12 -lz -lm"
+
+usage()
+{
+    cat <<EOF
+Usage: libpng-config [OPTION] ...
+
+Known values for OPTION are:
+
+  --prefix        print libpng prefix
+  --libdir        print path to directory containing library
+  --libs          print library linking information
+  --ccopts        print compiler options
+  --cppflags      print pre-processor flags
+  --cflags        print preprocessor flags, I_opts, and compiler options
+  --I_opts        print "-I" include options
+  --L_opts        print linker "-L" flags for dynamic linking
+  --R_opts        print dynamic linker "-R" or "-rpath" flags
+  --ldopts        print linker options
+  --ldflags       print linker flags (ldopts, L_opts, R_opts, and libs)
+  --static        revise subsequent outputs for static linking
+  --help          print this help and exit
+  --version       print version information
+EOF
+
+    exit $1
+}
+
+if test $# -eq 0; then
+    usage 1
+fi
+
+while test $# -gt 0; do
+    case "$1" in
+
+    --prefix)
+        echo ${prefix}
+        ;;
+
+    --version)
+        echo ${version}
+        exit 0
+        ;;
+
+    --help)
+        usage 0
+        ;;
+
+    --ccopts)
+        echo ${ccopts}
+        ;;
+
+    --cppflags)
+        echo ${cppflags}
+        ;;
+
+    --cflags)
+        echo ${I_opts} ${cppflags} ${ccopts}
+        ;;
+
+    --libdir)
+        echo ${libdir}
+        ;;
+
+    --libs)
+        echo ${libs}
+        ;;
+
+    --I_opts)
+        echo ${I_opts}
+        ;;
+
+    --L_opts)
+        echo ${L_opts}
+        ;;
+
+    --R_opts)
+        echo ${R_opts}
+        ;;
+
+    --ldflags)
+        echo ${ldflags} ${L_opts} ${R_opts} ${libs}
+        ;;
+
+    --static)
+        R_opts=""
+        ;;
+
+    *)
+        usage
+        exit 1
+        ;;
+    esac
+    shift
+done
+
+exit 0
diff -urdN ../Tekkotsu_2.3/aperios/bin/libpng12-config ./aperios/bin/libpng12-config
--- ../Tekkotsu_2.3/aperios/bin/libpng12-config	Wed Dec 31 19:00:00 1969
+++ ./aperios/bin/libpng12-config	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,122 @@
+#! /bin/sh
+
+# libpng-config
+# provides configuration info for libpng.
+
+# Copyright (C) 2002 Glenn Randers-Pehrson
+# For conditions of distribution and use, see copyright notice in png.h
+
+# Modeled after libxml-config.
+
+version=1.2.8
+prefix=""
+libdir=""
+libs=""
+I_opts=""
+L_opts=""
+R_opts=""
+cppflags=""
+ccopts=""
+ldopts=""
+
+prefix="/usr0/ejt/TekkotsuSim/aperios"
+I_opts="-I/usr0/ejt/TekkotsuSim/aperios/include/libpng12"
+L_opts="-L/usr0/ejt/TekkotsuSim/aperios/lib"
+R_opts="-Wl,-rpath,/usr0/ejt/TekkotsuSim/aperios/lib"
+libs="-lpng12 -lz -lm"
+
+usage()
+{
+    cat <<EOF
+Usage: libpng-config [OPTION] ...
+
+Known values for OPTION are:
+
+  --prefix        print libpng prefix
+  --libdir        print path to directory containing library
+  --libs          print library linking information
+  --ccopts        print compiler options
+  --cppflags      print pre-processor flags
+  --cflags        print preprocessor flags, I_opts, and compiler options
+  --I_opts        print "-I" include options
+  --L_opts        print linker "-L" flags for dynamic linking
+  --R_opts        print dynamic linker "-R" or "-rpath" flags
+  --ldopts        print linker options
+  --ldflags       print linker flags (ldopts, L_opts, R_opts, and libs)
+  --static        revise subsequent outputs for static linking
+  --help          print this help and exit
+  --version       print version information
+EOF
+
+    exit $1
+}
+
+if test $# -eq 0; then
+    usage 1
+fi
+
+while test $# -gt 0; do
+    case "$1" in
+
+    --prefix)
+        echo ${prefix}
+        ;;
+
+    --version)
+        echo ${version}
+        exit 0
+        ;;
+
+    --help)
+        usage 0
+        ;;
+
+    --ccopts)
+        echo ${ccopts}
+        ;;
+
+    --cppflags)
+        echo ${cppflags}
+        ;;
+
+    --cflags)
+        echo ${I_opts} ${cppflags} ${ccopts}
+        ;;
+
+    --libdir)
+        echo ${libdir}
+        ;;
+
+    --libs)
+        echo ${libs}
+        ;;
+
+    --I_opts)
+        echo ${I_opts}
+        ;;
+
+    --L_opts)
+        echo ${L_opts}
+        ;;
+
+    --R_opts)
+        echo ${R_opts}
+        ;;
+
+    --ldflags)
+        echo ${ldflags} ${L_opts} ${R_opts} ${libs}
+        ;;
+
+    --static)
+        R_opts=""
+        ;;
+
+    *)
+        usage
+        exit 1
+        ;;
+    esac
+    shift
+done
+
+exit 0
diff -urdN ../Tekkotsu_2.3/aperios/bin/xml2-config ./aperios/bin/xml2-config
--- ../Tekkotsu_2.3/aperios/bin/xml2-config	Wed Dec 31 19:00:00 1969
+++ ./aperios/bin/xml2-config	Tue Jun  7 19:22:31 2005
@@ -0,0 +1,104 @@
+#! /bin/sh
+
+prefix=aperios
+exec_prefix=${prefix}
+includedir=${prefix}/include
+libdir=${exec_prefix}/lib
+
+usage()
+{
+    cat <<EOF
+Usage: xml2-config [OPTION]
+
+Known values for OPTION are:
+
+  --prefix=DIR		change libxml prefix [default $prefix]
+  --exec-prefix=DIR	change libxml exec prefix [default $exec_prefix]
+  --libs		print library linking information
+  --libtool-libs        print linking information for use with libtool
+  --cflags		print pre-processor and compiler flags
+  --modules		module support enabled
+  --help		display this help and exit
+  --version		output version information
+EOF
+
+    exit $1
+}
+
+if test $# -eq 0; then
+    usage 1
+fi
+
+cflags=false
+libs=false
+
+while test $# -gt 0; do
+    case "$1" in
+    -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
+    *) optarg= ;;
+    esac
+
+    case "$1" in
+    --prefix=*)
+	prefix=$optarg
+	includedir=$prefix/include
+	libdir=$prefix/lib
+	;;
+
+    --prefix)
+	echo $prefix
+	;;
+
+    --exec-prefix=*)
+      exec_prefix=$optarg
+      libdir=$exec_prefix/lib
+      ;;
+
+    --exec-prefix)
+      echo $exec_prefix
+      ;;
+
+    --version)
+	echo 2.6.19
+	exit 0
+	;;
+
+    --help)
+	usage 0
+	;;
+
+    --cflags)
+       	echo -I${includedir}/libxml2 
+       	;;
+
+    --libtool-libs)
+	echo ${libdir}/libxml2.la
+        ;;
+
+    --modules)
+       	echo 0
+       	;;
+
+    --libs)
+        if [ "`uname`" = "Linux" ]
+	then
+	    if [ "-L${libdir}" = "-L/usr/lib64" ]
+	    then
+		echo -lxml2 -L${aperios}/lib -lz   -lm  
+	    else
+		echo -L${libdir} -lxml2 -L${aperios}/lib -lz   -lm  
+	    fi
+	else
+	    echo -L${libdir} -lxml2 -L${aperios}/lib -lz   -lm  
+	fi
+       	;;
+
+    *)
+	usage
+	exit 1
+	;;
+    esac
+    shift
+done
+
+exit 0
diff -urdN ../Tekkotsu_2.3/aperios/build-jpeg ./aperios/build-jpeg
--- ../Tekkotsu_2.3/aperios/build-jpeg	Wed Dec 31 19:00:00 1969
+++ ./aperios/build-jpeg	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,107 @@
+#!/bin/sh
+
+usage="\
+$0 <jpeg-dir>
+    will cause jpeg to be built and installed into the
+    directory which contains this script.
+    
+    You will need to have OPENRSDK installed, either at
+    /usr/local/OPEN_R_SDK, or else set the OPENRSDK_ROOT
+    environment variable.
+    
+    The patch contained within this script was relative to
+    the jpeg-6b release, and may need to be tweaked
+    or replaced to support newer versions...
+";
+
+
+if [ $# -lt 1 -o "$1" == "-h" -o "$1" == "--help" ] ; then
+	printf "$usage";
+	exit 2;
+fi;
+
+pushd "`dirname \"$0\"`"
+TGT="`pwd`";
+popd;
+
+pushd "$1";
+
+echo "Configuring..."
+./configure --prefix="$TGT" --disable-shared mipsel-linux
+if [ "$?" -gt 0 ] ; then
+    echo "Configure failed.";
+    exit 1;
+fi;
+
+echo "Patching..."
+patch -p1 <<'EOF'
+diff -ru jpeg-6b/Makefile jpeg-6b-aperios/Makefile
+--- jpeg-6b/Makefile	Thu Mar 17 14:31:05 2005
++++ jpeg-6b-aperios/Makefile	Thu Mar 17 14:28:41 2005
+@@ -5,6 +5,9 @@
+ 
+ # Read installation instructions before saying "make" !!
+ 
++OPENRSDK_ROOT?=/usr/local/OPEN_R_SDK
++ORBIN=$(OPENRSDK_ROOT)/bin/mipsel-linux-
++
+ # For compiling with source and object files in different directories.
+ srcdir = .
+ 
+@@ -20,10 +23,10 @@
+ mandir = $(prefix)/man/man$(manext)
+ 
+ # The name of your C compiler:
+-CC= gcc
++CC= $(ORBIN)gcc
+ 
+ # You may need to adjust these cc options:
+-CFLAGS= -O2  -I$(srcdir)
++CFLAGS= -O3  -I$(srcdir) -frename-registers -fomit-frame-pointer -ffast-math
+ # Generally, we recommend defining any configuration symbols in jconfig.h,
+ # NOT via -D switches here.
+ # However, any special defines for ansi2knr.c may be included here:
+@@ -60,9 +63,9 @@
+ # directory creation command
+ MKDIR= mkdir
+ # library (.a) file creation command
+-AR= ar rc
++AR= $(ORBIN)ar rc
+ # second step in .a creation (use "touch" if not needed)
+-AR2= ranlib
++AR2= $(ORBIN)ranlib
+ # installation program
+ INSTALL= /usr/bin/install -c
+ INSTALL_PROGRAM= ${INSTALL}
+@@ -133,7 +136,7 @@
+ TROBJECTS= jpegtran.$(O) rdswitch.$(O) cdjpeg.$(O) transupp.$(O)
+ 
+ 
+-all:  libjpeg.$(A) cjpeg djpeg jpegtran rdjpgcom wrjpgcom
++all:  libjpeg.$(A) 
+ 
+ # Special compilation rules to support ansi2knr and libtool.
+ .SUFFIXES: .lo .la
+Only in jpeg-6b: config.log
+Only in jpeg-6b: config.status
+EOF
+if [ "$?" -gt 0 ] ; then
+    echo "Patching failed.";
+    exit 1;
+fi;
+
+
+echo "Making..."
+make;
+if [ "$?" -gt 0 ] ; then
+    echo "Make failed.";
+    exit 1;
+fi;
+
+echo "Installing..."
+make install-lib;
+if [ "$?" -gt 0 ] ; then
+    echo "Make install failed.";
+    exit 1;
+fi;
+
diff -urdN ../Tekkotsu_2.3/aperios/build-libpng ./aperios/build-libpng
--- ../Tekkotsu_2.3/aperios/build-libpng	Wed Dec 31 19:00:00 1969
+++ ./aperios/build-libpng	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,113 @@
+#!/bin/sh
+
+usage="\
+$0 <libpng-dir>
+    will cause libpng to be built and installed into the
+    directory which contains this script.
+    
+    You will need to have OPENRSDK installed, either at
+    /usr/local/OPEN_R_SDK, or else set the OPENRSDK_ROOT
+    environment variable.
+    
+    The patch contained within this script was relative to
+    the libpng2-1.2.8 release, and may need to be tweaked
+    or replaced to support newer versions...
+";
+
+
+if [ $# -lt 1 -o "$1" == "-h" -o "$1" == "--help" ] ; then
+	printf "$usage";
+	exit 2;
+fi;
+
+pushd "`dirname \"$0\"`"
+TGT="`pwd`";
+popd;
+
+pushd "$1";
+
+cp scripts/makefile.linux Makefile
+
+echo "Patching..."
+patch -p0 <<'EOF'
+--- scripts/makefile.linux	Thu Dec  2 19:14:31 2004
++++ Makefile	Thu Mar 17 13:37:59 2005
+@@ -8,18 +8,21 @@
+ PNGMIN = 1.2.8
+ PNGVER = $(PNGMAJ).$(PNGMIN)
+ 
+-CC=gcc
++OPENRSDK_ROOT?=/usr/local/OPEN_R_SDK
++ORBIN=$(OPENRSDK_ROOT)/bin/mipsel-linux-
++
++CC=$(ORBIN)gcc
+ 
+ # where "make install" puts libpng12.a, libpng12.so*,
+ # libpng12/png.h and libpng12/pngconf.h
+ # Prefix must be a full pathname.
+-prefix=/usr/local
++#prefix=Will be defined as an environment variable by build script
+ 
+ # Where the zlib library and include files are located.
+ #ZLIBLIB=/usr/local/lib
+ #ZLIBINC=/usr/local/include
+-ZLIBLIB=../zlib
+-ZLIBINC=../zlib
++ZLIBLIB=$(prefix)/lib
++ZLIBINC=$(prefix)/include
+ 
+ ALIGN=
+ # for i386:
+@@ -37,7 +40,7 @@
+ LDFLAGS=-L. -Wl,-rpath,. -L$(ZLIBLIB) -Wl,-rpath,$(ZLIBLIB) -lpng12 -lz -lm
+ LDFLAGS_A=-L$(ZLIBLIB) -Wl,-rpath,$(ZLIBLIB) libpng.a -lz -lm
+ 
+-RANLIB=ranlib
++RANLIB=$(ORBIN)ranlib
+ #RANLIB=echo
+ 
+ INCPATH=$(prefix)/include
+@@ -71,10 +74,10 @@
+ .c.pic.o:
+ 	$(CC) -c $(CFLAGS) -fPIC -o $@ $*.c
+ 
+-all: libpng.a $(LIBNAME).so pngtest pngtest-static libpng.pc libpng-config
++all: libpng.a libpng.pc libpng-config
+ 
+ libpng.a: $(OBJS)
+-	ar rc $@ $(OBJS)
++	$(ORBIN)ar rc $@ $(OBJS)
+ 	$(RANLIB) $@
+ 
+ libpng.pc:
+@@ -181,7 +184,7 @@
+ 	chmod 755 $(DB)/$(LIBNAME)-config
+ 	(cd $(DB); ln -sf $(LIBNAME)-config libpng-config)
+ 
+-install: install-static install-shared install-man install-config
++install: install-static install-man install-config
+ 
+ # If you installed in $(DESTDIR), test-installed won't work until you
+ # move the library to its final location.  Use test-dd to test it
+EOF
+if [ "$?" -gt 0 ] ; then
+    echo "Patching failed.";
+    exit 1;
+fi;
+
+export prefix="$TGT"
+
+echo "Making..."
+make;
+if [ "$?" -gt 0 ] ; then
+    echo "Make failed.";
+    exit 1;
+fi;
+
+echo "Installing..."
+make install;
+if [ "$?" -gt 0 ] ; then
+    echo "Make install failed.";
+    exit 1;
+fi;
+
diff -urdN ../Tekkotsu_2.3/aperios/build-libxml ./aperios/build-libxml
--- ../Tekkotsu_2.3/aperios/build-libxml	Wed Dec 31 19:00:00 1969
+++ ./aperios/build-libxml	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,220 @@
+#!/bin/sh
+
+usage="\
+$0 <libxml-dir>
+    will cause libxml to be built and installed into the
+    directory which contains this script.
+    
+    You will need to have OPENRSDK installed, either at
+    /usr/local/OPEN_R_SDK, or else set the OPENRSDK_ROOT
+    environment variable.
+    
+    The patch contained within this script was relative to
+    the libxml2-2.6.19 release, and may need to be tweaked
+    or replaced to support newer versions...
+";
+
+
+if [ $# -lt 1 -o "$1" == "-h" -o "$1" == "--help" ] ; then
+	printf "$usage";
+	exit 2;
+fi;
+
+pushd "`dirname \"$0\"`"
+TGT="`pwd`";
+popd;
+
+pushd "$1";
+
+echo "Patching..."
+patch -p1 <<'EOF'
+diff -ru libxml2-2.6.19/Makefile.in libxml2-2.6.19-aperios/Makefile.in
+--- libxml2-2.6.19/Makefile.in	Sat Apr  2 05:53:16 2005
++++ libxml2-2.6.19-aperios/Makefile.in	Thu Apr 28 15:39:31 2005
+@@ -41,12 +41,8 @@
+ POST_UNINSTALL = :
+ build_triplet = @build@
+ host_triplet = @host@
+-noinst_PROGRAMS = testSchemas$(EXEEXT) testRelax$(EXEEXT) \
+-	testSAX$(EXEEXT) testHTML$(EXEEXT) testXPath$(EXEEXT) \
+-	testURI$(EXEEXT) testThreads$(EXEEXT) testC14N$(EXEEXT) \
+-	testAutomata$(EXEEXT) testRegexp$(EXEEXT) testReader$(EXEEXT) \
+-	testapi$(EXEEXT) testModule$(EXEEXT)
+-bin_PROGRAMS = xmllint$(EXEEXT) xmlcatalog$(EXEEXT)
++noinst_PROGRAMS =
++bin_PROGRAMS =
+ DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \
+ 	$(srcdir)/Makefile.in $(srcdir)/config.h.in \
+ 	$(srcdir)/libxml-2.0-uninstalled.pc.in \
+diff -ru libxml2-2.6.19/configure libxml2-2.6.19-aperios/configure
+--- libxml2-2.6.19/configure	Sat Apr  2 04:05:32 2005
++++ libxml2-2.6.19-aperios/configure	Thu Apr 28 16:12:54 2005
+@@ -2454,11 +2454,11 @@
+   echo "$as_me: failed program was:" >&5
+ sed 's/^/| /' conftest.$ac_ext >&5
+ 
+-{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
+-See \`config.log' for more details." >&5
+-echo "$as_me: error: C compiler cannot create executables
+-See \`config.log' for more details." >&2;}
+-   { (exit 77); exit 77; }; }
++#{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
++#See \`config.log' for more details." >&5
++#echo "$as_me: error: C compiler cannot create executables
++#See \`config.log' for more details." >&2;}
++#   { (exit 77); exit 77; }; }
+ fi
+ 
+ ac_exeext=$ac_cv_exeext
+@@ -2526,12 +2526,12 @@
+     * ) break;;
+   esac
+ done
+-else
+-  { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
+-See \`config.log' for more details." >&5
+-echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
+-See \`config.log' for more details." >&2;}
+-   { (exit 1); exit 1; }; }
++#else
++#  { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
++#See \`config.log' for more details." >&5
++#echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
++#See \`config.log' for more details." >&2;}
++#   { (exit 1); exit 1; }; }
+ fi
+ 
+ rm -f conftest$ac_cv_exeext
+@@ -20466,6 +20466,7 @@
+ _ACEOF
+  echo "$as_me:$LINENO: checking for gzread in -lz" >&5
+ echo $ECHO_N "checking for gzread in -lz... $ECHO_C" >&6
++if false ; then
+ if test "${ac_cv_lib_z_gzread+set}" = set; then
+   echo $ECHO_N "(cached) $ECHO_C" >&6
+ else
+@@ -20526,8 +20527,11 @@
+       conftest$ac_exeext conftest.$ac_ext
+ LIBS=$ac_check_lib_save_LIBS
+ fi
++fi;
++  ac_cv_lib_z_gzread=yes;
+ echo "$as_me:$LINENO: result: $ac_cv_lib_z_gzread" >&5
+ echo "${ECHO_T}$ac_cv_lib_z_gzread" >&6
++echo "*************** LIBZ TEST ********" $ac_cv_lib_z_gzread
+ if test $ac_cv_lib_z_gzread = yes; then
+ 
+ 
+diff -ru libxml2-2.6.19/globals.c libxml2-2.6.19-aperios/globals.c
+--- libxml2-2.6.19/globals.c	Fri Apr  1 08:15:02 2005
++++ libxml2-2.6.19-aperios/globals.c	Thu Apr 28 15:37:43 2005
+@@ -496,11 +496,16 @@
+ 
+     xmlMutexLock(xmlThrDefMutex);
+ 
++		//they check this in SAX.c where the functions are defined
++		//but forgot to here, which causes an undefined function
++		//linker error if legacy is disabled
++#ifdef LIBXML_LEGACY_ENABLED
+ #ifdef LIBXML_DOCB_ENABLED
+     initdocbDefaultSAXHandler(&gs->docbDefaultSAXHandler);
+ #endif
+ #ifdef LIBXML_HTML_ENABLED
+     inithtmlDefaultSAXHandler(&gs->htmlDefaultSAXHandler);
++#endif
+ #endif
+ 
+     gs->oldXMLWDcompatibility = 0;
+diff -ru libxml2-2.6.19/xmlIO.c libxml2-2.6.19-aperios/xmlIO.c
+--- libxml2-2.6.19/xmlIO.c	Fri Apr  1 08:15:10 2005
++++ libxml2-2.6.19-aperios/xmlIO.c	Thu Apr 28 15:37:43 2005
+@@ -893,10 +893,11 @@
+     const char *path = NULL;
+     gzFile fd;
+ 
+-    if (!strcmp(filename, "-")) {
+-        fd = gzdopen(dup(0), "rb");
+-	return((void *) fd);
+-    }
++		//don't do stdout output on aperios
++    //if (!strcmp(filename, "-")) {
++		//fd = gzdopen(dup(0), "rb");
++		//return((void *) fd);
++		//}
+ 
+     if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file://localhost/", 17))
+ #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__)
+@@ -963,10 +964,11 @@
+     gzFile fd;
+ 
+     snprintf(mode, sizeof(mode), "wb%d", compression);
+-    if (!strcmp(filename, "-")) {
+-        fd = gzdopen(dup(1), mode);
+-	return((void *) fd);
+-    }
++		//don't do stdout output on aperios
++    //if (!strcmp(filename, "-")) {
++		//fd = gzdopen(dup(1), mode);
++		//return((void *) fd);
++		//}
+ 
+     if (!xmlStrncasecmp(BAD_CAST filename, BAD_CAST "file://localhost/", 17))
+ #if defined (_WIN32) || defined (__DJGPP__) && !defined(__CYGWIN__)
+@@ -3276,10 +3278,12 @@
+ 	else *cur = 0;
+ 	ret = xmlMemStrdup(dir);
+     } else {
+-        if (getcwd(dir, 1024) != NULL) {
+-	    dir[1023] = 0;
+-	    ret = xmlMemStrdup(dir);
+-	}
++			//apparently no getcwd in aperios... just assume it's always '/'
++			return strncpy(dir,"/",1023);
++			//if (getcwd(dir, 1024) != NULL) {
++	    //dir[1023] = 0;
++	    //ret = xmlMemStrdup(dir);
++			//}
+     }
+     return(ret);
+ }
+EOF
+if [ "$?" -gt 0 ] ; then
+    echo "Patching failed.";
+    exit 1;
+fi;
+
+if [ -z "$OPENRSDK_ROOT" ] ; then
+    OPENRSDK_ROOT=/usr/local/OPEN_R_SDK;
+fi;
+export PATH="$OPENRSDK_ROOT/bin:$PATH"
+
+echo "Configuring..."
+
+./configure --prefix="$TGT" --host=mipsel-linux --enable-static=yes --enable-shared=no \
+  --without-http --without-ftp --without-threads --without-python --with-zlib="$TGT" \
+  --without-c14n --without-catalog --without-debug --without-docbook --without-pattern \
+	--with-html --without-legacy \
+  --with-push --with-reader --without-regexps --without-sax1 --without-schemas \
+  --with-valid --with-writer --with-xinclude --with-xpath --with-xptr --without-modules  ;
+if [ "$?" -gt 0 ] ; then
+    echo "Configure failed.";
+    exit 1;
+fi;
+
+printf "all:;\ninstall:;\nclean:;\n" > doc/Makefile
+printf "all:;\ninstall:;\nclean:;\n" > example/Makefile
+
+echo "Making..."
+make;
+if [ "$?" -gt 0 ] ; then
+    echo "Make failed.";
+    exit 1;
+fi;
+
+echo "Installing..."
+make install;
+if [ "$?" -gt 0 ] ; then
+    echo "Make install failed.";
+    exit 1;
+fi;
+
diff -urdN ../Tekkotsu_2.3/aperios/build-zlib ./aperios/build-zlib
--- ../Tekkotsu_2.3/aperios/build-zlib	Wed Dec 31 19:00:00 1969
+++ ./aperios/build-zlib	Wed Jun  1 01:47:59 2005
@@ -0,0 +1,102 @@
+#!/bin/sh
+
+usage="\
+$0 <zlib-dir>
+    will cause libzlib to be built and installed into the
+    directory which contains this script.
+    
+    You will need to have OPENRSDK installed, either at
+    /usr/local/OPEN_R_SDK, or else set the OPENRSDK_ROOT
+    environment variable.
+    
+    The patch contained within this script was relative to
+    the zlib-1.2.2 release, and may need to be tweaked
+    or replaced to support newer versions...
+";
+
+
+if [ $# -lt 1 -o "$1" == "-h" -o "$1" == "--help" ] ; then
+	printf "$usage";
+	exit 2;
+fi;
+
+pushd "`dirname \"$0\"`"
+TGT="`pwd`";
+popd;
+
+pushd "$1";
+
+echo "Configuring..."
+./configure --prefix="$TGT"
+if [ "$?" -gt 0 ] ; then
+    echo "Configure failed.";
+    exit 1;
+fi;
+
+echo "Patching..."
+patch -p1 <<'EOF'
+diff -u zlib-1.2.2/Makefile zlib-1.2.2-aperios/Makefile
+--- zlib-1.2.2/Makefile	Tue Apr 26 15:44:19 2005
++++ zlib-1.2.2-aperios/Makefile	Tue Apr 26 15:41:09 2005
+@@ -16,7 +16,9 @@
+ # To install in $HOME instead of /usr/local, use:
+ #    make install prefix=$HOME
+ 
+-CC=gcc
++OPENRSDK_ROOT?=/usr/local/OPEN_R_SDK
++ORBIN=$(OPENRSDK_ROOT)/bin/mipsel-linux-
++CC=$(ORBIN)gcc
+ 
+ CFLAGS=-O3 -DUSE_MMAP
+ #CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+@@ -25,16 +27,16 @@
+ #           -Wstrict-prototypes -Wmissing-prototypes
+ 
+ LDFLAGS=-L. libz.a
+-LDSHARED=gcc
+-CPP=gcc -E
++LDSHARED=$(ORBIN)gcc
++CPP=$(ORBIN)gcc -E
+ 
+ LIBS=libz.a
+ SHAREDLIB=libz.so
+ SHAREDLIBV=libz.so.1.2.2
+ SHAREDLIBM=libz.so.1
+ 
+-AR=ar rc
+-RANLIB=ranlib
++AR=$(ORBIN)ar rc
++RANLIB=$(ORBIN)ranlib
+ TAR=tar
+ SHELL=/bin/sh
+ EXE=
+@@ -54,7 +56,7 @@
+ 
+ TEST_OBJS = example.o minigzip.o
+ 
+-all: example$(EXE) minigzip$(EXE)
++all: $(LIBS)
+ 
+ check: test
+ test: all
+EOF
+if [ "$?" -gt 0 ] ; then
+    echo "Patching failed.";
+    exit 1;
+fi;
+
+
+echo "Making..."
+make;
+if [ "$?" -gt 0 ] ; then
+    echo "Make failed.";
+    exit 1;
+fi;
+
+echo "Installing..."
+make install;
+if [ "$?" -gt 0 ] ; then
+    echo "Make install failed.";
+    exit 1;
+fi;
+
diff -urdN ../Tekkotsu_2.3/aperios/include/CVS/Entries ./aperios/include/CVS/Entries
--- ../Tekkotsu_2.3/aperios/include/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,11 @@
+/jconfig.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/jerror.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/jmorecfg.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/jpeglib.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/png.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/pngconf.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/zconf.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/zlib.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+D/libpng////
+D/libpng12////
+D/libxml2////
diff -urdN ../Tekkotsu_2.3/aperios/include/CVS/Repository ./aperios/include/CVS/Repository
--- ../Tekkotsu_2.3/aperios/include/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/CVS/Repository	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/include
diff -urdN ../Tekkotsu_2.3/aperios/include/CVS/Root ./aperios/include/CVS/Root
--- ../Tekkotsu_2.3/aperios/include/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/CVS/Root	Wed Aug 10 11:03:21 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/include/CVS/Tag ./aperios/include/CVS/Tag
--- ../Tekkotsu_2.3/aperios/include/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/CVS/Tag	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/include/jconfig.h ./aperios/include/jconfig.h
--- ../Tekkotsu_2.3/aperios/include/jconfig.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/jconfig.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,45 @@
+/* jconfig.h.  Generated automatically by configure.  */
+/* jconfig.cfg --- source file edited by configure script */
+/* see jconfig.doc for explanations */
+
+#define HAVE_PROTOTYPES 
+#define HAVE_UNSIGNED_CHAR 
+#define HAVE_UNSIGNED_SHORT 
+#undef void
+#undef const
+#undef CHAR_IS_UNSIGNED
+#define HAVE_STDDEF_H 
+#define HAVE_STDLIB_H 
+#undef NEED_BSD_STRINGS
+#undef NEED_SYS_TYPES_H
+#undef NEED_FAR_POINTERS
+#undef NEED_SHORT_EXTERNAL_NAMES
+/* Define this if you get warnings about undefined structures. */
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifdef JPEG_INTERNALS
+
+#undef RIGHT_SHIFT_IS_UNSIGNED
+#define INLINE __inline__
+/* These are for configuring the JPEG memory manager. */
+#undef DEFAULT_MAX_MEM
+#undef NO_MKTEMP
+
+#endif /* JPEG_INTERNALS */
+
+#ifdef JPEG_CJPEG_DJPEG
+
+#define BMP_SUPPORTED		/* BMP image file format */
+#define GIF_SUPPORTED		/* GIF image file format */
+#define PPM_SUPPORTED		/* PBMPLUS PPM/PGM image file format */
+#undef RLE_SUPPORTED		/* Utah RLE image file format */
+#define TARGA_SUPPORTED		/* Targa image file format */
+
+#undef TWO_FILE_COMMANDLINE
+#undef NEED_SIGNAL_CATCHER
+#undef DONT_USE_B_MODE
+
+/* Define this if you want percent-done progress reports from cjpeg/djpeg. */
+#undef PROGRESS_REPORT
+
+#endif /* JPEG_CJPEG_DJPEG */
diff -urdN ../Tekkotsu_2.3/aperios/include/jerror.h ./aperios/include/jerror.h
--- ../Tekkotsu_2.3/aperios/include/jerror.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/jerror.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,291 @@
+/*
+ * jerror.h
+ *
+ * Copyright (C) 1994-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the error and message codes for the JPEG library.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ * A set of error-reporting macros are defined too.  Some applications using
+ * the JPEG library may wish to include this file to get the error codes
+ * and/or the macros.
+ */
+
+/*
+ * To define the enum list of message codes, include this file without
+ * defining macro JMESSAGE.  To create a message string table, include it
+ * again with a suitable JMESSAGE definition (see jerror.c for an example).
+ */
+#ifndef JMESSAGE
+#ifndef JERROR_H
+/* First time through, define the enum list */
+#define JMAKE_ENUM_LIST
+#else
+/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
+#define JMESSAGE(code,string)
+#endif /* JERROR_H */
+#endif /* JMESSAGE */
+
+#ifdef JMAKE_ENUM_LIST
+
+typedef enum {
+
+#define JMESSAGE(code,string)	code ,
+
+#endif /* JMAKE_ENUM_LIST */
+
+JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
+
+/* For maintenance convenience, list is alphabetical by message code name */
+JMESSAGE(JERR_ARITH_NOTIMPL,
+	 "Sorry, there are legal restrictions on arithmetic coding")
+JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
+JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
+JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
+JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
+JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
+JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
+JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
+JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
+JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
+JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
+JMESSAGE(JERR_BAD_LIB_VERSION,
+	 "Wrong JPEG library version: library is %d, caller expects %d")
+JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
+JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
+JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
+JMESSAGE(JERR_BAD_PROGRESSION,
+	 "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
+JMESSAGE(JERR_BAD_PROG_SCRIPT,
+	 "Invalid progressive parameters at scan script entry %d")
+JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
+JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
+JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
+JMESSAGE(JERR_BAD_STRUCT_SIZE,
+	 "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
+JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
+JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
+JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
+JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
+JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
+JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
+JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
+JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
+JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
+JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
+JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
+JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
+JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
+JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
+JMESSAGE(JERR_FILE_READ, "Input file read error")
+JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
+JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
+JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
+JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
+JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
+JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
+JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
+JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
+	 "Cannot transcode due to multiple use of quantization table %d")
+JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
+JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
+JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
+JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
+JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
+JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
+JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
+JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
+JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
+JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
+JMESSAGE(JERR_QUANT_COMPONENTS,
+	 "Cannot quantize more than %d color components")
+JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
+JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
+JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
+JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
+JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
+JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
+JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
+JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
+JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
+JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
+JMESSAGE(JERR_TFILE_WRITE,
+	 "Write failed on temporary file --- out of disk space?")
+JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
+JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
+JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
+JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
+JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
+JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
+JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
+JMESSAGE(JMSG_VERSION, JVERSION)
+JMESSAGE(JTRC_16BIT_TABLES,
+	 "Caution: quantization tables are too coarse for baseline JPEG")
+JMESSAGE(JTRC_ADOBE,
+	 "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
+JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
+JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
+JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
+JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
+JMESSAGE(JTRC_DQT, "Define Quantization Table %d  precision %d")
+JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
+JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
+JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
+JMESSAGE(JTRC_EOI, "End Of Image")
+JMESSAGE(JTRC_HUFFBITS, "        %3d %3d %3d %3d %3d %3d %3d %3d")
+JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d  %d")
+JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
+	 "Warning: thumbnail image size does not match data length %u")
+JMESSAGE(JTRC_JFIF_EXTENSION,
+	 "JFIF extension marker: type 0x%02x, length %u")
+JMESSAGE(JTRC_JFIF_THUMBNAIL, "    with %d x %d thumbnail image")
+JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
+JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
+JMESSAGE(JTRC_QUANTVALS, "        %4u %4u %4u %4u %4u %4u %4u %4u")
+JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
+JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
+JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
+JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
+JMESSAGE(JTRC_RST, "RST%d")
+JMESSAGE(JTRC_SMOOTH_NOTIMPL,
+	 "Smoothing not supported with nonstandard sampling ratios")
+JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
+JMESSAGE(JTRC_SOF_COMPONENT, "    Component %d: %dhx%dv q=%d")
+JMESSAGE(JTRC_SOI, "Start of Image")
+JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
+JMESSAGE(JTRC_SOS_COMPONENT, "    Component %d: dc=%d ac=%d")
+JMESSAGE(JTRC_SOS_PARAMS, "  Ss=%d, Se=%d, Ah=%d, Al=%d")
+JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
+JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
+JMESSAGE(JTRC_THUMB_JPEG,
+	 "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
+JMESSAGE(JTRC_THUMB_PALETTE,
+	 "JFIF extension marker: palette thumbnail image, length %u")
+JMESSAGE(JTRC_THUMB_RGB,
+	 "JFIF extension marker: RGB thumbnail image, length %u")
+JMESSAGE(JTRC_UNKNOWN_IDS,
+	 "Unrecognized component IDs %d %d %d, assuming YCbCr")
+JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
+JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
+JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
+JMESSAGE(JWRN_BOGUS_PROGRESSION,
+	 "Inconsistent progression sequence for component %d coefficient %d")
+JMESSAGE(JWRN_EXTRANEOUS_DATA,
+	 "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
+JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
+JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
+JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
+JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
+JMESSAGE(JWRN_MUST_RESYNC,
+	 "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
+JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
+JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
+
+#ifdef JMAKE_ENUM_LIST
+
+  JMSG_LASTMSGCODE
+} J_MESSAGE_CODE;
+
+#undef JMAKE_ENUM_LIST
+#endif /* JMAKE_ENUM_LIST */
+
+/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
+#undef JMESSAGE
+
+
+#ifndef JERROR_H
+#define JERROR_H
+
+/* Macros to simplify using the error and trace message stuff */
+/* The first parameter is either type of cinfo pointer */
+
+/* Fatal errors (print message and exit) */
+#define ERREXIT(cinfo,code)  \
+  ((cinfo)->err->msg_code = (code), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT1(cinfo,code,p1)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT2(cinfo,code,p1,p2)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT3(cinfo,code,p1,p2,p3)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (cinfo)->err->msg_parm.i[2] = (p3), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXIT4(cinfo,code,p1,p2,p3,p4)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (cinfo)->err->msg_parm.i[2] = (p3), \
+   (cinfo)->err->msg_parm.i[3] = (p4), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+#define ERREXITS(cinfo,code,str)  \
+  ((cinfo)->err->msg_code = (code), \
+   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+   (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
+
+#define MAKESTMT(stuff)		do { stuff } while (0)
+
+/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
+#define WARNMS(cinfo,code)  \
+  ((cinfo)->err->msg_code = (code), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS1(cinfo,code,p1)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+#define WARNMS2(cinfo,code,p1,p2)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
+
+/* Informational/debugging messages */
+#define TRACEMS(cinfo,lvl,code)  \
+  ((cinfo)->err->msg_code = (code), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS1(cinfo,lvl,code,p1)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS2(cinfo,lvl,code,p1,p2)  \
+  ((cinfo)->err->msg_code = (code), \
+   (cinfo)->err->msg_parm.i[0] = (p1), \
+   (cinfo)->err->msg_parm.i[1] = (p2), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+#define TRACEMS3(cinfo,lvl,code,p1,p2,p3)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+	   _mp[4] = (p5); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8)  \
+  MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
+	   _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
+	   _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
+	   (cinfo)->err->msg_code = (code); \
+	   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
+#define TRACEMSS(cinfo,lvl,code,str)  \
+  ((cinfo)->err->msg_code = (code), \
+   strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
+   (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
+
+#endif /* JERROR_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/jmorecfg.h ./aperios/include/jmorecfg.h
--- ../Tekkotsu_2.3/aperios/include/jmorecfg.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/jmorecfg.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,363 @@
+/*
+ * jmorecfg.h
+ *
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file contains additional configuration options that customize the
+ * JPEG software for special applications or support machine-dependent
+ * optimizations.  Most users will not need to touch this file.
+ */
+
+
+/*
+ * Define BITS_IN_JSAMPLE as either
+ *   8   for 8-bit sample values (the usual setting)
+ *   12  for 12-bit sample values
+ * Only 8 and 12 are legal data precisions for lossy JPEG according to the
+ * JPEG standard, and the IJG code does not support anything else!
+ * We do not support run-time selection of data precision, sorry.
+ */
+
+#define BITS_IN_JSAMPLE  8	/* use 8 or 12 */
+
+
+/*
+ * Maximum number of components (color channels) allowed in JPEG image.
+ * To meet the letter of the JPEG spec, set this to 255.  However, darn
+ * few applications need more than 4 channels (maybe 5 for CMYK + alpha
+ * mask).  We recommend 10 as a reasonable compromise; use 4 if you are
+ * really short on memory.  (Each allowed component costs a hundred or so
+ * bytes of storage, whether actually used in an image or not.)
+ */
+
+#define MAX_COMPONENTS  10	/* maximum number of image components */
+
+
+/*
+ * Basic data types.
+ * You may need to change these if you have a machine with unusual data
+ * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
+ * or "long" not 32 bits.  We don't care whether "int" is 16 or 32 bits,
+ * but it had better be at least 16.
+ */
+
+/* Representation of a single sample (pixel element value).
+ * We frequently allocate large arrays of these, so it's important to keep
+ * them small.  But if you have memory to burn and access to char or short
+ * arrays is very slow on your hardware, you might want to change these.
+ */
+
+#if BITS_IN_JSAMPLE == 8
+/* JSAMPLE should be the smallest type that will hold the values 0..255.
+ * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JSAMPLE;
+#define GETJSAMPLE(value)  ((int) (value))
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JSAMPLE;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJSAMPLE(value)  ((int) (value))
+#else
+#define GETJSAMPLE(value)  ((int) (value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+#define MAXJSAMPLE	255
+#define CENTERJSAMPLE	128
+
+#endif /* BITS_IN_JSAMPLE == 8 */
+
+
+#if BITS_IN_JSAMPLE == 12
+/* JSAMPLE should be the smallest type that will hold the values 0..4095.
+ * On nearly all machines "short" will do nicely.
+ */
+
+typedef short JSAMPLE;
+#define GETJSAMPLE(value)  ((int) (value))
+
+#define MAXJSAMPLE	4095
+#define CENTERJSAMPLE	2048
+
+#endif /* BITS_IN_JSAMPLE == 12 */
+
+
+/* Representation of a DCT frequency coefficient.
+ * This should be a signed value of at least 16 bits; "short" is usually OK.
+ * Again, we allocate large arrays of these, but you can change to int
+ * if you have memory to burn and "short" is really slow.
+ */
+
+typedef short JCOEF;
+
+
+/* Compressed datastreams are represented as arrays of JOCTET.
+ * These must be EXACTLY 8 bits wide, at least once they are written to
+ * external storage.  Note that when using the stdio data source/destination
+ * managers, this is also the data type passed to fread/fwrite.
+ */
+
+#ifdef HAVE_UNSIGNED_CHAR
+
+typedef unsigned char JOCTET;
+#define GETJOCTET(value)  (value)
+
+#else /* not HAVE_UNSIGNED_CHAR */
+
+typedef char JOCTET;
+#ifdef CHAR_IS_UNSIGNED
+#define GETJOCTET(value)  (value)
+#else
+#define GETJOCTET(value)  ((value) & 0xFF)
+#endif /* CHAR_IS_UNSIGNED */
+
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+/* These typedefs are used for various table entries and so forth.
+ * They must be at least as wide as specified; but making them too big
+ * won't cost a huge amount of memory, so we don't provide special
+ * extraction code like we did for JSAMPLE.  (In other words, these
+ * typedefs live at a different point on the speed/space tradeoff curve.)
+ */
+
+/* UINT8 must hold at least the values 0..255. */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char UINT8;
+#else /* not HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char UINT8;
+#else /* not CHAR_IS_UNSIGNED */
+typedef short UINT8;
+#endif /* CHAR_IS_UNSIGNED */
+#endif /* HAVE_UNSIGNED_CHAR */
+
+/* UINT16 must hold at least the values 0..65535. */
+
+#ifdef HAVE_UNSIGNED_SHORT
+typedef unsigned short UINT16;
+#else /* not HAVE_UNSIGNED_SHORT */
+typedef unsigned int UINT16;
+#endif /* HAVE_UNSIGNED_SHORT */
+
+/* INT16 must hold at least the values -32768..32767. */
+
+#ifndef XMD_H			/* X11/xmd.h correctly defines INT16 */
+typedef short INT16;
+#endif
+
+/* INT32 must hold at least signed 32-bit values. */
+
+#ifndef XMD_H			/* X11/xmd.h correctly defines INT32 */
+typedef long INT32;
+#endif
+
+/* Datatype used for image dimensions.  The JPEG standard only supports
+ * images up to 64K*64K due to 16-bit fields in SOF markers.  Therefore
+ * "unsigned int" is sufficient on all machines.  However, if you need to
+ * handle larger images and you don't mind deviating from the spec, you
+ * can change this datatype.
+ */
+
+typedef unsigned int JDIMENSION;
+
+#define JPEG_MAX_DIMENSION  65500L  /* a tad under 64K to prevent overflows */
+
+
+/* These macros are used in all function definitions and extern declarations.
+ * You could modify them if you need to change function linkage conventions;
+ * in particular, you'll need to do that to make the library a Windows DLL.
+ * Another application is to make all functions global for use with debuggers
+ * or code profilers that require it.
+ */
+
+/* a function called through method pointers: */
+#define METHODDEF(type)		static type
+/* a function used only in its module: */
+#define LOCAL(type)		static type
+/* a function referenced thru EXTERNs: */
+#define GLOBAL(type)		type
+/* a reference to a GLOBAL function: */
+#define EXTERN(type)		extern type
+
+
+/* This macro is used to declare a "method", that is, a function pointer.
+ * We want to supply prototype parameters if the compiler can cope.
+ * Note that the arglist parameter must be parenthesized!
+ * Again, you can customize this if you need special linkage keywords.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JMETHOD(type,methodname,arglist)  type (*methodname) arglist
+#else
+#define JMETHOD(type,methodname,arglist)  type (*methodname) ()
+#endif
+
+
+/* Here is the pseudo-keyword for declaring pointers that must be "far"
+ * on 80x86 machines.  Most of the specialized coding for 80x86 is handled
+ * by just saying "FAR *" where such a pointer is needed.  In a few places
+ * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
+ */
+
+#ifdef NEED_FAR_POINTERS
+#define FAR  far
+#else
+#define FAR
+#endif
+
+
+/*
+ * On a few systems, type boolean and/or its values FALSE, TRUE may appear
+ * in standard header files.  Or you may have conflicts with application-
+ * specific header files that you want to include together with these files.
+ * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
+ */
+
+#ifndef HAVE_BOOLEAN
+typedef int boolean;
+#endif
+#ifndef FALSE			/* in case these macros already exist */
+#define FALSE	0		/* values of boolean */
+#endif
+#ifndef TRUE
+#define TRUE	1
+#endif
+
+
+/*
+ * The remaining options affect code selection within the JPEG library,
+ * but they don't need to be visible to most applications using the library.
+ * To minimize application namespace pollution, the symbols won't be
+ * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
+ */
+
+#ifdef JPEG_INTERNALS
+#define JPEG_INTERNAL_OPTIONS
+#endif
+
+#ifdef JPEG_INTERNAL_OPTIONS
+
+
+/*
+ * These defines indicate whether to include various optional functions.
+ * Undefining some of these symbols will produce a smaller but less capable
+ * library.  Note that you can leave certain source files out of the
+ * compilation/linking process if you've #undef'd the corresponding symbols.
+ * (You may HAVE to do that if your compiler doesn't like null source files.)
+ */
+
+/* Arithmetic coding is unsupported for legal reasons.  Complaints to IBM. */
+
+/* Capability options common to encoder and decoder: */
+
+#define DCT_ISLOW_SUPPORTED	/* slow but accurate integer algorithm */
+#define DCT_IFAST_SUPPORTED	/* faster, less accurate integer method */
+#define DCT_FLOAT_SUPPORTED	/* floating-point: accurate, fast on fast HW */
+
+/* Encoder capability options: */
+
+#undef  C_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
+#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define C_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
+#define ENTROPY_OPT_SUPPORTED	    /* Optimization of entropy coding parms? */
+/* Note: if you selected 12-bit data precision, it is dangerous to turn off
+ * ENTROPY_OPT_SUPPORTED.  The standard Huffman tables are only good for 8-bit
+ * precision, so jchuff.c normally uses entropy optimization to compute
+ * usable tables for higher precision.  If you don't want to do optimization,
+ * you'll have to supply different default Huffman tables.
+ * The exact same statements apply for progressive JPEG: the default tables
+ * don't work for progressive mode.  (This may get fixed, however.)
+ */
+#define INPUT_SMOOTHING_SUPPORTED   /* Input image smoothing option? */
+
+/* Decoder capability options: */
+
+#undef  D_ARITH_CODING_SUPPORTED    /* Arithmetic coding back end? */
+#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
+#define D_PROGRESSIVE_SUPPORTED	    /* Progressive JPEG? (Requires MULTISCAN)*/
+#define SAVE_MARKERS_SUPPORTED	    /* jpeg_save_markers() needed? */
+#define BLOCK_SMOOTHING_SUPPORTED   /* Block smoothing? (Progressive only) */
+#define IDCT_SCALING_SUPPORTED	    /* Output rescaling via IDCT? */
+#undef  UPSAMPLE_SCALING_SUPPORTED  /* Output rescaling at upsample stage? */
+#define UPSAMPLE_MERGING_SUPPORTED  /* Fast path for sloppy upsampling? */
+#define QUANT_1PASS_SUPPORTED	    /* 1-pass color quantization? */
+#define QUANT_2PASS_SUPPORTED	    /* 2-pass color quantization? */
+
+/* more capability options later, no doubt */
+
+
+/*
+ * Ordering of RGB data in scanlines passed to or from the application.
+ * If your application wants to deal with data in the order B,G,R, just
+ * change these macros.  You can also deal with formats such as R,G,B,X
+ * (one extra byte per pixel) by changing RGB_PIXELSIZE.  Note that changing
+ * the offsets will also change the order in which colormap data is organized.
+ * RESTRICTIONS:
+ * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
+ * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
+ *    useful if you are using JPEG color spaces other than YCbCr or grayscale.
+ * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
+ *    is not 3 (they don't understand about dummy color components!).  So you
+ *    can't use color quantization if you change that value.
+ */
+
+#define RGB_RED		0	/* Offset of Red in an RGB scanline element */
+#define RGB_GREEN	1	/* Offset of Green */
+#define RGB_BLUE	2	/* Offset of Blue */
+#define RGB_PIXELSIZE	3	/* JSAMPLEs per RGB scanline element */
+
+
+/* Definitions for speed-related optimizations. */
+
+
+/* If your compiler supports inline functions, define INLINE
+ * as the inline keyword; otherwise define it as empty.
+ */
+
+#ifndef INLINE
+#ifdef __GNUC__			/* for instance, GNU C knows about inline */
+#define INLINE __inline__
+#endif
+#ifndef INLINE
+#define INLINE			/* default is to define it as empty */
+#endif
+#endif
+
+
+/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
+ * two 16-bit shorts is faster than multiplying two ints.  Define MULTIPLIER
+ * as short on such a machine.  MULTIPLIER must be at least 16 bits wide.
+ */
+
+#ifndef MULTIPLIER
+#define MULTIPLIER  int		/* type for fastest integer multiply */
+#endif
+
+
+/* FAST_FLOAT should be either float or double, whichever is done faster
+ * by your compiler.  (Note that this type is only used in the floating point
+ * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
+ * Typically, float is faster in ANSI C compilers, while double is faster in
+ * pre-ANSI compilers (because they insist on converting to double anyway).
+ * The code below therefore chooses float if we have ANSI-style prototypes.
+ */
+
+#ifndef FAST_FLOAT
+#ifdef HAVE_PROTOTYPES
+#define FAST_FLOAT  float
+#else
+#define FAST_FLOAT  double
+#endif
+#endif
+
+#endif /* JPEG_INTERNAL_OPTIONS */
diff -urdN ../Tekkotsu_2.3/aperios/include/jpeglib.h ./aperios/include/jpeglib.h
--- ../Tekkotsu_2.3/aperios/include/jpeglib.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/jpeglib.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,1096 @@
+/*
+ * jpeglib.h
+ *
+ * Copyright (C) 1991-1998, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+ * This file defines the application interface for the JPEG library.
+ * Most applications using the library need only include this file,
+ * and perhaps jerror.h if they want to know the exact error codes.
+ */
+
+#ifndef JPEGLIB_H
+#define JPEGLIB_H
+
+/*
+ * First we include the configuration files that record how this
+ * installation of the JPEG library is set up.  jconfig.h can be
+ * generated automatically for many systems.  jmorecfg.h contains
+ * manual configuration options that most people need not worry about.
+ */
+
+#ifndef JCONFIG_INCLUDED	/* in case jinclude.h already did */
+#include "jconfig.h"		/* widely used configuration options */
+#endif
+#include "jmorecfg.h"		/* seldom changed options */
+
+
+/* Version ID for the JPEG library.
+ * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
+ */
+
+#define JPEG_LIB_VERSION  62	/* Version 6b */
+
+
+/* Various constants determining the sizes of things.
+ * All of these are specified by the JPEG standard, so don't change them
+ * if you want to be compatible.
+ */
+
+#define DCTSIZE		    8	/* The basic DCT block is 8x8 samples */
+#define DCTSIZE2	    64	/* DCTSIZE squared; # of elements in a block */
+#define NUM_QUANT_TBLS      4	/* Quantization tables are numbered 0..3 */
+#define NUM_HUFF_TBLS       4	/* Huffman tables are numbered 0..3 */
+#define NUM_ARITH_TBLS      16	/* Arith-coding tables are numbered 0..15 */
+#define MAX_COMPS_IN_SCAN   4	/* JPEG limit on # of components in one scan */
+#define MAX_SAMP_FACTOR     4	/* JPEG limit on sampling factors */
+/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
+ * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
+ * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
+ * to handle it.  We even let you do this from the jconfig.h file.  However,
+ * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
+ * sometimes emits noncompliant files doesn't mean you should too.
+ */
+#define C_MAX_BLOCKS_IN_MCU   10 /* compressor's limit on blocks per MCU */
+#ifndef D_MAX_BLOCKS_IN_MCU
+#define D_MAX_BLOCKS_IN_MCU   10 /* decompressor's limit on blocks per MCU */
+#endif
+
+
+/* Data structures for images (arrays of samples and of DCT coefficients).
+ * On 80x86 machines, the image arrays are too big for near pointers,
+ * but the pointer arrays can fit in near memory.
+ */
+
+typedef JSAMPLE FAR *JSAMPROW;	/* ptr to one image row of pixel samples. */
+typedef JSAMPROW *JSAMPARRAY;	/* ptr to some rows (a 2-D sample array) */
+typedef JSAMPARRAY *JSAMPIMAGE;	/* a 3-D sample array: top index is color */
+
+typedef JCOEF JBLOCK[DCTSIZE2];	/* one block of coefficients */
+typedef JBLOCK FAR *JBLOCKROW;	/* pointer to one row of coefficient blocks */
+typedef JBLOCKROW *JBLOCKARRAY;		/* a 2-D array of coefficient blocks */
+typedef JBLOCKARRAY *JBLOCKIMAGE;	/* a 3-D array of coefficient blocks */
+
+typedef JCOEF FAR *JCOEFPTR;	/* useful in a couple of places */
+
+
+/* Types for JPEG compression parameters and working tables. */
+
+
+/* DCT coefficient quantization tables. */
+
+typedef struct {
+  /* This array gives the coefficient quantizers in natural array order
+   * (not the zigzag order in which they are stored in a JPEG DQT marker).
+   * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
+   */
+  UINT16 quantval[DCTSIZE2];	/* quantization step for each coefficient */
+  /* This field is used only during compression.  It's initialized FALSE when
+   * the table is created, and set TRUE when it's been output to the file.
+   * You could suppress output of a table by setting this to TRUE.
+   * (See jpeg_suppress_tables for an example.)
+   */
+  boolean sent_table;		/* TRUE when table has been output */
+} JQUANT_TBL;
+
+
+/* Huffman coding tables. */
+
+typedef struct {
+  /* These two fields directly represent the contents of a JPEG DHT marker */
+  UINT8 bits[17];		/* bits[k] = # of symbols with codes of */
+				/* length k bits; bits[0] is unused */
+  UINT8 huffval[256];		/* The symbols, in order of incr code length */
+  /* This field is used only during compression.  It's initialized FALSE when
+   * the table is created, and set TRUE when it's been output to the file.
+   * You could suppress output of a table by setting this to TRUE.
+   * (See jpeg_suppress_tables for an example.)
+   */
+  boolean sent_table;		/* TRUE when table has been output */
+} JHUFF_TBL;
+
+
+/* Basic info about one component (color channel). */
+
+typedef struct {
+  /* These values are fixed over the whole image. */
+  /* For compression, they must be supplied by parameter setup; */
+  /* for decompression, they are read from the SOF marker. */
+  int component_id;		/* identifier for this component (0..255) */
+  int component_index;		/* its index in SOF or cinfo->comp_info[] */
+  int h_samp_factor;		/* horizontal sampling factor (1..4) */
+  int v_samp_factor;		/* vertical sampling factor (1..4) */
+  int quant_tbl_no;		/* quantization table selector (0..3) */
+  /* These values may vary between scans. */
+  /* For compression, they must be supplied by parameter setup; */
+  /* for decompression, they are read from the SOS marker. */
+  /* The decompressor output side may not use these variables. */
+  int dc_tbl_no;		/* DC entropy table selector (0..3) */
+  int ac_tbl_no;		/* AC entropy table selector (0..3) */
+  
+  /* Remaining fields should be treated as private by applications. */
+  
+  /* These values are computed during compression or decompression startup: */
+  /* Component's size in DCT blocks.
+   * Any dummy blocks added to complete an MCU are not counted; therefore
+   * these values do not depend on whether a scan is interleaved or not.
+   */
+  JDIMENSION width_in_blocks;
+  JDIMENSION height_in_blocks;
+  /* Size of a DCT block in samples.  Always DCTSIZE for compression.
+   * For decompression this is the size of the output from one DCT block,
+   * reflecting any scaling we choose to apply during the IDCT step.
+   * Values of 1,2,4,8 are likely to be supported.  Note that different
+   * components may receive different IDCT scalings.
+   */
+  int DCT_scaled_size;
+  /* The downsampled dimensions are the component's actual, unpadded number
+   * of samples at the main buffer (preprocessing/compression interface), thus
+   * downsampled_width = ceil(image_width * Hi/Hmax)
+   * and similarly for height.  For decompression, IDCT scaling is included, so
+   * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
+   */
+  JDIMENSION downsampled_width;	 /* actual width in samples */
+  JDIMENSION downsampled_height; /* actual height in samples */
+  /* This flag is used only for decompression.  In cases where some of the
+   * components will be ignored (eg grayscale output from YCbCr image),
+   * we can skip most computations for the unused components.
+   */
+  boolean component_needed;	/* do we need the value of this component? */
+
+  /* These values are computed before starting a scan of the component. */
+  /* The decompressor output side may not use these variables. */
+  int MCU_width;		/* number of blocks per MCU, horizontally */
+  int MCU_height;		/* number of blocks per MCU, vertically */
+  int MCU_blocks;		/* MCU_width * MCU_height */
+  int MCU_sample_width;		/* MCU width in samples, MCU_width*DCT_scaled_size */
+  int last_col_width;		/* # of non-dummy blocks across in last MCU */
+  int last_row_height;		/* # of non-dummy blocks down in last MCU */
+
+  /* Saved quantization table for component; NULL if none yet saved.
+   * See jdinput.c comments about the need for this information.
+   * This field is currently used only for decompression.
+   */
+  JQUANT_TBL * quant_table;
+
+  /* Private per-component storage for DCT or IDCT subsystem. */
+  void * dct_table;
+} jpeg_component_info;
+
+
+/* The script for encoding a multiple-scan file is an array of these: */
+
+typedef struct {
+  int comps_in_scan;		/* number of components encoded in this scan */
+  int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
+  int Ss, Se;			/* progressive JPEG spectral selection parms */
+  int Ah, Al;			/* progressive JPEG successive approx. parms */
+} jpeg_scan_info;
+
+/* The decompressor can save APPn and COM markers in a list of these: */
+
+typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
+
+struct jpeg_marker_struct {
+  jpeg_saved_marker_ptr next;	/* next in list, or NULL */
+  UINT8 marker;			/* marker code: JPEG_COM, or JPEG_APP0+n */
+  unsigned int original_length;	/* # bytes of data in the file */
+  unsigned int data_length;	/* # bytes of data saved at data[] */
+  JOCTET FAR * data;		/* the data contained in the marker */
+  /* the marker length word is not counted in data_length or original_length */
+};
+
+/* Known color spaces. */
+
+typedef enum {
+	JCS_UNKNOWN,		/* error/unspecified */
+	JCS_GRAYSCALE,		/* monochrome */
+	JCS_RGB,		/* red/green/blue */
+	JCS_YCbCr,		/* Y/Cb/Cr (also known as YUV) */
+	JCS_CMYK,		/* C/M/Y/K */
+	JCS_YCCK		/* Y/Cb/Cr/K */
+} J_COLOR_SPACE;
+
+/* DCT/IDCT algorithm options. */
+
+typedef enum {
+	JDCT_ISLOW,		/* slow but accurate integer algorithm */
+	JDCT_IFAST,		/* faster, less accurate integer method */
+	JDCT_FLOAT		/* floating-point: accurate, fast on fast HW */
+} J_DCT_METHOD;
+
+#ifndef JDCT_DEFAULT		/* may be overridden in jconfig.h */
+#define JDCT_DEFAULT  JDCT_ISLOW
+#endif
+#ifndef JDCT_FASTEST		/* may be overridden in jconfig.h */
+#define JDCT_FASTEST  JDCT_IFAST
+#endif
+
+/* Dithering options for decompression. */
+
+typedef enum {
+	JDITHER_NONE,		/* no dithering */
+	JDITHER_ORDERED,	/* simple ordered dither */
+	JDITHER_FS		/* Floyd-Steinberg error diffusion dither */
+} J_DITHER_MODE;
+
+
+/* Common fields between JPEG compression and decompression master structs. */
+
+#define jpeg_common_fields \
+  struct jpeg_error_mgr * err;	/* Error handler module */\
+  struct jpeg_memory_mgr * mem;	/* Memory manager module */\
+  struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
+  void * client_data;		/* Available for use by application */\
+  boolean is_decompressor;	/* So common code can tell which is which */\
+  int global_state		/* For checking call sequence validity */
+
+/* Routines that are to be used by both halves of the library are declared
+ * to receive a pointer to this structure.  There are no actual instances of
+ * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
+ */
+struct jpeg_common_struct {
+  jpeg_common_fields;		/* Fields common to both master struct types */
+  /* Additional fields follow in an actual jpeg_compress_struct or
+   * jpeg_decompress_struct.  All three structs must agree on these
+   * initial fields!  (This would be a lot cleaner in C++.)
+   */
+};
+
+typedef struct jpeg_common_struct * j_common_ptr;
+typedef struct jpeg_compress_struct * j_compress_ptr;
+typedef struct jpeg_decompress_struct * j_decompress_ptr;
+
+
+/* Master record for a compression instance */
+
+struct jpeg_compress_struct {
+  jpeg_common_fields;		/* Fields shared with jpeg_decompress_struct */
+
+  /* Destination for compressed data */
+  struct jpeg_destination_mgr * dest;
+
+  /* Description of source image --- these fields must be filled in by
+   * outer application before starting compression.  in_color_space must
+   * be correct before you can even call jpeg_set_defaults().
+   */
+
+  JDIMENSION image_width;	/* input image width */
+  JDIMENSION image_height;	/* input image height */
+  int input_components;		/* # of color components in input image */
+  J_COLOR_SPACE in_color_space;	/* colorspace of input image */
+
+  double input_gamma;		/* image gamma of input image */
+
+  /* Compression parameters --- these fields must be set before calling
+   * jpeg_start_compress().  We recommend calling jpeg_set_defaults() to
+   * initialize everything to reasonable defaults, then changing anything
+   * the application specifically wants to change.  That way you won't get
+   * burnt when new parameters are added.  Also note that there are several
+   * helper routines to simplify changing parameters.
+   */
+
+  int data_precision;		/* bits of precision in image data */
+
+  int num_components;		/* # of color components in JPEG image */
+  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+  jpeg_component_info * comp_info;
+  /* comp_info[i] describes component that appears i'th in SOF */
+  
+  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+  /* ptrs to coefficient quantization tables, or NULL if not defined */
+  
+  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  /* ptrs to Huffman coding tables, or NULL if not defined */
+  
+  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+  int num_scans;		/* # of entries in scan_info array */
+  const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
+  /* The default value of scan_info is NULL, which causes a single-scan
+   * sequential JPEG file to be emitted.  To create a multi-scan file,
+   * set num_scans and scan_info to point to an array of scan definitions.
+   */
+
+  boolean raw_data_in;		/* TRUE=caller supplies downsampled data */
+  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
+  boolean optimize_coding;	/* TRUE=optimize entropy encoding parms */
+  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
+  int smoothing_factor;		/* 1..100, or 0 for no input smoothing */
+  J_DCT_METHOD dct_method;	/* DCT algorithm selector */
+
+  /* The restart interval can be specified in absolute MCUs by setting
+   * restart_interval, or in MCU rows by setting restart_in_rows
+   * (in which case the correct restart_interval will be figured
+   * for each scan).
+   */
+  unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
+  int restart_in_rows;		/* if > 0, MCU rows per restart interval */
+
+  /* Parameters controlling emission of special markers. */
+
+  boolean write_JFIF_header;	/* should a JFIF marker be written? */
+  UINT8 JFIF_major_version;	/* What to write for the JFIF version number */
+  UINT8 JFIF_minor_version;
+  /* These three values are not used by the JPEG code, merely copied */
+  /* into the JFIF APP0 marker.  density_unit can be 0 for unknown, */
+  /* 1 for dots/inch, or 2 for dots/cm.  Note that the pixel aspect */
+  /* ratio is defined by X_density/Y_density even when density_unit=0. */
+  UINT8 density_unit;		/* JFIF code for pixel size units */
+  UINT16 X_density;		/* Horizontal pixel density */
+  UINT16 Y_density;		/* Vertical pixel density */
+  boolean write_Adobe_marker;	/* should an Adobe marker be written? */
+  
+  /* State variable: index of next scanline to be written to
+   * jpeg_write_scanlines().  Application may use this to control its
+   * processing loop, e.g., "while (next_scanline < image_height)".
+   */
+
+  JDIMENSION next_scanline;	/* 0 .. image_height-1  */
+
+  /* Remaining fields are known throughout compressor, but generally
+   * should not be touched by a surrounding application.
+   */
+
+  /*
+   * These fields are computed during compression startup
+   */
+  boolean progressive_mode;	/* TRUE if scan script uses progressive mode */
+  int max_h_samp_factor;	/* largest h_samp_factor */
+  int max_v_samp_factor;	/* largest v_samp_factor */
+
+  JDIMENSION total_iMCU_rows;	/* # of iMCU rows to be input to coef ctlr */
+  /* The coefficient controller receives data in units of MCU rows as defined
+   * for fully interleaved scans (whether the JPEG file is interleaved or not).
+   * There are v_samp_factor * DCTSIZE sample rows of each component in an
+   * "iMCU" (interleaved MCU) row.
+   */
+  
+  /*
+   * These fields are valid during any one scan.
+   * They describe the components and MCUs actually appearing in the scan.
+   */
+  int comps_in_scan;		/* # of JPEG components in this scan */
+  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+  /* *cur_comp_info[i] describes component that appears i'th in SOS */
+  
+  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
+  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
+  
+  int blocks_in_MCU;		/* # of DCT blocks per MCU */
+  int MCU_membership[C_MAX_BLOCKS_IN_MCU];
+  /* MCU_membership[i] is index in cur_comp_info of component owning */
+  /* i'th block in an MCU */
+
+  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
+
+  /*
+   * Links to compression subobjects (methods and private variables of modules)
+   */
+  struct jpeg_comp_master * master;
+  struct jpeg_c_main_controller * main;
+  struct jpeg_c_prep_controller * prep;
+  struct jpeg_c_coef_controller * coef;
+  struct jpeg_marker_writer * marker;
+  struct jpeg_color_converter * cconvert;
+  struct jpeg_downsampler * downsample;
+  struct jpeg_forward_dct * fdct;
+  struct jpeg_entropy_encoder * entropy;
+  jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
+  int script_space_size;
+};
+
+
+/* Master record for a decompression instance */
+
+struct jpeg_decompress_struct {
+  jpeg_common_fields;		/* Fields shared with jpeg_compress_struct */
+
+  /* Source of compressed data */
+  struct jpeg_source_mgr * src;
+
+  /* Basic description of image --- filled in by jpeg_read_header(). */
+  /* Application may inspect these values to decide how to process image. */
+
+  JDIMENSION image_width;	/* nominal image width (from SOF marker) */
+  JDIMENSION image_height;	/* nominal image height */
+  int num_components;		/* # of color components in JPEG image */
+  J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
+
+  /* Decompression processing parameters --- these fields must be set before
+   * calling jpeg_start_decompress().  Note that jpeg_read_header() initializes
+   * them to default values.
+   */
+
+  J_COLOR_SPACE out_color_space; /* colorspace for output */
+
+  unsigned int scale_num, scale_denom; /* fraction by which to scale image */
+
+  double output_gamma;		/* image gamma wanted in output */
+
+  boolean buffered_image;	/* TRUE=multiple output passes */
+  boolean raw_data_out;		/* TRUE=downsampled data wanted */
+
+  J_DCT_METHOD dct_method;	/* IDCT algorithm selector */
+  boolean do_fancy_upsampling;	/* TRUE=apply fancy upsampling */
+  boolean do_block_smoothing;	/* TRUE=apply interblock smoothing */
+
+  boolean quantize_colors;	/* TRUE=colormapped output wanted */
+  /* the following are ignored if not quantize_colors: */
+  J_DITHER_MODE dither_mode;	/* type of color dithering to use */
+  boolean two_pass_quantize;	/* TRUE=use two-pass color quantization */
+  int desired_number_of_colors;	/* max # colors to use in created colormap */
+  /* these are significant only in buffered-image mode: */
+  boolean enable_1pass_quant;	/* enable future use of 1-pass quantizer */
+  boolean enable_external_quant;/* enable future use of external colormap */
+  boolean enable_2pass_quant;	/* enable future use of 2-pass quantizer */
+
+  /* Description of actual output image that will be returned to application.
+   * These fields are computed by jpeg_start_decompress().
+   * You can also use jpeg_calc_output_dimensions() to determine these values
+   * in advance of calling jpeg_start_decompress().
+   */
+
+  JDIMENSION output_width;	/* scaled image width */
+  JDIMENSION output_height;	/* scaled image height */
+  int out_color_components;	/* # of color components in out_color_space */
+  int output_components;	/* # of color components returned */
+  /* output_components is 1 (a colormap index) when quantizing colors;
+   * otherwise it equals out_color_components.
+   */
+  int rec_outbuf_height;	/* min recommended height of scanline buffer */
+  /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
+   * high, space and time will be wasted due to unnecessary data copying.
+   * Usually rec_outbuf_height will be 1 or 2, at most 4.
+   */
+
+  /* When quantizing colors, the output colormap is described by these fields.
+   * The application can supply a colormap by setting colormap non-NULL before
+   * calling jpeg_start_decompress; otherwise a colormap is created during
+   * jpeg_start_decompress or jpeg_start_output.
+   * The map has out_color_components rows and actual_number_of_colors columns.
+   */
+  int actual_number_of_colors;	/* number of entries in use */
+  JSAMPARRAY colormap;		/* The color map as a 2-D pixel array */
+
+  /* State variables: these variables indicate the progress of decompression.
+   * The application may examine these but must not modify them.
+   */
+
+  /* Row index of next scanline to be read from jpeg_read_scanlines().
+   * Application may use this to control its processing loop, e.g.,
+   * "while (output_scanline < output_height)".
+   */
+  JDIMENSION output_scanline;	/* 0 .. output_height-1  */
+
+  /* Current input scan number and number of iMCU rows completed in scan.
+   * These indicate the progress of the decompressor input side.
+   */
+  int input_scan_number;	/* Number of SOS markers seen so far */
+  JDIMENSION input_iMCU_row;	/* Number of iMCU rows completed */
+
+  /* The "output scan number" is the notional scan being displayed by the
+   * output side.  The decompressor will not allow output scan/row number
+   * to get ahead of input scan/row, but it can fall arbitrarily far behind.
+   */
+  int output_scan_number;	/* Nominal scan number being displayed */
+  JDIMENSION output_iMCU_row;	/* Number of iMCU rows read */
+
+  /* Current progression status.  coef_bits[c][i] indicates the precision
+   * with which component c's DCT coefficient i (in zigzag order) is known.
+   * It is -1 when no data has yet been received, otherwise it is the point
+   * transform (shift) value for the most recent scan of the coefficient
+   * (thus, 0 at completion of the progression).
+   * This pointer is NULL when reading a non-progressive file.
+   */
+  int (*coef_bits)[DCTSIZE2];	/* -1 or current Al value for each coef */
+
+  /* Internal JPEG parameters --- the application usually need not look at
+   * these fields.  Note that the decompressor output side may not use
+   * any parameters that can change between scans.
+   */
+
+  /* Quantization and Huffman tables are carried forward across input
+   * datastreams when processing abbreviated JPEG datastreams.
+   */
+
+  JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
+  /* ptrs to coefficient quantization tables, or NULL if not defined */
+
+  JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
+  /* ptrs to Huffman coding tables, or NULL if not defined */
+
+  /* These parameters are never carried across datastreams, since they
+   * are given in SOF/SOS markers or defined to be reset by SOI.
+   */
+
+  int data_precision;		/* bits of precision in image data */
+
+  jpeg_component_info * comp_info;
+  /* comp_info[i] describes component that appears i'th in SOF */
+
+  boolean progressive_mode;	/* TRUE if SOFn specifies progressive mode */
+  boolean arith_code;		/* TRUE=arithmetic coding, FALSE=Huffman */
+
+  UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
+  UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
+  UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
+
+  unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
+
+  /* These fields record data obtained from optional markers recognized by
+   * the JPEG library.
+   */
+  boolean saw_JFIF_marker;	/* TRUE iff a JFIF APP0 marker was found */
+  /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
+  UINT8 JFIF_major_version;	/* JFIF version number */
+  UINT8 JFIF_minor_version;
+  UINT8 density_unit;		/* JFIF code for pixel size units */
+  UINT16 X_density;		/* Horizontal pixel density */
+  UINT16 Y_density;		/* Vertical pixel density */
+  boolean saw_Adobe_marker;	/* TRUE iff an Adobe APP14 marker was found */
+  UINT8 Adobe_transform;	/* Color transform code from Adobe marker */
+
+  boolean CCIR601_sampling;	/* TRUE=first samples are cosited */
+
+  /* Aside from the specific data retained from APPn markers known to the
+   * library, the uninterpreted contents of any or all APPn and COM markers
+   * can be saved in a list for examination by the application.
+   */
+  jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
+
+  /* Remaining fields are known throughout decompressor, but generally
+   * should not be touched by a surrounding application.
+   */
+
+  /*
+   * These fields are computed during decompression startup
+   */
+  int max_h_samp_factor;	/* largest h_samp_factor */
+  int max_v_samp_factor;	/* largest v_samp_factor */
+
+  int min_DCT_scaled_size;	/* smallest DCT_scaled_size of any component */
+
+  JDIMENSION total_iMCU_rows;	/* # of iMCU rows in image */
+  /* The coefficient controller's input and output progress is measured in
+   * units of "iMCU" (interleaved MCU) rows.  These are the same as MCU rows
+   * in fully interleaved JPEG scans, but are used whether the scan is
+   * interleaved or not.  We define an iMCU row as v_samp_factor DCT block
+   * rows of each component.  Therefore, the IDCT output contains
+   * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
+   */
+
+  JSAMPLE * sample_range_limit; /* table for fast range-limiting */
+
+  /*
+   * These fields are valid during any one scan.
+   * They describe the components and MCUs actually appearing in the scan.
+   * Note that the decompressor output side must not use these fields.
+   */
+  int comps_in_scan;		/* # of JPEG components in this scan */
+  jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
+  /* *cur_comp_info[i] describes component that appears i'th in SOS */
+
+  JDIMENSION MCUs_per_row;	/* # of MCUs across the image */
+  JDIMENSION MCU_rows_in_scan;	/* # of MCU rows in the image */
+
+  int blocks_in_MCU;		/* # of DCT blocks per MCU */
+  int MCU_membership[D_MAX_BLOCKS_IN_MCU];
+  /* MCU_membership[i] is index in cur_comp_info of component owning */
+  /* i'th block in an MCU */
+
+  int Ss, Se, Ah, Al;		/* progressive JPEG parameters for scan */
+
+  /* This field is shared between entropy decoder and marker parser.
+   * It is either zero or the code of a JPEG marker that has been
+   * read from the data source, but has not yet been processed.
+   */
+  int unread_marker;
+
+  /*
+   * Links to decompression subobjects (methods, private variables of modules)
+   */
+  struct jpeg_decomp_master * master;
+  struct jpeg_d_main_controller * main;
+  struct jpeg_d_coef_controller * coef;
+  struct jpeg_d_post_controller * post;
+  struct jpeg_input_controller * inputctl;
+  struct jpeg_marker_reader * marker;
+  struct jpeg_entropy_decoder * entropy;
+  struct jpeg_inverse_dct * idct;
+  struct jpeg_upsampler * upsample;
+  struct jpeg_color_deconverter * cconvert;
+  struct jpeg_color_quantizer * cquantize;
+};
+
+
+/* "Object" declarations for JPEG modules that may be supplied or called
+ * directly by the surrounding application.
+ * As with all objects in the JPEG library, these structs only define the
+ * publicly visible methods and state variables of a module.  Additional
+ * private fields may exist after the public ones.
+ */
+
+
+/* Error handler object */
+
+struct jpeg_error_mgr {
+  /* Error exit handler: does not return to caller */
+  JMETHOD(void, error_exit, (j_common_ptr cinfo));
+  /* Conditionally emit a trace or warning message */
+  JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
+  /* Routine that actually outputs a trace or error message */
+  JMETHOD(void, output_message, (j_common_ptr cinfo));
+  /* Format a message string for the most recent JPEG error or message */
+  JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
+#define JMSG_LENGTH_MAX  200	/* recommended size of format_message buffer */
+  /* Reset error state variables at start of a new image */
+  JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
+  
+  /* The message ID code and any parameters are saved here.
+   * A message can have one string parameter or up to 8 int parameters.
+   */
+  int msg_code;
+#define JMSG_STR_PARM_MAX  80
+  union {
+    int i[8];
+    char s[JMSG_STR_PARM_MAX];
+  } msg_parm;
+  
+  /* Standard state variables for error facility */
+  
+  int trace_level;		/* max msg_level that will be displayed */
+  
+  /* For recoverable corrupt-data errors, we emit a warning message,
+   * but keep going unless emit_message chooses to abort.  emit_message
+   * should count warnings in num_warnings.  The surrounding application
+   * can check for bad data by seeing if num_warnings is nonzero at the
+   * end of processing.
+   */
+  long num_warnings;		/* number of corrupt-data warnings */
+
+  /* These fields point to the table(s) of error message strings.
+   * An application can change the table pointer to switch to a different
+   * message list (typically, to change the language in which errors are
+   * reported).  Some applications may wish to add additional error codes
+   * that will be handled by the JPEG library error mechanism; the second
+   * table pointer is used for this purpose.
+   *
+   * First table includes all errors generated by JPEG library itself.
+   * Error code 0 is reserved for a "no such error string" message.
+   */
+  const char * const * jpeg_message_table; /* Library errors */
+  int last_jpeg_message;    /* Table contains strings 0..last_jpeg_message */
+  /* Second table can be added by application (see cjpeg/djpeg for example).
+   * It contains strings numbered first_addon_message..last_addon_message.
+   */
+  const char * const * addon_message_table; /* Non-library errors */
+  int first_addon_message;	/* code for first string in addon table */
+  int last_addon_message;	/* code for last string in addon table */
+};
+
+
+/* Progress monitor object */
+
+struct jpeg_progress_mgr {
+  JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
+
+  long pass_counter;		/* work units completed in this pass */
+  long pass_limit;		/* total number of work units in this pass */
+  int completed_passes;		/* passes completed so far */
+  int total_passes;		/* total number of passes expected */
+};
+
+
+/* Data destination object for compression */
+
+struct jpeg_destination_mgr {
+  JOCTET * next_output_byte;	/* => next byte to write in buffer */
+  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
+
+  JMETHOD(void, init_destination, (j_compress_ptr cinfo));
+  JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
+  JMETHOD(void, term_destination, (j_compress_ptr cinfo));
+};
+
+
+/* Data source object for decompression */
+
+struct jpeg_source_mgr {
+  const JOCTET * next_input_byte; /* => next byte to read from buffer */
+  size_t bytes_in_buffer;	/* # of bytes remaining in buffer */
+
+  JMETHOD(void, init_source, (j_decompress_ptr cinfo));
+  JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
+  JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
+  JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
+  JMETHOD(void, term_source, (j_decompress_ptr cinfo));
+};
+
+
+/* Memory manager object.
+ * Allocates "small" objects (a few K total), "large" objects (tens of K),
+ * and "really big" objects (virtual arrays with backing store if needed).
+ * The memory manager does not allow individual objects to be freed; rather,
+ * each created object is assigned to a pool, and whole pools can be freed
+ * at once.  This is faster and more convenient than remembering exactly what
+ * to free, especially where malloc()/free() are not too speedy.
+ * NB: alloc routines never return NULL.  They exit to error_exit if not
+ * successful.
+ */
+
+#define JPOOL_PERMANENT	0	/* lasts until master record is destroyed */
+#define JPOOL_IMAGE	1	/* lasts until done with image/datastream */
+#define JPOOL_NUMPOOLS	2
+
+typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
+typedef struct jvirt_barray_control * jvirt_barray_ptr;
+
+
+struct jpeg_memory_mgr {
+  /* Method pointers */
+  JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
+				size_t sizeofobject));
+  JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
+				     size_t sizeofobject));
+  JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
+				     JDIMENSION samplesperrow,
+				     JDIMENSION numrows));
+  JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
+				      JDIMENSION blocksperrow,
+				      JDIMENSION numrows));
+  JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
+						  int pool_id,
+						  boolean pre_zero,
+						  JDIMENSION samplesperrow,
+						  JDIMENSION numrows,
+						  JDIMENSION maxaccess));
+  JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
+						  int pool_id,
+						  boolean pre_zero,
+						  JDIMENSION blocksperrow,
+						  JDIMENSION numrows,
+						  JDIMENSION maxaccess));
+  JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
+  JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
+					   jvirt_sarray_ptr ptr,
+					   JDIMENSION start_row,
+					   JDIMENSION num_rows,
+					   boolean writable));
+  JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
+					    jvirt_barray_ptr ptr,
+					    JDIMENSION start_row,
+					    JDIMENSION num_rows,
+					    boolean writable));
+  JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
+  JMETHOD(void, self_destruct, (j_common_ptr cinfo));
+
+  /* Limit on memory allocation for this JPEG object.  (Note that this is
+   * merely advisory, not a guaranteed maximum; it only affects the space
+   * used for virtual-array buffers.)  May be changed by outer application
+   * after creating the JPEG object.
+   */
+  long max_memory_to_use;
+
+  /* Maximum allocation request accepted by alloc_large. */
+  long max_alloc_chunk;
+};
+
+
+/* Routine signature for application-supplied marker processing methods.
+ * Need not pass marker code since it is stored in cinfo->unread_marker.
+ */
+typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
+
+
+/* Declarations for routines called by application.
+ * The JPP macro hides prototype parameters from compilers that can't cope.
+ * Note JPP requires double parentheses.
+ */
+
+#ifdef HAVE_PROTOTYPES
+#define JPP(arglist)	arglist
+#else
+#define JPP(arglist)	()
+#endif
+
+
+/* Short forms of external names for systems with brain-damaged linkers.
+ * We shorten external names to be unique in the first six letters, which
+ * is good enough for all known systems.
+ * (If your compiler itself needs names to be unique in less than 15 
+ * characters, you are out of luck.  Get a better compiler.)
+ */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jpeg_std_error		jStdError
+#define jpeg_CreateCompress	jCreaCompress
+#define jpeg_CreateDecompress	jCreaDecompress
+#define jpeg_destroy_compress	jDestCompress
+#define jpeg_destroy_decompress	jDestDecompress
+#define jpeg_stdio_dest		jStdDest
+#define jpeg_stdio_src		jStdSrc
+#define jpeg_set_defaults	jSetDefaults
+#define jpeg_set_colorspace	jSetColorspace
+#define jpeg_default_colorspace	jDefColorspace
+#define jpeg_set_quality	jSetQuality
+#define jpeg_set_linear_quality	jSetLQuality
+#define jpeg_add_quant_table	jAddQuantTable
+#define jpeg_quality_scaling	jQualityScaling
+#define jpeg_simple_progression	jSimProgress
+#define jpeg_suppress_tables	jSuppressTables
+#define jpeg_alloc_quant_table	jAlcQTable
+#define jpeg_alloc_huff_table	jAlcHTable
+#define jpeg_start_compress	jStrtCompress
+#define jpeg_write_scanlines	jWrtScanlines
+#define jpeg_finish_compress	jFinCompress
+#define jpeg_write_raw_data	jWrtRawData
+#define jpeg_write_marker	jWrtMarker
+#define jpeg_write_m_header	jWrtMHeader
+#define jpeg_write_m_byte	jWrtMByte
+#define jpeg_write_tables	jWrtTables
+#define jpeg_read_header	jReadHeader
+#define jpeg_start_decompress	jStrtDecompress
+#define jpeg_read_scanlines	jReadScanlines
+#define jpeg_finish_decompress	jFinDecompress
+#define jpeg_read_raw_data	jReadRawData
+#define jpeg_has_multiple_scans	jHasMultScn
+#define jpeg_start_output	jStrtOutput
+#define jpeg_finish_output	jFinOutput
+#define jpeg_input_complete	jInComplete
+#define jpeg_new_colormap	jNewCMap
+#define jpeg_consume_input	jConsumeInput
+#define jpeg_calc_output_dimensions	jCalcDimensions
+#define jpeg_save_markers	jSaveMarkers
+#define jpeg_set_marker_processor	jSetMarker
+#define jpeg_read_coefficients	jReadCoefs
+#define jpeg_write_coefficients	jWrtCoefs
+#define jpeg_copy_critical_parameters	jCopyCrit
+#define jpeg_abort_compress	jAbrtCompress
+#define jpeg_abort_decompress	jAbrtDecompress
+#define jpeg_abort		jAbort
+#define jpeg_destroy		jDestroy
+#define jpeg_resync_to_restart	jResyncRestart
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+
+/* Default error-management setup */
+EXTERN(struct jpeg_error_mgr *) jpeg_std_error
+	JPP((struct jpeg_error_mgr * err));
+
+/* Initialization of JPEG compression objects.
+ * jpeg_create_compress() and jpeg_create_decompress() are the exported
+ * names that applications should call.  These expand to calls on
+ * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
+ * passed for version mismatch checking.
+ * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
+ */
+#define jpeg_create_compress(cinfo) \
+    jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
+			(size_t) sizeof(struct jpeg_compress_struct))
+#define jpeg_create_decompress(cinfo) \
+    jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
+			  (size_t) sizeof(struct jpeg_decompress_struct))
+EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
+				      int version, size_t structsize));
+EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
+					int version, size_t structsize));
+/* Destruction of JPEG compression objects */
+EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
+
+/* Standard data source and destination managers: stdio streams. */
+/* Caller is responsible for opening the file before and closing after. */
+EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
+EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
+
+/* Default parameter setup for compression */
+EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
+/* Compression parameter setup aids */
+EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
+				      J_COLOR_SPACE colorspace));
+EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
+				   boolean force_baseline));
+EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
+					  int scale_factor,
+					  boolean force_baseline));
+EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
+				       const unsigned int *basic_table,
+				       int scale_factor,
+				       boolean force_baseline));
+EXTERN(int) jpeg_quality_scaling JPP((int quality));
+EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
+				       boolean suppress));
+EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
+EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
+
+/* Main entry points for compression */
+EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
+				      boolean write_all_tables));
+EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
+					     JSAMPARRAY scanlines,
+					     JDIMENSION num_lines));
+EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
+
+/* Replaces jpeg_write_scanlines when writing raw downsampled data. */
+EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
+					    JSAMPIMAGE data,
+					    JDIMENSION num_lines));
+
+/* Write a special marker.  See libjpeg.doc concerning safe usage. */
+EXTERN(void) jpeg_write_marker
+	JPP((j_compress_ptr cinfo, int marker,
+	     const JOCTET * dataptr, unsigned int datalen));
+/* Same, but piecemeal. */
+EXTERN(void) jpeg_write_m_header
+	JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
+EXTERN(void) jpeg_write_m_byte
+	JPP((j_compress_ptr cinfo, int val));
+
+/* Alternate compression function: just write an abbreviated table file */
+EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
+
+/* Decompression startup: read start of JPEG datastream to see what's there */
+EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
+				  boolean require_image));
+/* Return value is one of: */
+#define JPEG_SUSPENDED		0 /* Suspended due to lack of input data */
+#define JPEG_HEADER_OK		1 /* Found valid image datastream */
+#define JPEG_HEADER_TABLES_ONLY	2 /* Found valid table-specs-only datastream */
+/* If you pass require_image = TRUE (normal case), you need not check for
+ * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
+ * JPEG_SUSPENDED is only possible if you use a data source module that can
+ * give a suspension return (the stdio source module doesn't).
+ */
+
+/* Main entry points for decompression */
+EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
+EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
+					    JSAMPARRAY scanlines,
+					    JDIMENSION max_lines));
+EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
+
+/* Replaces jpeg_read_scanlines when reading raw downsampled data. */
+EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
+					   JSAMPIMAGE data,
+					   JDIMENSION max_lines));
+
+/* Additional entry points for buffered-image mode. */
+EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
+EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
+				       int scan_number));
+EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
+EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
+EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
+EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
+/* Return value is one of: */
+/* #define JPEG_SUSPENDED	0    Suspended due to lack of input data */
+#define JPEG_REACHED_SOS	1 /* Reached start of new scan */
+#define JPEG_REACHED_EOI	2 /* Reached end of image */
+#define JPEG_ROW_COMPLETED	3 /* Completed one iMCU row */
+#define JPEG_SCAN_COMPLETED	4 /* Completed last iMCU row of a scan */
+
+/* Precalculate output dimensions for current decompression parameters. */
+EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
+
+/* Control saving of COM and APPn markers into marker_list. */
+EXTERN(void) jpeg_save_markers
+	JPP((j_decompress_ptr cinfo, int marker_code,
+	     unsigned int length_limit));
+
+/* Install a special processing method for COM or APPn markers. */
+EXTERN(void) jpeg_set_marker_processor
+	JPP((j_decompress_ptr cinfo, int marker_code,
+	     jpeg_marker_parser_method routine));
+
+/* Read or write raw DCT coefficients --- useful for lossless transcoding. */
+EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
+EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
+					  jvirt_barray_ptr * coef_arrays));
+EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
+						j_compress_ptr dstinfo));
+
+/* If you choose to abort compression or decompression before completing
+ * jpeg_finish_(de)compress, then you need to clean up to release memory,
+ * temporary files, etc.  You can just call jpeg_destroy_(de)compress
+ * if you're done with the JPEG object, but if you want to clean it up and
+ * reuse it, call this:
+ */
+EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
+EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
+
+/* Generic versions of jpeg_abort and jpeg_destroy that work on either
+ * flavor of JPEG object.  These may be more convenient in some places.
+ */
+EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
+EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
+
+/* Default restart-marker-resync procedure for use by data source modules */
+EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
+					    int desired));
+
+
+/* These marker codes are exported since applications and data source modules
+ * are likely to want to use them.
+ */
+
+#define JPEG_RST0	0xD0	/* RST0 marker code */
+#define JPEG_EOI	0xD9	/* EOI marker code */
+#define JPEG_APP0	0xE0	/* APP0 marker code */
+#define JPEG_COM	0xFE	/* COM marker code */
+
+
+/* If we have a brain-damaged compiler that emits warnings (or worse, errors)
+ * for structure definitions that are never filled in, keep it quiet by
+ * supplying dummy definitions for the various substructures.
+ */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef JPEG_INTERNALS		/* will be defined in jpegint.h */
+struct jvirt_sarray_control { long dummy; };
+struct jvirt_barray_control { long dummy; };
+struct jpeg_comp_master { long dummy; };
+struct jpeg_c_main_controller { long dummy; };
+struct jpeg_c_prep_controller { long dummy; };
+struct jpeg_c_coef_controller { long dummy; };
+struct jpeg_marker_writer { long dummy; };
+struct jpeg_color_converter { long dummy; };
+struct jpeg_downsampler { long dummy; };
+struct jpeg_forward_dct { long dummy; };
+struct jpeg_entropy_encoder { long dummy; };
+struct jpeg_decomp_master { long dummy; };
+struct jpeg_d_main_controller { long dummy; };
+struct jpeg_d_coef_controller { long dummy; };
+struct jpeg_d_post_controller { long dummy; };
+struct jpeg_input_controller { long dummy; };
+struct jpeg_marker_reader { long dummy; };
+struct jpeg_entropy_decoder { long dummy; };
+struct jpeg_inverse_dct { long dummy; };
+struct jpeg_upsampler { long dummy; };
+struct jpeg_color_deconverter { long dummy; };
+struct jpeg_color_quantizer { long dummy; };
+#endif /* JPEG_INTERNALS */
+#endif /* INCOMPLETE_TYPES_BROKEN */
+
+
+/*
+ * The JPEG library modules define JPEG_INTERNALS before including this file.
+ * The internal structure declarations are read only when that is true.
+ * Applications using the library should not include jpegint.h, but may wish
+ * to include jerror.h.
+ */
+
+#ifdef JPEG_INTERNALS
+#include "jpegint.h"		/* fetch private declarations */
+#include "jerror.h"		/* fetch error codes too */
+#endif
+
+#endif /* JPEGLIB_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng/CVS/Entries ./aperios/include/libpng/CVS/Entries
--- ../Tekkotsu_2.3/aperios/include/libpng/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng/CVS/Entries	Wed Aug 10 11:03:22 2005
@@ -0,0 +1,3 @@
+/png.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/pngconf.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng/CVS/Repository ./aperios/include/libpng/CVS/Repository
--- ../Tekkotsu_2.3/aperios/include/libpng/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng/CVS/Repository	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/include/libpng
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng/CVS/Root ./aperios/include/libpng/CVS/Root
--- ../Tekkotsu_2.3/aperios/include/libpng/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng/CVS/Root	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng/CVS/Tag ./aperios/include/libpng/CVS/Tag
--- ../Tekkotsu_2.3/aperios/include/libpng/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng/CVS/Tag	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng/png.h ./aperios/include/libpng/png.h
--- ../Tekkotsu_2.3/aperios/include/libpng/png.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng/png.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,3419 @@
+/* png.h - header file for PNG reference library
+ *
+ * libpng version 1.2.8 - December 3, 2004
+ * Copyright (c) 1998-2004 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * Authors and maintainers:
+ *  libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
+ *  libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
+ *  libpng versions 0.97, January 1998, through 1.2.8 - December 3, 2004: Glenn
+ *  See also "Contributing Authors", below.
+ *
+ * Note about libpng version numbers:
+ *
+ *    Due to various miscommunications, unforeseen code incompatibilities
+ *    and occasional factors outside the authors' control, version numbering
+ *    on the library has not always been consistent and straightforward.
+ *    The following table summarizes matters since version 0.89c, which was
+ *    the first widely used release:
+ *
+ *    source                 png.h  png.h  shared-lib
+ *    version                string   int  version
+ *    -------                ------ -----  ----------
+ *    0.89c "1.0 beta 3"     0.89      89  1.0.89
+ *    0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
+ *    0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
+ *    0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
+ *    0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
+ *    0.97c                  0.97      97  2.0.97
+ *    0.98                   0.98      98  2.0.98
+ *    0.99                   0.99      98  2.0.99
+ *    0.99a-m                0.99      99  2.0.99
+ *    1.00                   1.00     100  2.1.0 [100 should be 10000]
+ *    1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
+ *    1.0.1       png.h string is   10001  2.1.0
+ *    1.0.1a-e    identical to the  10002  from here on, the shared library
+ *    1.0.2       source version)   10002  is 2.V where V is the source code
+ *    1.0.2a-b                      10003  version, except as noted.
+ *    1.0.3                         10003
+ *    1.0.3a-d                      10004
+ *    1.0.4                         10004
+ *    1.0.4a-f                      10005
+ *    1.0.5 (+ 2 patches)           10005
+ *    1.0.5a-d                      10006
+ *    1.0.5e-r                      10100 (not source compatible)
+ *    1.0.5s-v                      10006 (not binary compatible)
+ *    1.0.6 (+ 3 patches)           10006 (still binary incompatible)
+ *    1.0.6d-f                      10007 (still binary incompatible)
+ *    1.0.6g                        10007
+ *    1.0.6h                        10007  10.6h (testing xy.z so-numbering)
+ *    1.0.6i                        10007  10.6i
+ *    1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)
+ *    1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)
+ *    1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)
+ *    1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
+ *    1.0.7                    1    10007  (still compatible)
+ *    1.0.8beta1-4             1    10008  2.1.0.8beta1-4
+ *    1.0.8rc1                 1    10008  2.1.0.8rc1
+ *    1.0.8                    1    10008  2.1.0.8
+ *    1.0.9beta1-6             1    10009  2.1.0.9beta1-6
+ *    1.0.9rc1                 1    10009  2.1.0.9rc1
+ *    1.0.9beta7-10            1    10009  2.1.0.9beta7-10
+ *    1.0.9rc2                 1    10009  2.1.0.9rc2
+ *    1.0.9                    1    10009  2.1.0.9
+ *    1.0.10beta1              1    10010  2.1.0.10beta1
+ *    1.0.10rc1                1    10010  2.1.0.10rc1
+ *    1.0.10                   1    10010  2.1.0.10
+ *    1.0.11beta1-3            1    10011  2.1.0.11beta1-3
+ *    1.0.11rc1                1    10011  2.1.0.11rc1
+ *    1.0.11                   1    10011  2.1.0.11
+ *    1.0.12beta1-2            2    10012  2.1.0.12beta1-2
+ *    1.0.12rc1                2    10012  2.1.0.12rc1
+ *    1.0.12                   2    10012  2.1.0.12
+ *    1.1.0a-f                 -    10100  2.1.1.0a-f (branch abandoned)
+ *    1.2.0beta1-2             2    10200  2.1.2.0beta1-2
+ *    1.2.0beta3-5             3    10200  3.1.2.0beta3-5
+ *    1.2.0rc1                 3    10200  3.1.2.0rc1
+ *    1.2.0                    3    10200  3.1.2.0
+ *    1.2.1beta1-4             3    10201  3.1.2.1beta1-4
+ *    1.2.1rc1-2               3    10201  3.1.2.1rc1-2
+ *    1.2.1                    3    10201  3.1.2.1
+ *    1.2.2beta1-6            12    10202  12.so.0.1.2.2beta1-6
+ *    1.0.13beta1             10    10013  10.so.0.1.0.13beta1
+ *    1.0.13rc1               10    10013  10.so.0.1.0.13rc1
+ *    1.2.2rc1                12    10202  12.so.0.1.2.2rc1
+ *    1.0.13                  10    10013  10.so.0.1.0.13
+ *    1.2.2                   12    10202  12.so.0.1.2.2
+ *    1.2.3rc1-6              12    10203  12.so.0.1.2.3rc1-6
+ *    1.2.3                   12    10203  12.so.0.1.2.3
+ *    1.2.4beta1-3            13    10204  12.so.0.1.2.4beta1-3
+ *    1.0.14rc1               13    10014  10.so.0.1.0.14rc1
+ *    1.2.4rc1                13    10204  12.so.0.1.2.4rc1
+ *    1.0.14                  10    10014  10.so.0.1.0.14
+ *    1.2.4                   13    10204  12.so.0.1.2.4
+ *    1.2.5beta1-2            13    10205  12.so.0.1.2.5beta1-2
+ *    1.0.15rc1-3             10    10015  10.so.0.1.0.15rc1-3
+ *    1.2.5rc1-3              13    10205  12.so.0.1.2.5rc1-3
+ *    1.0.15                  10    10015  10.so.0.1.0.15
+ *    1.2.5                   13    10205  12.so.0.1.2.5
+ *    1.2.6beta1-4            13    10206  12.so.0.1.2.6beta1-4
+ *    1.0.16                  10    10016  10.so.0.1.0.16
+ *    1.2.6                   13    10206  12.so.0.1.2.6
+ *    1.2.7beta1-2            13    10207  12.so.0.1.2.7beta1-2
+ *    1.0.17rc1               10    10017  12.so.0.1.0.17rc1
+ *    1.2.7rc1                13    10207  12.so.0.1.2.7rc1
+ *    1.0.17                  10    10017  12.so.0.1.0.17
+ *    1.2.7                   13    10207  12.so.0.1.2.7
+ *    1.2.8beta1-5            13    10208  12.so.0.1.2.8beta1-5
+ *    1.0.18rc1-5             10    10018  12.so.0.1.0.18rc1-5
+ *    1.2.8rc1-5              13    10208  12.so.0.1.2.8rc1-5
+ *    1.0.18                  10    10018  12.so.0.1.0.18
+ *    1.2.8                   13    10208  12.so.0.1.2.8
+ *
+ *    Henceforth the source version will match the shared-library major
+ *    and minor numbers; the shared-library major version number will be
+ *    used for changes in backward compatibility, as it is intended.  The
+ *    PNG_LIBPNG_VER macro, which is not used within libpng but is available
+ *    for applications, is an unsigned integer of the form xyyzz corresponding
+ *    to the source version x.y.z (leading zeros in y and z).  Beta versions
+ *    were given the previous public release number plus a letter, until
+ *    version 1.0.6j; from then on they were given the upcoming public
+ *    release number plus "betaNN" or "rcN".
+ *
+ *    Binary incompatibility exists only when applications make direct access
+ *    to the info_ptr or png_ptr members through png.h, and the compiled
+ *    application is loaded with a different version of the library.
+ *
+ *    DLLNUM will change each time there are forward or backward changes
+ *    in binary compatibility (e.g., when a new feature is added).
+ *
+ * See libpng.txt or libpng.3 for more information.  The PNG specification
+ * is available as a W3C Recommendation and as an ISO Specification,
+ * <http://www.w3.org/TR/2003/REC-PNG-20031110/
+ */
+
+/*
+ * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
+ *
+ * If you modify libpng you may insert additional notices immediately following
+ * this sentence.
+ *
+ * libpng versions 1.2.6, August 15, 2004, through 1.2.8, December 3, 2004, are
+ * Copyright (c) 2004 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.2.5
+ * with the following individual added to the list of Contributing Authors:
+ *
+ *    Cosmin Truta
+ *
+ * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
+ * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.0.6
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Simon-Pierre Cadieux
+ *    Eric S. Raymond
+ *    Gilles Vollant
+ *
+ * and with the following additions to the disclaimer:
+ *
+ *    There is no warranty against interference with your enjoyment of the
+ *    library or against infringement.  There is no warranty that our
+ *    efforts or the library will fulfill any of your particular purposes
+ *    or needs.  This library is provided with all faults, and the entire
+ *    risk of satisfactory quality, performance, accuracy, and effort is with
+ *    the user.
+ *
+ * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+ * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-0.96,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Tom Lane
+ *    Glenn Randers-Pehrson
+ *    Willem van Schaik
+ *
+ * libpng versions 0.89, June 1996, through 0.96, May 1997, are
+ * Copyright (c) 1996, 1997 Andreas Dilger
+ * Distributed according to the same disclaimer and license as libpng-0.88,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    John Bowler
+ *    Kevin Bracey
+ *    Sam Bushell
+ *    Magnus Holmgren
+ *    Greg Roelofs
+ *    Tom Tanner
+ *
+ * libpng versions 0.5, May 1995, through 0.88, January 1996, are
+ * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+ *
+ * For the purposes of this copyright and license, "Contributing Authors"
+ * is defined as the following set of individuals:
+ *
+ *    Andreas Dilger
+ *    Dave Martindale
+ *    Guy Eric Schalnat
+ *    Paul Schmidt
+ *    Tim Wegner
+ *
+ * The PNG Reference Library is supplied "AS IS".  The Contributing Authors
+ * and Group 42, Inc. disclaim all warranties, expressed or implied,
+ * including, without limitation, the warranties of merchantability and of
+ * fitness for any purpose.  The Contributing Authors and Group 42, Inc.
+ * assume no liability for direct, indirect, incidental, special, exemplary,
+ * or consequential damages, which may result from the use of the PNG
+ * Reference Library, even if advised of the possibility of such damage.
+ *
+ * Permission is hereby granted to use, copy, modify, and distribute this
+ * source code, or portions hereof, for any purpose, without fee, subject
+ * to the following restrictions:
+ *
+ * 1. The origin of this source code must not be misrepresented.
+ *
+ * 2. Altered versions must be plainly marked as such and
+ * must not be misrepresented as being the original source.
+ *
+ * 3. This Copyright notice may not be removed or altered from
+ *    any source or altered source distribution.
+ *
+ * The Contributing Authors and Group 42, Inc. specifically permit, without
+ * fee, and encourage the use of this source code as a component to
+ * supporting the PNG file format in commercial products.  If you use this
+ * source code in a product, acknowledgment is not required but would be
+ * appreciated.
+ */
+
+/*
+ * A "png_get_copyright" function is available, for convenient use in "about"
+ * boxes and the like:
+ *
+ * printf("%s",png_get_copyright(NULL));
+ *
+ * Also, the PNG logo (in PNG format, of course) is supplied in the
+ * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
+ */
+
+/*
+ * Libpng is OSI Certified Open Source Software.  OSI Certified is a
+ * certification mark of the Open Source Initiative.
+ */
+
+/*
+ * The contributing authors would like to thank all those who helped
+ * with testing, bug fixes, and patience.  This wouldn't have been
+ * possible without all of you.
+ *
+ * Thanks to Frank J. T. Wojcik for helping with the documentation.
+ */
+
+/*
+ * Y2K compliance in libpng:
+ * =========================
+ *
+ *    December 3, 2004
+ *
+ *    Since the PNG Development group is an ad-hoc body, we can't make
+ *    an official declaration.
+ *
+ *    This is your unofficial assurance that libpng from version 0.71 and
+ *    upward through 1.2.8 are Y2K compliant.  It is my belief that earlier
+ *    versions were also Y2K compliant.
+ *
+ *    Libpng only has three year fields.  One is a 2-byte unsigned integer
+ *    that will hold years up to 65535.  The other two hold the date in text
+ *    format, and will hold years up to 9999.
+ *
+ *    The integer is
+ *        "png_uint_16 year" in png_time_struct.
+ *
+ *    The strings are
+ *        "png_charp time_buffer" in png_struct and
+ *        "near_time_buffer", which is a local character string in png.c.
+ *
+ *    There are seven time-related functions:
+ *        png.c: png_convert_to_rfc_1123() in png.c
+ *          (formerly png_convert_to_rfc_1152() in error)
+ *        png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
+ *        png_convert_from_time_t() in pngwrite.c
+ *        png_get_tIME() in pngget.c
+ *        png_handle_tIME() in pngrutil.c, called in pngread.c
+ *        png_set_tIME() in pngset.c
+ *        png_write_tIME() in pngwutil.c, called in pngwrite.c
+ *
+ *    All handle dates properly in a Y2K environment.  The
+ *    png_convert_from_time_t() function calls gmtime() to convert from system
+ *    clock time, which returns (year - 1900), which we properly convert to
+ *    the full 4-digit year.  There is a possibility that applications using
+ *    libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
+ *    function, or that they are incorrectly passing only a 2-digit year
+ *    instead of "year - 1900" into the png_convert_from_struct_tm() function,
+ *    but this is not under our control.  The libpng documentation has always
+ *    stated that it works with 4-digit years, and the APIs have been
+ *    documented as such.
+ *
+ *    The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
+ *    integer to hold the year, and can hold years as large as 65535.
+ *
+ *    zlib, upon which libpng depends, is also Y2K compliant.  It contains
+ *    no date-related code.
+ *
+ *       Glenn Randers-Pehrson
+ *       libpng maintainer
+ *       PNG Development Group
+ */
+
+#ifndef PNG_H
+#define PNG_H
+
+/* This is not the place to learn how to use libpng.  The file libpng.txt
+ * describes how to use libpng, and the file example.c summarizes it
+ * with some code on which to build.  This file is useful for looking
+ * at the actual function definitions and structure components.
+ */
+
+/* Version information for png.h - this should match the version in png.c */
+#define PNG_LIBPNG_VER_STRING "1.2.8"
+#define PNG_HEADER_VERSION_STRING \
+   " libpng version 1.2.8 - December 3, 2004 (header)\n"
+
+#define PNG_LIBPNG_VER_SONUM   0
+#define PNG_LIBPNG_VER_DLLNUM  13
+
+/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
+#define PNG_LIBPNG_VER_MAJOR   1
+#define PNG_LIBPNG_VER_MINOR   2
+#define PNG_LIBPNG_VER_RELEASE 8
+/* This should match the numeric part of the final component of
+ * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
+
+#define PNG_LIBPNG_VER_BUILD  0
+
+/* Release Status */
+#define PNG_LIBPNG_BUILD_ALPHA    1
+#define PNG_LIBPNG_BUILD_BETA     2
+#define PNG_LIBPNG_BUILD_RC       3
+#define PNG_LIBPNG_BUILD_STABLE   4
+#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
+  
+/* Release-Specific Flags */
+#define PNG_LIBPNG_BUILD_PATCH    8 /* Can be OR'ed with
+                                       PNG_LIBPNG_BUILD_STABLE only */
+#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_SPECIAL */
+#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_PRIVATE */
+
+#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
+
+/* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
+ * We must not include leading zeros.
+ * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
+ * version 1.0.0 was mis-numbered 100 instead of 10000).  From
+ * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release */
+#define PNG_LIBPNG_VER 10208 /* 1.2.8 */
+
+#ifndef PNG_VERSION_INFO_ONLY
+/* include the compression library's header */
+#include "zlib.h"
+#endif
+
+/* include all user configurable info, including optional assembler routines */
+#include "pngconf.h"
+
+/*
+ * Added at libpng-1.2.8 */
+/* Ref MSDN: Private as priority over Special
+ * VS_FF_PRIVATEBUILD File *was not* built using standard release
+ * procedures. If this value is given, the StringFileInfo block must
+ * contain a PrivateBuild string. 
+ *
+ * VS_FF_SPECIALBUILD File *was* built by the original company using
+ * standard release procedures but is a variation of the standard
+ * file of the same version number. If this value is given, the
+ * StringFileInfo block must contain a SpecialBuild string. 
+ */
+
+#if defined(PNG_USER_PRIVATEBUILD)
+#  define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE | \
+          PNG_LIBPNG_BUILD_PRIVATE
+#else
+#  if defined(PNG_LIBPNG_SPECIALBUILD)
+#    define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE | \
+            PNG_LIBPNG_BUILD_SPECIAL
+#  else
+#    define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE
+#  endif
+#endif
+
+#ifndef PNG_VERSION_INFO_ONLY
+
+/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* This file is arranged in several sections.  The first section contains
+ * structure and type definitions.  The second section contains the external
+ * library functions, while the third has the internal library functions,
+ * which applications aren't expected to use directly.
+ */
+
+#ifndef PNG_NO_TYPECAST_NULL
+#define int_p_NULL                (int *)NULL
+#define png_bytep_NULL            (png_bytep)NULL
+#define png_bytepp_NULL           (png_bytepp)NULL
+#define png_doublep_NULL          (png_doublep)NULL
+#define png_error_ptr_NULL        (png_error_ptr)NULL
+#define png_flush_ptr_NULL        (png_flush_ptr)NULL
+#define png_free_ptr_NULL         (png_free_ptr)NULL
+#define png_infopp_NULL           (png_infopp)NULL
+#define png_malloc_ptr_NULL       (png_malloc_ptr)NULL
+#define png_read_status_ptr_NULL  (png_read_status_ptr)NULL
+#define png_rw_ptr_NULL           (png_rw_ptr)NULL
+#define png_structp_NULL          (png_structp)NULL
+#define png_uint_16p_NULL         (png_uint_16p)NULL
+#define png_voidp_NULL            (png_voidp)NULL
+#define png_write_status_ptr_NULL (png_write_status_ptr)NULL
+#else
+#define int_p_NULL                NULL
+#define png_bytep_NULL            NULL
+#define png_bytepp_NULL           NULL
+#define png_doublep_NULL          NULL
+#define png_error_ptr_NULL        NULL
+#define png_flush_ptr_NULL        NULL
+#define png_free_ptr_NULL         NULL
+#define png_infopp_NULL           NULL
+#define png_malloc_ptr_NULL       NULL
+#define png_read_status_ptr_NULL  NULL
+#define png_rw_ptr_NULL           NULL
+#define png_structp_NULL          NULL
+#define png_uint_16p_NULL         NULL
+#define png_voidp_NULL            NULL
+#define png_write_status_ptr_NULL NULL
+#endif
+
+/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
+#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
+/* Version information for C files, stored in png.c.  This had better match
+ * the version above.
+ */
+#ifdef PNG_USE_GLOBAL_ARRAYS
+PNG_EXPORT_VAR (const char) png_libpng_ver[18];
+  /* need room for 99.99.99beta99z */
+#else
+#define png_libpng_ver png_get_header_ver(NULL)
+#endif
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+/* This was removed in version 1.0.5c */
+/* Structures to facilitate easy interlacing.  See png.c for more details */
+PNG_EXPORT_VAR (const int FARDATA) png_pass_start[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_inc[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_ystart[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_yinc[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_mask[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_dsp_mask[7];
+#ifdef PNG_HAVE_ASSEMBLER_COMBINE_ROW
+PNG_EXPORT_VAR (const int FARDATA) png_pass_width[7];
+#endif
+/* This isn't currently used.  If you need it, see png.c for more details.
+PNG_EXPORT_VAR (const int FARDATA) png_pass_height[7];
+*/
+#endif
+
+#endif /* PNG_NO_EXTERN */
+
+/* Three color definitions.  The order of the red, green, and blue, (and the
+ * exact size) is not important, although the size of the fields need to
+ * be png_byte or png_uint_16 (as defined below).
+ */
+typedef struct png_color_struct
+{
+   png_byte red;
+   png_byte green;
+   png_byte blue;
+} png_color;
+typedef png_color FAR * png_colorp;
+typedef png_color FAR * FAR * png_colorpp;
+
+typedef struct png_color_16_struct
+{
+   png_byte index;    /* used for palette files */
+   png_uint_16 red;   /* for use in red green blue files */
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 gray;  /* for use in grayscale files */
+} png_color_16;
+typedef png_color_16 FAR * png_color_16p;
+typedef png_color_16 FAR * FAR * png_color_16pp;
+
+typedef struct png_color_8_struct
+{
+   png_byte red;   /* for use in red green blue files */
+   png_byte green;
+   png_byte blue;
+   png_byte gray;  /* for use in grayscale files */
+   png_byte alpha; /* for alpha channel files */
+} png_color_8;
+typedef png_color_8 FAR * png_color_8p;
+typedef png_color_8 FAR * FAR * png_color_8pp;
+
+/*
+ * The following two structures are used for the in-core representation
+ * of sPLT chunks.
+ */
+typedef struct png_sPLT_entry_struct
+{
+   png_uint_16 red;
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 alpha;
+   png_uint_16 frequency;
+} png_sPLT_entry;
+typedef png_sPLT_entry FAR * png_sPLT_entryp;
+typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
+
+/*  When the depth of the sPLT palette is 8 bits, the color and alpha samples
+ *  occupy the LSB of their respective members, and the MSB of each member
+ *  is zero-filled.  The frequency member always occupies the full 16 bits.
+ */
+
+typedef struct png_sPLT_struct
+{
+   png_charp name;           /* palette name */
+   png_byte depth;           /* depth of palette samples */
+   png_sPLT_entryp entries;  /* palette entries */
+   png_int_32 nentries;      /* number of palette entries */
+} png_sPLT_t;
+typedef png_sPLT_t FAR * png_sPLT_tp;
+typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
+
+#ifdef PNG_TEXT_SUPPORTED
+/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
+ * and whether that contents is compressed or not.  The "key" field
+ * points to a regular zero-terminated C string.  The "text", "lang", and
+ * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
+ * However, the * structure returned by png_get_text() will always contain
+ * regular zero-terminated C strings (possibly empty), never NULL pointers,
+ * so they can be safely used in printf() and other string-handling functions.
+ */
+typedef struct png_text_struct
+{
+   int  compression;       /* compression value:
+                             -1: tEXt, none
+                              0: zTXt, deflate
+                              1: iTXt, none
+                              2: iTXt, deflate  */
+   png_charp key;          /* keyword, 1-79 character description of "text" */
+   png_charp text;         /* comment, may be an empty string (ie "")
+                              or a NULL pointer */
+   png_size_t text_length; /* length of the text string */
+#ifdef PNG_iTXt_SUPPORTED
+   png_size_t itxt_length; /* length of the itxt string */
+   png_charp lang;         /* language code, 0-79 characters
+                              or a NULL pointer */
+   png_charp lang_key;     /* keyword translated UTF-8 string, 0 or more
+                              chars or a NULL pointer */
+#endif
+} png_text;
+typedef png_text FAR * png_textp;
+typedef png_text FAR * FAR * png_textpp;
+#endif
+
+/* Supported compression types for text in PNG files (tEXt, and zTXt).
+ * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
+#define PNG_TEXT_COMPRESSION_NONE_WR -3
+#define PNG_TEXT_COMPRESSION_zTXt_WR -2
+#define PNG_TEXT_COMPRESSION_NONE    -1
+#define PNG_TEXT_COMPRESSION_zTXt     0
+#define PNG_ITXT_COMPRESSION_NONE     1
+#define PNG_ITXT_COMPRESSION_zTXt     2
+#define PNG_TEXT_COMPRESSION_LAST     3  /* Not a valid value */
+
+/* png_time is a way to hold the time in an machine independent way.
+ * Two conversions are provided, both from time_t and struct tm.  There
+ * is no portable way to convert to either of these structures, as far
+ * as I know.  If you know of a portable way, send it to me.  As a side
+ * note - PNG has always been Year 2000 compliant!
+ */
+typedef struct png_time_struct
+{
+   png_uint_16 year; /* full year, as in, 1995 */
+   png_byte month;   /* month of year, 1 - 12 */
+   png_byte day;     /* day of month, 1 - 31 */
+   png_byte hour;    /* hour of day, 0 - 23 */
+   png_byte minute;  /* minute of hour, 0 - 59 */
+   png_byte second;  /* second of minute, 0 - 60 (for leap seconds) */
+} png_time;
+typedef png_time FAR * png_timep;
+typedef png_time FAR * FAR * png_timepp;
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+/* png_unknown_chunk is a structure to hold queued chunks for which there is
+ * no specific support.  The idea is that we can use this to queue
+ * up private chunks for output even though the library doesn't actually
+ * know about their semantics.
+ */
+typedef struct png_unknown_chunk_t
+{
+    png_byte name[5];
+    png_byte *data;
+    png_size_t size;
+
+    /* libpng-using applications should NOT directly modify this byte. */
+    png_byte location; /* mode of operation at read time */
+}
+png_unknown_chunk;
+typedef png_unknown_chunk FAR * png_unknown_chunkp;
+typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
+#endif
+
+/* png_info is a structure that holds the information in a PNG file so
+ * that the application can find out the characteristics of the image.
+ * If you are reading the file, this structure will tell you what is
+ * in the PNG file.  If you are writing the file, fill in the information
+ * you want to put into the PNG file, then call png_write_info().
+ * The names chosen should be very close to the PNG specification, so
+ * consult that document for information about the meaning of each field.
+ *
+ * With libpng < 0.95, it was only possible to directly set and read the
+ * the values in the png_info_struct, which meant that the contents and
+ * order of the values had to remain fixed.  With libpng 0.95 and later,
+ * however, there are now functions that abstract the contents of
+ * png_info_struct from the application, so this makes it easier to use
+ * libpng with dynamic libraries, and even makes it possible to use
+ * libraries that don't have all of the libpng ancillary chunk-handing
+ * functionality.
+ *
+ * In any case, the order of the parameters in png_info_struct should NOT
+ * be changed for as long as possible to keep compatibility with applications
+ * that use the old direct-access method with png_info_struct.
+ *
+ * The following members may have allocated storage attached that should be
+ * cleaned up before the structure is discarded: palette, trans, text,
+ * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
+ * splt_palettes, scal_unit, row_pointers, and unknowns.   By default, these
+ * are automatically freed when the info structure is deallocated, if they were
+ * allocated internally by libpng.  This behavior can be changed by means
+ * of the png_data_freer() function.
+ *
+ * More allocation details: all the chunk-reading functions that
+ * change these members go through the corresponding png_set_*
+ * functions.  A function to clear these members is available: see
+ * png_free_data().  The png_set_* functions do not depend on being
+ * able to point info structure members to any of the storage they are
+ * passed (they make their own copies), EXCEPT that the png_set_text
+ * functions use the same storage passed to them in the text_ptr or
+ * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
+ * functions do not make their own copies.
+ */
+typedef struct png_info_struct
+{
+   /* the following are necessary for every PNG file */
+   png_uint_32 width;       /* width of image in pixels (from IHDR) */
+   png_uint_32 height;      /* height of image in pixels (from IHDR) */
+   png_uint_32 valid;       /* valid chunk data (see PNG_INFO_ below) */
+   png_uint_32 rowbytes;    /* bytes needed to hold an untransformed row */
+   png_colorp palette;      /* array of color values (valid & PNG_INFO_PLTE) */
+   png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
+   png_uint_16 num_trans;   /* number of transparent palette color (tRNS) */
+   png_byte bit_depth;      /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
+   png_byte color_type;     /* see PNG_COLOR_TYPE_ below (from IHDR) */
+   /* The following three should have been named *_method not *_type */
+   png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
+   png_byte filter_type;    /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
+   png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+
+   /* The following is informational only on read, and not used on writes. */
+   png_byte channels;       /* number of data channels per pixel (1, 2, 3, 4) */
+   png_byte pixel_depth;    /* number of bits per pixel */
+   png_byte spare_byte;     /* to align the data, and for future use */
+   png_byte signature[8];   /* magic bytes read by libpng from start of file */
+
+   /* The rest of the data is optional.  If you are reading, check the
+    * valid field to see if the information in these are valid.  If you
+    * are writing, set the valid field to those chunks you want written,
+    * and initialize the appropriate fields below.
+    */
+
+#if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
+   /* The gAMA chunk describes the gamma characteristics of the system
+    * on which the image was created, normally in the range [1.0, 2.5].
+    * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
+    */
+   float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+    /* GR-P, 0.96a */
+    /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
+   png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)
+   /* The tEXt, and zTXt chunks contain human-readable textual data in
+    * uncompressed, compressed, and optionally compressed forms, respectively.
+    * The data in "text" is an array of pointers to uncompressed,
+    * null-terminated C strings. Each chunk has a keyword that describes the
+    * textual data contained in that chunk.  Keywords are not required to be
+    * unique, and the text string may be empty.  Any number of text chunks may
+    * be in an image.
+    */
+   int num_text; /* number of comments read/to write */
+   int max_text; /* current size of text array */
+   png_textp text; /* array of comments read/to write */
+#endif /* PNG_TEXT_SUPPORTED */
+
+#if defined(PNG_tIME_SUPPORTED)
+   /* The tIME chunk holds the last time the displayed image data was
+    * modified.  See the png_time struct for the contents of this struct.
+    */
+   png_time mod_time;
+#endif
+
+#if defined(PNG_sBIT_SUPPORTED)
+   /* The sBIT chunk specifies the number of significant high-order bits
+    * in the pixel data.  Values are in the range [1, bit_depth], and are
+    * only specified for the channels in the pixel data.  The contents of
+    * the low-order bits is not specified.  Data is valid if
+    * (valid & PNG_INFO_sBIT) is non-zero.
+    */
+   png_color_8 sig_bit; /* significant bits in color channels */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
+defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The tRNS chunk supplies transparency data for paletted images and
+    * other image types that don't need a full alpha channel.  There are
+    * "num_trans" transparency values for a paletted image, stored in the
+    * same order as the palette colors, starting from index 0.  Values
+    * for the data are in the range [0, 255], ranging from fully transparent
+    * to fully opaque, respectively.  For non-paletted images, there is a
+    * single color specified that should be treated as fully transparent.
+    * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
+    */
+   png_bytep trans; /* transparent values for paletted image */
+   png_color_16 trans_values; /* transparent color for non-palette image */
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The bKGD chunk gives the suggested image background color if the
+    * display program does not have its own background color and the image
+    * is needs to composited onto a background before display.  The colors
+    * in "background" are normally in the same color space/depth as the
+    * pixel data.  Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
+    */
+   png_color_16 background;
+#endif
+
+#if defined(PNG_oFFs_SUPPORTED)
+   /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
+    * and downwards from the top-left corner of the display, page, or other
+    * application-specific co-ordinate space.  See the PNG_OFFSET_ defines
+    * below for the unit types.  Valid if (valid & PNG_INFO_oFFs) non-zero.
+    */
+   png_int_32 x_offset; /* x offset on page */
+   png_int_32 y_offset; /* y offset on page */
+   png_byte offset_unit_type; /* offset units type */
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+   /* The pHYs chunk gives the physical pixel density of the image for
+    * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
+    * defines below).  Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
+    */
+   png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
+   png_uint_32 y_pixels_per_unit; /* vertical pixel density */
+   png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+   /* The hIST chunk contains the relative frequency or importance of the
+    * various palette entries, so that a viewer can intelligently select a
+    * reduced-color palette, if required.  Data is an array of "num_palette"
+    * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
+    * is non-zero.
+    */
+   png_uint_16p hist;
+#endif
+
+#ifdef PNG_cHRM_SUPPORTED
+   /* The cHRM chunk describes the CIE color characteristics of the monitor
+    * on which the PNG was created.  This data allows the viewer to do gamut
+    * mapping of the input image to ensure that the viewer sees the same
+    * colors in the image as the creator.  Values are in the range
+    * [0.0, 0.8].  Data valid if (valid & PNG_INFO_cHRM) non-zero.
+    */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   float x_white;
+   float y_white;
+   float x_red;
+   float y_red;
+   float x_green;
+   float y_green;
+   float x_blue;
+   float y_blue;
+#endif
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+   /* The pCAL chunk describes a transformation between the stored pixel
+    * values and original physical data values used to create the image.
+    * The integer range [0, 2^bit_depth - 1] maps to the floating-point
+    * range given by [pcal_X0, pcal_X1], and are further transformed by a
+    * (possibly non-linear) transformation function given by "pcal_type"
+    * and "pcal_params" into "pcal_units".  Please see the PNG_EQUATION_
+    * defines below, and the PNG-Group's PNG extensions document for a
+    * complete description of the transformations and how they should be
+    * implemented, and for a description of the ASCII parameter strings.
+    * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
+    */
+   png_charp pcal_purpose;  /* pCAL chunk description string */
+   png_int_32 pcal_X0;      /* minimum value */
+   png_int_32 pcal_X1;      /* maximum value */
+   png_charp pcal_units;    /* Latin-1 string giving physical units */
+   png_charpp pcal_params;  /* ASCII strings containing parameter values */
+   png_byte pcal_type;      /* equation type (see PNG_EQUATION_ below) */
+   png_byte pcal_nparams;   /* number of parameters given in pcal_params */
+#endif
+
+/* New members added in libpng-1.0.6 */
+#ifdef PNG_FREE_ME_SUPPORTED
+   png_uint_32 free_me;     /* flags items libpng is responsible for freeing */
+#endif
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+   /* storage for unknown chunks that the library doesn't recognize. */
+   png_unknown_chunkp unknown_chunks;
+   png_size_t unknown_chunks_num;
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+   /* iCCP chunk data. */
+   png_charp iccp_name;     /* profile name */
+   png_charp iccp_profile;  /* International Color Consortium profile data */
+                            /* Note to maintainer: should be png_bytep */
+   png_uint_32 iccp_proflen;  /* ICC profile data length */
+   png_byte iccp_compression; /* Always zero */
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+   /* data on sPLT chunks (there may be more than one). */
+   png_sPLT_tp splt_palettes;
+   png_uint_32 splt_palettes_num;
+#endif
+
+#if defined(PNG_sCAL_SUPPORTED)
+   /* The sCAL chunk describes the actual physical dimensions of the
+    * subject matter of the graphic.  The chunk contains a unit specification
+    * a byte value, and two ASCII strings representing floating-point
+    * values.  The values are width and height corresponsing to one pixel
+    * in the image.  This external representation is converted to double
+    * here.  Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
+    */
+   png_byte scal_unit;         /* unit of physical scale */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   double scal_pixel_width;    /* width of one pixel */
+   double scal_pixel_height;   /* height of one pixel */
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+   png_charp scal_s_width;     /* string containing height */
+   png_charp scal_s_height;    /* string containing width */
+#endif
+#endif
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+   /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
+   /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
+   png_bytepp row_pointers;        /* the image bits */
+#endif
+
+#if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
+   png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
+   png_fixed_point int_x_white;
+   png_fixed_point int_y_white;
+   png_fixed_point int_x_red;
+   png_fixed_point int_y_red;
+   png_fixed_point int_x_green;
+   png_fixed_point int_y_green;
+   png_fixed_point int_x_blue;
+   png_fixed_point int_y_blue;
+#endif
+
+} png_info;
+
+typedef png_info FAR * png_infop;
+typedef png_info FAR * FAR * png_infopp;
+
+/* Maximum positive integer used in PNG is (2^31)-1 */
+#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
+#define PNG_UINT_32_MAX ((png_uint_32)(-1))
+#define PNG_SIZE_MAX ((png_size_t)(-1))
+/* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
+#define PNG_MAX_UINT PNG_UINT_31_MAX
+
+/* These describe the color_type field in png_info. */
+/* color type masks */
+#define PNG_COLOR_MASK_PALETTE    1
+#define PNG_COLOR_MASK_COLOR      2
+#define PNG_COLOR_MASK_ALPHA      4
+
+/* color types.  Note that not all combinations are legal */
+#define PNG_COLOR_TYPE_GRAY 0
+#define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
+#define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
+#define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
+#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
+/* aliases */
+#define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
+#define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
+
+/* This is for compression type. PNG 1.0-1.2 only define the single type. */
+#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
+#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
+
+/* This is for filter type. PNG 1.0-1.2 only define the single type. */
+#define PNG_FILTER_TYPE_BASE      0 /* Single row per-byte filtering */
+#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
+#define PNG_FILTER_TYPE_DEFAULT   PNG_FILTER_TYPE_BASE
+
+/* These are for the interlacing type.  These values should NOT be changed. */
+#define PNG_INTERLACE_NONE        0 /* Non-interlaced image */
+#define PNG_INTERLACE_ADAM7       1 /* Adam7 interlacing */
+#define PNG_INTERLACE_LAST        2 /* Not a valid value */
+
+/* These are for the oFFs chunk.  These values should NOT be changed. */
+#define PNG_OFFSET_PIXEL          0 /* Offset in pixels */
+#define PNG_OFFSET_MICROMETER     1 /* Offset in micrometers (1/10^6 meter) */
+#define PNG_OFFSET_LAST           2 /* Not a valid value */
+
+/* These are for the pCAL chunk.  These values should NOT be changed. */
+#define PNG_EQUATION_LINEAR       0 /* Linear transformation */
+#define PNG_EQUATION_BASE_E       1 /* Exponential base e transform */
+#define PNG_EQUATION_ARBITRARY    2 /* Arbitrary base exponential transform */
+#define PNG_EQUATION_HYPERBOLIC   3 /* Hyperbolic sine transformation */
+#define PNG_EQUATION_LAST         4 /* Not a valid value */
+
+/* These are for the sCAL chunk.  These values should NOT be changed. */
+#define PNG_SCALE_UNKNOWN         0 /* unknown unit (image scale) */
+#define PNG_SCALE_METER           1 /* meters per pixel */
+#define PNG_SCALE_RADIAN          2 /* radians per pixel */
+#define PNG_SCALE_LAST            3 /* Not a valid value */
+
+/* These are for the pHYs chunk.  These values should NOT be changed. */
+#define PNG_RESOLUTION_UNKNOWN    0 /* pixels/unknown unit (aspect ratio) */
+#define PNG_RESOLUTION_METER      1 /* pixels/meter */
+#define PNG_RESOLUTION_LAST       2 /* Not a valid value */
+
+/* These are for the sRGB chunk.  These values should NOT be changed. */
+#define PNG_sRGB_INTENT_PERCEPTUAL 0
+#define PNG_sRGB_INTENT_RELATIVE   1
+#define PNG_sRGB_INTENT_SATURATION 2
+#define PNG_sRGB_INTENT_ABSOLUTE   3
+#define PNG_sRGB_INTENT_LAST       4 /* Not a valid value */
+
+/* This is for text chunks */
+#define PNG_KEYWORD_MAX_LENGTH     79
+
+/* Maximum number of entries in PLTE/sPLT/tRNS arrays */
+#define PNG_MAX_PALETTE_LENGTH    256
+
+/* These determine if an ancillary chunk's data has been successfully read
+ * from the PNG header, or if the application has filled in the corresponding
+ * data in the info_struct to be written into the output file.  The values
+ * of the PNG_INFO_<chunk> defines should NOT be changed.
+ */
+#define PNG_INFO_gAMA 0x0001
+#define PNG_INFO_sBIT 0x0002
+#define PNG_INFO_cHRM 0x0004
+#define PNG_INFO_PLTE 0x0008
+#define PNG_INFO_tRNS 0x0010
+#define PNG_INFO_bKGD 0x0020
+#define PNG_INFO_hIST 0x0040
+#define PNG_INFO_pHYs 0x0080
+#define PNG_INFO_oFFs 0x0100
+#define PNG_INFO_tIME 0x0200
+#define PNG_INFO_pCAL 0x0400
+#define PNG_INFO_sRGB 0x0800   /* GR-P, 0.96a */
+#define PNG_INFO_iCCP 0x1000   /* ESR, 1.0.6 */
+#define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
+#define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
+#define PNG_INFO_IDAT 0x8000L  /* ESR, 1.0.6 */
+
+/* This is used for the transformation routines, as some of them
+ * change these values for the row.  It also should enable using
+ * the routines for other purposes.
+ */
+typedef struct png_row_info_struct
+{
+   png_uint_32 width; /* width of row */
+   png_uint_32 rowbytes; /* number of bytes in row */
+   png_byte color_type; /* color type of row */
+   png_byte bit_depth; /* bit depth of row */
+   png_byte channels; /* number of channels (1, 2, 3, or 4) */
+   png_byte pixel_depth; /* bits per pixel (depth * channels) */
+} png_row_info;
+
+typedef png_row_info FAR * png_row_infop;
+typedef png_row_info FAR * FAR * png_row_infopp;
+
+/* These are the function types for the I/O functions and for the functions
+ * that allow the user to override the default I/O functions with his or her
+ * own.  The png_error_ptr type should match that of user-supplied warning
+ * and error functions, while the png_rw_ptr type should match that of the
+ * user read/write data functions.
+ */
+typedef struct png_struct_def png_struct;
+typedef png_struct FAR * png_structp;
+
+typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
+typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
+typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
+typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
+   int));
+typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
+   int));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
+typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
+typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
+   png_uint_32, int));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
+    png_row_infop, png_bytep));
+#endif
+
+#if defined(PNG_USER_CHUNKS_SUPPORTED)
+typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
+#endif
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
+#endif
+
+/* Transform masks for the high-level interface */
+#define PNG_TRANSFORM_IDENTITY       0x0000    /* read and write */
+#define PNG_TRANSFORM_STRIP_16       0x0001    /* read only */
+#define PNG_TRANSFORM_STRIP_ALPHA    0x0002    /* read only */
+#define PNG_TRANSFORM_PACKING        0x0004    /* read and write */
+#define PNG_TRANSFORM_PACKSWAP       0x0008    /* read and write */
+#define PNG_TRANSFORM_EXPAND         0x0010    /* read only */
+#define PNG_TRANSFORM_INVERT_MONO    0x0020    /* read and write */
+#define PNG_TRANSFORM_SHIFT          0x0040    /* read and write */
+#define PNG_TRANSFORM_BGR            0x0080    /* read and write */
+#define PNG_TRANSFORM_SWAP_ALPHA     0x0100    /* read and write */
+#define PNG_TRANSFORM_SWAP_ENDIAN    0x0200    /* read and write */
+#define PNG_TRANSFORM_INVERT_ALPHA   0x0400    /* read and write */
+#define PNG_TRANSFORM_STRIP_FILLER   0x0800    /* WRITE only */
+
+/* Flags for MNG supported features */
+#define PNG_FLAG_MNG_EMPTY_PLTE     0x01
+#define PNG_FLAG_MNG_FILTER_64      0x04
+#define PNG_ALL_MNG_FEATURES        0x05
+
+typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
+typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
+
+/* The structure that holds the information to read and write PNG files.
+ * The only people who need to care about what is inside of this are the
+ * people who will be modifying the library for their own special needs.
+ * It should NOT be accessed directly by an application, except to store
+ * the jmp_buf.
+ */
+
+struct png_struct_def
+{
+#ifdef PNG_SETJMP_SUPPORTED
+   jmp_buf jmpbuf;            /* used in png_error */
+#endif
+   png_error_ptr error_fn;    /* function for printing errors and aborting */
+   png_error_ptr warning_fn;  /* function for printing warnings */
+   png_voidp error_ptr;       /* user supplied struct for error functions */
+   png_rw_ptr write_data_fn;  /* function for writing output data */
+   png_rw_ptr read_data_fn;   /* function for reading input data */
+   png_voidp io_ptr;          /* ptr to application struct for I/O functions */
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
+   png_user_transform_ptr read_user_transform_fn; /* user read transform */
+#endif
+
+#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+   png_user_transform_ptr write_user_transform_fn; /* user write transform */
+#endif
+
+/* These were added in libpng-1.0.2 */
+#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+   png_voidp user_transform_ptr; /* user supplied struct for user transform */
+   png_byte user_transform_depth;    /* bit depth of user transformed pixels */
+   png_byte user_transform_channels; /* channels in user transformed pixels */
+#endif
+#endif
+
+   png_uint_32 mode;          /* tells us where we are in the PNG file */
+   png_uint_32 flags;         /* flags indicating various things to libpng */
+   png_uint_32 transformations; /* which transformations to perform */
+
+   z_stream zstream;          /* pointer to decompression structure (below) */
+   png_bytep zbuf;            /* buffer for zlib */
+   png_size_t zbuf_size;      /* size of zbuf */
+   int zlib_level;            /* holds zlib compression level */
+   int zlib_method;           /* holds zlib compression method */
+   int zlib_window_bits;      /* holds zlib compression window bits */
+   int zlib_mem_level;        /* holds zlib compression memory level */
+   int zlib_strategy;         /* holds zlib compression strategy */
+
+   png_uint_32 width;         /* width of image in pixels */
+   png_uint_32 height;        /* height of image in pixels */
+   png_uint_32 num_rows;      /* number of rows in current pass */
+   png_uint_32 usr_width;     /* width of row at start of write */
+   png_uint_32 rowbytes;      /* size of row in bytes */
+   png_uint_32 irowbytes;     /* size of current interlaced row in bytes */
+   png_uint_32 iwidth;        /* width of current interlaced row in pixels */
+   png_uint_32 row_number;    /* current row in interlace pass */
+   png_bytep prev_row;        /* buffer to save previous (unfiltered) row */
+   png_bytep row_buf;         /* buffer to save current (unfiltered) row */
+   png_bytep sub_row;         /* buffer to save "sub" row when filtering */
+   png_bytep up_row;          /* buffer to save "up" row when filtering */
+   png_bytep avg_row;         /* buffer to save "avg" row when filtering */
+   png_bytep paeth_row;       /* buffer to save "Paeth" row when filtering */
+   png_row_info row_info;     /* used for transformation routines */
+
+   png_uint_32 idat_size;     /* current IDAT size for read */
+   png_uint_32 crc;           /* current chunk CRC value */
+   png_colorp palette;        /* palette from the input file */
+   png_uint_16 num_palette;   /* number of color entries in palette */
+   png_uint_16 num_trans;     /* number of transparency values */
+   png_byte chunk_name[5];    /* null-terminated name of current chunk */
+   png_byte compression;      /* file compression type (always 0) */
+   png_byte filter;           /* file filter type (always 0) */
+   png_byte interlaced;       /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+   png_byte pass;             /* current interlace pass (0 - 6) */
+   png_byte do_filter;        /* row filter flags (see PNG_FILTER_ below ) */
+   png_byte color_type;       /* color type of file */
+   png_byte bit_depth;        /* bit depth of file */
+   png_byte usr_bit_depth;    /* bit depth of users row */
+   png_byte pixel_depth;      /* number of bits per pixel */
+   png_byte channels;         /* number of channels in file */
+   png_byte usr_channels;     /* channels at start of write */
+   png_byte sig_bytes;        /* magic bytes read/written from start of file */
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+#ifdef PNG_LEGACY_SUPPORTED
+   png_byte filler;           /* filler byte for pixel expansion */
+#else
+   png_uint_16 filler;           /* filler bytes for pixel expansion */
+#endif
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED)
+   png_byte background_gamma_type;
+#  ifdef PNG_FLOATING_POINT_SUPPORTED
+   float background_gamma;
+#  endif
+   png_color_16 background;   /* background color in screen gamma space */
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+   png_color_16 background_1; /* background normalized to gamma 1.0 */
+#endif
+#endif /* PNG_bKGD_SUPPORTED */
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+   png_flush_ptr output_flush_fn;/* Function for flushing output */
+   png_uint_32 flush_dist;    /* how many rows apart to flush, 0 - no flush */
+   png_uint_32 flush_rows;    /* number of rows written since last flush */
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   int gamma_shift;      /* number of "insignificant" bits 16-bit gamma */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   float gamma;          /* file gamma value */
+   float screen_gamma;   /* screen gamma value (display_exponent) */
+#endif
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_bytep gamma_table;     /* gamma table for 8-bit depth files */
+   png_bytep gamma_from_1;    /* converts from 1.0 to screen */
+   png_bytep gamma_to_1;      /* converts from file to 1.0 */
+   png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
+   png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
+   png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
+   png_color_8 sig_bit;       /* significant bits in each available channel */
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+   png_color_8 shift;         /* shift for significant bit tranformation */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
+ || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_bytep trans;           /* transparency values for paletted files */
+   png_color_16 trans_values; /* transparency values for non-paletted files */
+#endif
+
+   png_read_status_ptr read_row_fn;   /* called after each row is decoded */
+   png_write_status_ptr write_row_fn; /* called after each row is encoded */
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+   png_progressive_info_ptr info_fn; /* called after header data fully read */
+   png_progressive_row_ptr row_fn;   /* called after each prog. row is decoded */
+   png_progressive_end_ptr end_fn;   /* called after image is complete */
+   png_bytep save_buffer_ptr;        /* current location in save_buffer */
+   png_bytep save_buffer;            /* buffer for previously read data */
+   png_bytep current_buffer_ptr;     /* current location in current_buffer */
+   png_bytep current_buffer;         /* buffer for recently used data */
+   png_uint_32 push_length;          /* size of current input chunk */
+   png_uint_32 skip_length;          /* bytes to skip in input data */
+   png_size_t save_buffer_size;      /* amount of data now in save_buffer */
+   png_size_t save_buffer_max;       /* total size of save_buffer */
+   png_size_t buffer_size;           /* total amount of available input data */
+   png_size_t current_buffer_size;   /* amount of data now in current_buffer */
+   int process_mode;                 /* what push library is currently doing */
+   int cur_palette;                  /* current push library palette index */
+
+#  if defined(PNG_TEXT_SUPPORTED)
+     png_size_t current_text_size;   /* current size of text input data */
+     png_size_t current_text_left;   /* how much text left to read in input */
+     png_charp current_text;         /* current text chunk buffer */
+     png_charp current_text_ptr;     /* current location in current_text */
+#  endif /* PNG_PROGRESSIVE_READ_SUPPORTED && PNG_TEXT_SUPPORTED */
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
+/* for the Borland special 64K segment handler */
+   png_bytepp offset_table_ptr;
+   png_bytep offset_table;
+   png_uint_16 offset_table_number;
+   png_uint_16 offset_table_count;
+   png_uint_16 offset_table_count_free;
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+   png_bytep palette_lookup;         /* lookup table for dithering */
+   png_bytep dither_index;           /* index translation for palette files */
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
+   png_uint_16p hist;                /* histogram */
+#endif
+
+#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
+   png_byte heuristic_method;        /* heuristic for row filter selection */
+   png_byte num_prev_filters;        /* number of weights for previous rows */
+   png_bytep prev_filters;           /* filter type(s) of previous row(s) */
+   png_uint_16p filter_weights;      /* weight(s) for previous line(s) */
+   png_uint_16p inv_filter_weights;  /* 1/weight(s) for previous line(s) */
+   png_uint_16p filter_costs;        /* relative filter calculation cost */
+   png_uint_16p inv_filter_costs;    /* 1/relative filter calculation cost */
+#endif
+
+#if defined(PNG_TIME_RFC1123_SUPPORTED)
+   png_charp time_buffer;            /* String to hold RFC 1123 time text */
+#endif
+
+/* New members added in libpng-1.0.6 */
+
+#ifdef PNG_FREE_ME_SUPPORTED
+   png_uint_32 free_me;       /* flags items libpng is responsible for freeing */
+#endif
+
+#if defined(PNG_USER_CHUNKS_SUPPORTED)
+   png_voidp user_chunk_ptr;
+   png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
+#endif
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+   int num_chunk_list;
+   png_bytep chunk_list;
+#endif
+
+/* New members added in libpng-1.0.3 */
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+   png_byte rgb_to_gray_status;
+   /* These were changed from png_byte in libpng-1.0.6 */
+   png_uint_16 rgb_to_gray_red_coeff;
+   png_uint_16 rgb_to_gray_green_coeff;
+   png_uint_16 rgb_to_gray_blue_coeff;
+#endif
+
+/* New member added in libpng-1.0.4 (renamed in 1.0.9) */
+#if defined(PNG_MNG_FEATURES_SUPPORTED) || \
+    defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
+    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
+/* changed from png_byte to png_uint_32 at version 1.2.0 */
+#ifdef PNG_1_0_X
+   png_byte mng_features_permitted;
+#else
+   png_uint_32 mng_features_permitted;
+#endif /* PNG_1_0_X */
+#endif
+
+/* New member added in libpng-1.0.7 */
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_fixed_point int_gamma;
+#endif
+
+/* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
+#if defined(PNG_MNG_FEATURES_SUPPORTED)
+   png_byte filter_type;
+#endif
+
+#if defined(PNG_1_0_X) || (defined(PNG_DEBUG) && defined(PNG_USE_PNGGCCRD))
+/* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
+   png_uint_32 row_buf_size;
+#endif
+
+/* New members added in libpng-1.2.0 */
+#if !defined(PNG_1_0_X) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+   png_byte     mmx_bitdepth_threshold;
+   png_uint_32  mmx_rowbytes_threshold;
+   png_uint_32  asm_flags;
+#endif
+
+/* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
+#ifdef PNG_USER_MEM_SUPPORTED
+   png_voidp mem_ptr;                /* user supplied struct for mem functions */
+   png_malloc_ptr malloc_fn;         /* function for allocating memory */
+   png_free_ptr free_fn;             /* function for freeing memory */
+#endif
+
+/* New member added in libpng-1.0.13 and 1.2.0 */
+   png_bytep big_row_buf;         /* buffer to save current (unfiltered) row */
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+/* The following three members were added at version 1.0.14 and 1.2.4 */
+   png_bytep dither_sort;            /* working sort array */
+   png_bytep index_to_palette;       /* where the original index currently is */
+                                     /* in the palette */
+   png_bytep palette_to_index;       /* which original index points to this */
+                                     /* palette color */
+#endif
+
+/* New members added in libpng-1.0.16 and 1.2.6 */
+   png_byte compression_type;
+
+#ifdef PNG_SET_USER_LIMITS_SUPPORTED
+   png_uint_32 user_width_max;
+   png_uint_32 user_height_max;
+#endif
+
+};
+
+
+/* This triggers a compiler error in png.c, if png.c and png.h
+ * do not agree upon the version number.
+ */
+typedef png_structp version_1_2_8;
+
+typedef png_struct FAR * FAR * png_structpp;
+
+/* Here are the function definitions most commonly used.  This is not
+ * the place to find out how to use libpng.  See libpng.txt for the
+ * full explanation, see example.c for the summary.  This just provides
+ * a simple one line description of the use of each function.
+ */
+
+/* Returns the version number of the library */
+extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
+
+/* Tell lib we have already handled the first <num_bytes> magic bytes.
+ * Handling more than 8 bytes from the beginning of the file is an error.
+ */
+extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
+   int num_bytes));
+
+/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
+ * PNG file.  Returns zero if the supplied bytes match the 8-byte PNG
+ * signature, and non-zero otherwise.  Having num_to_check == 0 or
+ * start > 7 will always fail (ie return non-zero).
+ */
+extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
+   png_size_t num_to_check));
+
+/* Simple signature checking function.  This is the same as calling
+ * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
+ */
+extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
+
+/* Allocate and initialize png_ptr struct for reading, and any other memory. */
+extern PNG_EXPORT(png_structp,png_create_read_struct)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn));
+
+/* Allocate and initialize png_ptr struct for writing, and any other memory */
+extern PNG_EXPORT(png_structp,png_create_write_struct)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn));
+
+#ifdef PNG_WRITE_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
+   PNGARG((png_structp png_ptr));
+#endif
+
+#ifdef PNG_WRITE_SUPPORTED
+extern PNG_EXPORT(void,png_set_compression_buffer_size)
+   PNGARG((png_structp png_ptr, png_uint_32 size));
+#endif
+
+/* Reset the compression stream */
+extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
+
+/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
+#ifdef PNG_USER_MEM_SUPPORTED
+extern PNG_EXPORT(png_structp,png_create_read_struct_2)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
+   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+extern PNG_EXPORT(png_structp,png_create_write_struct_2)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
+   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+#endif
+
+/* Write a PNG chunk - size, type, (optional) data, CRC. */
+extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
+   png_bytep chunk_name, png_bytep data, png_size_t length));
+
+/* Write the start of a PNG chunk - length and chunk name. */
+extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
+   png_bytep chunk_name, png_uint_32 length));
+
+/* Write the data of a PNG chunk started with png_write_chunk_start(). */
+extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+/* Finish a chunk started with png_write_chunk_start() (includes CRC). */
+extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
+
+/* Allocate and initialize the info structure */
+extern PNG_EXPORT(png_infop,png_create_info_struct)
+   PNGARG((png_structp png_ptr));
+
+/* Initialize the info structure (old interface - DEPRECATED) */
+extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
+#undef png_info_init
+#define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
+    png_sizeof(png_info));
+extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
+    png_size_t png_info_struct_size));
+
+/* Writes all the PNG information before the image. */
+extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the information before the actual image data. */
+extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+#if defined(PNG_TIME_RFC1123_SUPPORTED)
+extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
+   PNGARG((png_structp png_ptr, png_timep ptime));
+#endif
+
+#if !defined(_WIN32_WCE)
+/* "time.h" functions are not supported on WindowsCE */
+#if defined(PNG_WRITE_tIME_SUPPORTED)
+/* convert from a struct tm to png_time */
+extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
+   struct tm FAR * ttime));
+
+/* convert from time_t to png_time.  Uses gmtime() */
+extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
+   time_t ttime));
+#endif /* PNG_WRITE_tIME_SUPPORTED */
+#endif /* _WIN32_WCE */
+
+#if defined(PNG_READ_EXPAND_SUPPORTED)
+/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
+extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+/* Use blue, green, red order for pixels. */
+extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
+/* Expand the grayscale to 24-bit RGB if necessary. */
+extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+/* Reduce RGB to grayscale. */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
+   int error_action, double red, double green ));
+#endif
+extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
+   int error_action, png_fixed_point red, png_fixed_point green ));
+extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
+   png_ptr));
+#endif
+
+extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
+   png_colorp palette));
+
+#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
+extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
+   png_uint_32 filler, int flags));
+/* The values of the PNG_FILLER_ defines should NOT be changed */
+#define PNG_FILLER_BEFORE 0
+#define PNG_FILLER_AFTER 1
+/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
+#if !defined(PNG_1_0_X)
+extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
+   png_uint_32 filler, int flags));
+#endif
+#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
+
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+/* Swap bytes in 16-bit depth files. */
+extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
+/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
+extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+/* Swap packing order of pixels in bytes. */
+extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+/* Converts files to legal bit depths. */
+extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
+   png_color_8p true_bits));
+#endif
+
+#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
+    defined(PNG_WRITE_INTERLACING_SUPPORTED)
+/* Have the code handle the interlacing.  Returns the number of passes. */
+extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+/* Invert monochrome files */
+extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_BACKGROUND_SUPPORTED)
+/* Handle alpha and tRNS by replacing with a background color. */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
+   png_color_16p background_color, int background_gamma_code,
+   int need_expand, double background_gamma));
+#endif
+#define PNG_BACKGROUND_GAMMA_UNKNOWN 0
+#define PNG_BACKGROUND_GAMMA_SCREEN  1
+#define PNG_BACKGROUND_GAMMA_FILE    2
+#define PNG_BACKGROUND_GAMMA_UNIQUE  3
+#endif
+
+#if defined(PNG_READ_16_TO_8_SUPPORTED)
+/* strip the second byte of information from a 16-bit depth file. */
+extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+/* Turn on dithering, and reduce the palette to the number of colors available. */
+extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
+   png_colorp palette, int num_palette, int maximum_colors,
+   png_uint_16p histogram, int full_dither));
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+/* Handle gamma correction. Screen_gamma=(display_exponent) */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
+   double screen_gamma, double default_file_gamma));
+#endif
+#endif
+
+#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
+    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
+/* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
+/* Deprecated and will be removed.  Use png_permit_mng_features() instead. */
+extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
+   int empty_plte_permitted));
+#endif
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+/* Set how many lines between output flushes - 0 for no flushing */
+extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
+/* Flush the current PNG output buffer */
+extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
+#endif
+
+/* optional update palette with requested transformations */
+extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
+
+/* optional call to update the users info structure */
+extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read one or more rows of image data. */
+extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
+   png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
+#endif
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read a row of data. */
+extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
+   png_bytep row,
+   png_bytep display_row));
+#endif
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the whole image into memory at once. */
+extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
+   png_bytepp image));
+#endif
+
+/* write a row of image data */
+extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
+   png_bytep row));
+
+/* write a few rows of image data */
+extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
+   png_bytepp row, png_uint_32 num_rows));
+
+/* write the image data */
+extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
+   png_bytepp image));
+
+/* writes the end of the PNG file. */
+extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the end of the PNG file. */
+extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+/* free any memory associated with the png_info_struct */
+extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
+   png_infopp info_ptr_ptr));
+
+/* free any memory associated with the png_struct and the png_info_structs */
+extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
+   png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
+
+/* free all memory used by the read (old method - NOT DLL EXPORTED) */
+extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_infop end_info_ptr));
+
+/* free any memory associated with the png_struct and the png_info_structs */
+extern PNG_EXPORT(void,png_destroy_write_struct)
+   PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
+
+/* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
+extern void png_write_destroy PNGARG((png_structp png_ptr));
+
+/* set the libpng method of handling chunk CRC errors */
+extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
+   int crit_action, int ancil_action));
+
+/* Values for png_set_crc_action() to say how to handle CRC errors in
+ * ancillary and critical chunks, and whether to use the data contained
+ * therein.  Note that it is impossible to "discard" data in a critical
+ * chunk.  For versions prior to 0.90, the action was always error/quit,
+ * whereas in version 0.90 and later, the action for CRC errors in ancillary
+ * chunks is warn/discard.  These values should NOT be changed.
+ *
+ *      value                       action:critical     action:ancillary
+ */
+#define PNG_CRC_DEFAULT       0  /* error/quit          warn/discard data */
+#define PNG_CRC_ERROR_QUIT    1  /* error/quit          error/quit        */
+#define PNG_CRC_WARN_DISCARD  2  /* (INVALID)           warn/discard data */
+#define PNG_CRC_WARN_USE      3  /* warn/use data       warn/use data     */
+#define PNG_CRC_QUIET_USE     4  /* quiet/use data      quiet/use data    */
+#define PNG_CRC_NO_CHANGE     5  /* use current value   use current value */
+
+/* These functions give the user control over the scan-line filtering in
+ * libpng and the compression methods used by zlib.  These functions are
+ * mainly useful for testing, as the defaults should work with most users.
+ * Those users who are tight on memory or want faster performance at the
+ * expense of compression can modify them.  See the compression library
+ * header file (zlib.h) for an explination of the compression functions.
+ */
+
+/* set the filtering method(s) used by libpng.  Currently, the only valid
+ * value for "method" is 0.
+ */
+extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
+   int filters));
+
+/* Flags for png_set_filter() to say which filters to use.  The flags
+ * are chosen so that they don't conflict with real filter types
+ * below, in case they are supplied instead of the #defined constants.
+ * These values should NOT be changed.
+ */
+#define PNG_NO_FILTERS     0x00
+#define PNG_FILTER_NONE    0x08
+#define PNG_FILTER_SUB     0x10
+#define PNG_FILTER_UP      0x20
+#define PNG_FILTER_AVG     0x40
+#define PNG_FILTER_PAETH   0x80
+#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
+                         PNG_FILTER_AVG | PNG_FILTER_PAETH)
+
+/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
+ * These defines should NOT be changed.
+ */
+#define PNG_FILTER_VALUE_NONE  0
+#define PNG_FILTER_VALUE_SUB   1
+#define PNG_FILTER_VALUE_UP    2
+#define PNG_FILTER_VALUE_AVG   3
+#define PNG_FILTER_VALUE_PAETH 4
+#define PNG_FILTER_VALUE_LAST  5
+
+#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
+/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
+ * defines, either the default (minimum-sum-of-absolute-differences), or
+ * the experimental method (weighted-minimum-sum-of-absolute-differences).
+ *
+ * Weights are factors >= 1.0, indicating how important it is to keep the
+ * filter type consistent between rows.  Larger numbers mean the current
+ * filter is that many times as likely to be the same as the "num_weights"
+ * previous filters.  This is cumulative for each previous row with a weight.
+ * There needs to be "num_weights" values in "filter_weights", or it can be
+ * NULL if the weights aren't being specified.  Weights have no influence on
+ * the selection of the first row filter.  Well chosen weights can (in theory)
+ * improve the compression for a given image.
+ *
+ * Costs are factors >= 1.0 indicating the relative decoding costs of a
+ * filter type.  Higher costs indicate more decoding expense, and are
+ * therefore less likely to be selected over a filter with lower computational
+ * costs.  There needs to be a value in "filter_costs" for each valid filter
+ * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
+ * setting the costs.  Costs try to improve the speed of decompression without
+ * unduly increasing the compressed image size.
+ *
+ * A negative weight or cost indicates the default value is to be used, and
+ * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
+ * The default values for both weights and costs are currently 1.0, but may
+ * change if good general weighting/cost heuristics can be found.  If both
+ * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
+ * to the UNWEIGHTED method, but with added encoding time/computation.
+ */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
+   int heuristic_method, int num_weights, png_doublep filter_weights,
+   png_doublep filter_costs));
+#endif
+#endif /*  PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
+
+/* Heuristic used for row filter selection.  These defines should NOT be
+ * changed.
+ */
+#define PNG_FILTER_HEURISTIC_DEFAULT    0  /* Currently "UNWEIGHTED" */
+#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1  /* Used by libpng < 0.95 */
+#define PNG_FILTER_HEURISTIC_WEIGHTED   2  /* Experimental feature */
+#define PNG_FILTER_HEURISTIC_LAST       3  /* Not a valid value */
+
+/* Set the library compression level.  Currently, valid values range from
+ * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
+ * (0 - no compression, 9 - "maximal" compression).  Note that tests have
+ * shown that zlib compression levels 3-6 usually perform as well as level 9
+ * for PNG images, and do considerably fewer caclulations.  In the future,
+ * these values may not correspond directly to the zlib compression levels.
+ */
+extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
+   int level));
+
+extern PNG_EXPORT(void,png_set_compression_mem_level)
+   PNGARG((png_structp png_ptr, int mem_level));
+
+extern PNG_EXPORT(void,png_set_compression_strategy)
+   PNGARG((png_structp png_ptr, int strategy));
+
+extern PNG_EXPORT(void,png_set_compression_window_bits)
+   PNGARG((png_structp png_ptr, int window_bits));
+
+extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
+   int method));
+
+/* These next functions are called for input/output, memory, and error
+ * handling.  They are in the file pngrio.c, pngwio.c, and pngerror.c,
+ * and call standard C I/O routines such as fread(), fwrite(), and
+ * fprintf().  These functions can be made to use other I/O routines
+ * at run time for those applications that need to handle I/O in a
+ * different manner by calling png_set_???_fn().  See libpng.txt for
+ * more information.
+ */
+
+#if !defined(PNG_NO_STDIO)
+/* Initialize the input/output for the PNG file to the default functions. */
+extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
+#endif
+
+/* Replace the (error and abort), and warning functions with user
+ * supplied functions.  If no messages are to be printed you must still
+ * write and use replacement functions. The replacement error_fn should
+ * still do a longjmp to the last setjmp location if you are using this
+ * method of error handling.  If error_fn or warning_fn is NULL, the
+ * default function will be used.
+ */
+
+extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
+   png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
+
+/* Return the user pointer associated with the error functions */
+extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
+
+/* Replace the default data output functions with a user supplied one(s).
+ * If buffered output is not used, then output_flush_fn can be set to NULL.
+ * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
+ * output_flush_fn will be ignored (and thus can be NULL).
+ */
+extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
+   png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
+
+/* Replace the default data input function with a user supplied one. */
+extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
+   png_voidp io_ptr, png_rw_ptr read_data_fn));
+
+/* Return the user pointer associated with the I/O functions */
+extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
+
+extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
+   png_read_status_ptr read_row_fn));
+
+extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
+   png_write_status_ptr write_row_fn));
+
+#ifdef PNG_USER_MEM_SUPPORTED
+/* Replace the default memory allocation functions with user supplied one(s). */
+extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
+   png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+/* Return the user pointer associated with the memory functions */
+extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
+   png_ptr, png_user_transform_ptr read_user_transform_fn));
+#endif
+
+#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
+   png_ptr, png_user_transform_ptr write_user_transform_fn));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
+   png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
+   int user_transform_channels));
+/* Return the user pointer associated with the user transform functions */
+extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
+   PNGARG((png_structp png_ptr));
+#endif
+
+#ifdef PNG_USER_CHUNKS_SUPPORTED
+extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
+   png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
+extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
+   png_ptr));
+#endif
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+/* Sets the function callbacks for the push reader, and a pointer to a
+ * user-defined structure available to the callback functions.
+ */
+extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
+   png_voidp progressive_ptr,
+   png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
+   png_progressive_end_ptr end_fn));
+
+/* returns the user pointer associated with the push read functions */
+extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
+   PNGARG((png_structp png_ptr));
+
+/* function to be called when data becomes available */
+extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
+
+/* function that combines rows.  Not very much different than the
+ * png_combine_row() call.  Is this even used?????
+ */
+extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
+   png_bytep old_row, png_bytep new_row));
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+
+#if defined(PNG_1_0_X)
+#  define png_malloc_warn png_malloc
+#else
+/* Added at libpng version 1.2.4 */
+extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+#endif
+
+/* frees a pointer allocated by png_malloc() */
+extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
+
+#if defined(PNG_1_0_X)
+/* Function to allocate memory for zlib. */
+extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
+   uInt size));
+
+/* Function to free memory for zlib */
+extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
+#endif
+
+/* Free data that was allocated internally */
+extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 free_me, int num));
+#ifdef PNG_FREE_ME_SUPPORTED
+/* Reassign responsibility for freeing existing data, whether allocated
+ * by libpng or by the application */
+extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int freer, png_uint_32 mask));
+#endif
+/* assignments for png_data_freer */
+#define PNG_DESTROY_WILL_FREE_DATA 1
+#define PNG_SET_WILL_FREE_DATA 1
+#define PNG_USER_WILL_FREE_DATA 2
+/* Flags for png_ptr->free_me and info_ptr->free_me */
+#define PNG_FREE_HIST 0x0008
+#define PNG_FREE_ICCP 0x0010
+#define PNG_FREE_SPLT 0x0020
+#define PNG_FREE_ROWS 0x0040
+#define PNG_FREE_PCAL 0x0080
+#define PNG_FREE_SCAL 0x0100
+#define PNG_FREE_UNKN 0x0200
+#define PNG_FREE_LIST 0x0400
+#define PNG_FREE_PLTE 0x1000
+#define PNG_FREE_TRNS 0x2000
+#define PNG_FREE_TEXT 0x4000
+#define PNG_FREE_ALL  0x7fff
+#define PNG_FREE_MUL  0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
+
+#ifdef PNG_USER_MEM_SUPPORTED
+extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
+   png_voidp ptr));
+#endif
+
+extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
+   png_voidp s1, png_voidp s2, png_uint_32 size));
+
+extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
+   png_voidp s1, int value, png_uint_32 size));
+
+#if defined(USE_FAR_KEYWORD)  /* memory model conversion function */
+extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
+   int check));
+#endif /* USE_FAR_KEYWORD */
+
+/* Fatal error in PNG image of libpng - can't continue */
+extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
+   png_const_charp error_message));
+
+/* The same, but the chunk name is prepended to the error string. */
+extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
+   png_const_charp error_message));
+
+/* Non-fatal error in libpng.  Can continue, but may have a problem. */
+extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
+   png_const_charp warning_message));
+
+/* Non-fatal error in libpng, chunk name is prepended to message. */
+extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
+   png_const_charp warning_message));
+
+/* The png_set_<chunk> functions are for storing values in the png_info_struct.
+ * Similarly, the png_get_<chunk> calls are used to read values from the
+ * png_info_struct, either storing the parameters in the passed variables, or
+ * setting pointers into the png_info_struct where the data is stored.  The
+ * png_get_<chunk> functions return a non-zero value if the data was available
+ * in info_ptr, or return zero and do not change any of the parameters if the
+ * data was not available.
+ *
+ * These functions should be used instead of directly accessing png_info
+ * to avoid problems with future changes in the size and internal layout of
+ * png_info_struct.
+ */
+/* Returns "flag" if chunk data is valid in info_ptr. */
+extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
+png_infop info_ptr, png_uint_32 flag));
+
+/* Returns number of bytes needed to hold a transformed row. */
+extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+/* Returns row_pointers, which is an array of pointers to scanlines that was
+returned from png_read_png(). */
+extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+/* Set row_pointers, which is an array of pointers to scanlines for use
+by png_write_png(). */
+extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytepp row_pointers));
+#endif
+
+/* Returns number of color channels in image. */
+extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#ifdef PNG_EASY_ACCESS_SUPPORTED
+/* Returns image width in pixels. */
+extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image height in pixels. */
+extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image bit_depth. */
+extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image color_type. */
+extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image filter_type. */
+extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image interlace_type. */
+extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image compression_type. */
+extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image resolution in pixels per meter, from pHYs chunk data. */
+extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns pixel aspect ratio, computed from pHYs chunk data.  */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+#endif
+
+/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
+extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+#endif /* PNG_EASY_ACCESS_SUPPORTED */
+
+/* Returns pointer to signature string read from PNG header */
+extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#if defined(PNG_bKGD_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_16p *background));
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED)
+extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_16p background));
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double *white_x, double *white_y, double *red_x,
+   double *red_y, double *green_x, double *green_y, double *blue_x,
+   double *blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
+   *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
+   png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
+   *int_blue_x, png_fixed_point *int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double white_x, double white_y, double red_x,
+   double red_y, double green_x, double green_y, double blue_x, double blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
+   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+   png_fixed_point int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double *file_gamma));
+#endif
+extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point *int_file_gamma));
+#endif
+
+#if defined(PNG_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double file_gamma));
+#endif
+extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point int_file_gamma));
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_16p *hist));
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_16p hist));
+#endif
+
+extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
+   int *bit_depth, int *color_type, int *interlace_method,
+   int *compression_method, int *filter_method));
+
+extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
+   int color_type, int interlace_method, int compression_method,
+   int filter_method));
+
+#if defined(PNG_oFFs_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
+   int *unit_type));
+#endif
+
+#if defined(PNG_oFFs_SUPPORTED)
+extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
+   int unit_type));
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
+   int *type, int *nparams, png_charp *units, png_charpp *params));
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
+   int type, int nparams, png_charp units, png_charpp params));
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
+#endif
+
+extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_colorp *palette, int *num_palette));
+
+extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_colorp palette, int num_palette));
+
+#if defined(PNG_sBIT_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_8p *sig_bit));
+#endif
+
+#if defined(PNG_sBIT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_8p sig_bit));
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *intent));
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int intent));
+extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int intent));
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charpp name, int *compression_type,
+   png_charpp profile, png_uint_32 *proflen));
+   /* Note to maintainer: profile should be png_bytepp */
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp name, int compression_type,
+   png_charp profile, png_uint_32 proflen));
+   /* Note to maintainer: profile should be png_bytep */
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_sPLT_tpp entries));
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_sPLT_tp entries, int nentries));
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)
+/* png_get_text also returns the number of text chunks in *num_text */
+extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp *text_ptr, int *num_text));
+#endif
+
+/*
+ *  Note while png_set_text() will accept a structure whose text,
+ *  language, and  translated keywords are NULL pointers, the structure
+ *  returned by png_get_text will always contain regular
+ *  zero-terminated C strings.  They might be empty strings but
+ *  they will never be NULL pointers.
+ */
+
+#if defined(PNG_TEXT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp text_ptr, int num_text));
+#endif
+
+#if defined(PNG_tIME_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_timep *mod_time));
+#endif
+
+#if defined(PNG_tIME_SUPPORTED)
+extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_timep mod_time));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep *trans, int *num_trans,
+   png_color_16p *trans_values));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep trans, int num_trans,
+   png_color_16p trans_values));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+#endif
+
+#if defined(PNG_sCAL_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *unit, double *width, double *height));
+#else
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
+#endif
+#endif
+#endif /* PNG_sCAL_SUPPORTED */
+
+#if defined(PNG_sCAL_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int unit, double width, double height));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
+#endif
+#endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+/* provide a list of chunks and how they are to be handled, if the built-in
+   handling or default unknown chunk handling is not desired.  Any chunks not
+   listed will be handled in the default manner.  The IHDR and IEND chunks
+   must not be listed.
+      keep = 0: follow default behavour
+           = 1: do not keep
+           = 2: keep only if safe-to-copy
+           = 3: keep even if unsafe-to-copy
+*/
+extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
+   png_ptr, int keep, png_bytep chunk_list, int num_chunks));
+extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
+extern PNG_EXPORT(void, png_set_unknown_chunk_location)
+   PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
+extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
+   png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
+#endif
+#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
+   chunk_name));
+#endif
+
+/* Png_free_data() will turn off the "valid" flag for anything it frees.
+   If you need to turn it off for a chunk that your application has freed,
+   you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
+extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int mask));
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+/* The "params" pointer is currently not used and is for future expansion. */
+extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
+                        png_infop info_ptr,
+                        int transforms,
+                        png_voidp params));
+extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
+                        png_infop info_ptr,
+                        int transforms,
+                        png_voidp params));
+#endif
+
+/* Define PNG_DEBUG at compile time for debugging information.  Higher
+ * numbers for PNG_DEBUG mean more debugging information.  This has
+ * only been added since version 0.95 so it is not implemented throughout
+ * libpng yet, but more support will be added as needed.
+ */
+#ifdef PNG_DEBUG
+#if (PNG_DEBUG > 0)
+#if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
+#include <crtdbg.h>
+#if (PNG_DEBUG > 1)
+#define png_debug(l,m)  _RPT0(_CRT_WARN,m)
+#define png_debug1(l,m,p1)  _RPT1(_CRT_WARN,m,p1)
+#define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
+#endif
+#else /* PNG_DEBUG_FILE || !_MSC_VER */
+#ifndef PNG_DEBUG_FILE
+#define PNG_DEBUG_FILE stderr
+#endif /* PNG_DEBUG_FILE */
+#if (PNG_DEBUG > 1)
+#define png_debug(l,m) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
+}
+#define png_debug1(l,m,p1) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
+}
+#define png_debug2(l,m,p1,p2) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
+}
+#endif /* (PNG_DEBUG > 1) */
+#endif /* _MSC_VER */
+#endif /* (PNG_DEBUG > 0) */
+#endif /* PNG_DEBUG */
+#ifndef png_debug
+#define png_debug(l, m)
+#endif
+#ifndef png_debug1
+#define png_debug1(l, m, p1)
+#endif
+#ifndef png_debug2
+#define png_debug2(l, m, p1, p2)
+#endif
+
+extern PNG_EXPORT(png_bytep,png_sig_bytes) PNGARG((void));
+
+extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
+   png_ptr, png_uint_32 mng_features_permitted));
+#endif
+
+/* For use in png_set_keep_unknown, added to version 1.2.6 */
+#define PNG_HANDLE_CHUNK_AS_DEFAULT   0
+#define PNG_HANDLE_CHUNK_NEVER        1
+#define PNG_HANDLE_CHUNK_IF_SAFE      2
+#define PNG_HANDLE_CHUNK_ALWAYS       3
+
+/* Added to version 1.2.0 */
+#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+#define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED  0x01  /* not user-settable */
+#define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU    0x02  /* not user-settable */
+#define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  0x04
+#define PNG_ASM_FLAG_MMX_READ_INTERLACE    0x08
+#define PNG_ASM_FLAG_MMX_READ_FILTER_SUB   0x10
+#define PNG_ASM_FLAG_MMX_READ_FILTER_UP    0x20
+#define PNG_ASM_FLAG_MMX_READ_FILTER_AVG   0x40
+#define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
+#define PNG_ASM_FLAGS_INITIALIZED          0x80000000  /* not user-settable */
+
+#define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  \
+                           | PNG_ASM_FLAG_MMX_READ_INTERLACE    \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_SUB   \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_UP    \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_AVG   \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
+#define PNG_MMX_WRITE_FLAGS ( 0 )
+
+#define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
+                      | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU   \
+                      | PNG_MMX_READ_FLAGS                \
+                      | PNG_MMX_WRITE_FLAGS )
+
+#define PNG_SELECT_READ   1
+#define PNG_SELECT_WRITE  2
+
+#if !defined(PNG_1_0_X)
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
+   PNGARG((int flag_select, int *compilerID));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
+   PNGARG((int flag_select));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
+   PNGARG((png_structp png_ptr));
+
+/* pngget.c */
+extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
+   PNGARG((png_structp png_ptr));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
+   PNGARG((png_structp png_ptr));
+
+/* pngset.c */
+extern PNG_EXPORT(void,png_set_asm_flags)
+   PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
+
+/* pngset.c */
+extern PNG_EXPORT(void,png_set_mmx_thresholds)
+   PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
+   png_uint_32 mmx_rowbytes_threshold));
+
+#endif /* PNG_1_0_X */
+#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
+
+#if !defined(PNG_1_0_X)
+/* png.c, pnggccrd.c, or pngvcrd.c */
+extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
+
+/* Strip the prepended error numbers ("#nnn ") from error and warning
+ * messages before passing them to the error or warning handler. */
+#ifdef PNG_ERROR_NUMBERS_SUPPORTED
+extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
+   png_ptr, png_uint_32 strip_mode));
+#endif
+
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.2.6 */
+#ifdef PNG_SET_USER_LIMITS_SUPPORTED
+extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
+   png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
+extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
+   png_ptr));
+extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
+   png_ptr));
+#endif
+
+/* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
+
+#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
+/* With these routines we avoid an integer divide, which will be slower on
+ * most machines.  However, it does take more operations than the corresponding
+ * divide method, so it may be slower on a few RISC systems.  There are two
+ * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
+ *
+ * Note that the rounding factors are NOT supposed to be the same!  128 and
+ * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
+ * standard method.
+ *
+ * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
+ */
+
+ /* fg and bg should be in `gamma 1.0' space; alpha is the opacity          */
+
+#  define png_composite(composite, fg, alpha, bg)                            \
+     { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
+                        +        (png_uint_16)(bg)*(png_uint_16)(255 -       \
+                        (png_uint_16)(alpha)) + (png_uint_16)128);           \
+       (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
+
+#  define png_composite_16(composite, fg, alpha, bg)                         \
+     { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
+                        + (png_uint_32)(bg)*(png_uint_32)(65535L -           \
+                        (png_uint_32)(alpha)) + (png_uint_32)32768L);        \
+       (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
+
+#else  /* standard method using integer division */
+
+#  define png_composite(composite, fg, alpha, bg)                            \
+     (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) +    \
+       (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) +       \
+       (png_uint_16)127) / 255)
+
+#  define png_composite_16(composite, fg, alpha, bg)                         \
+     (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
+       (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) +      \
+       (png_uint_32)32767) / (png_uint_32)65535L)
+
+#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
+
+/* These next functions are used internally in the code.  They generally
+ * shouldn't be used unless you are writing code to add or replace some
+ * functionality in libpng.  More information about most functions can
+ * be found in the files where the functions are located.
+ */
+
+#if defined(PNG_INTERNAL)
+
+/* Various modes of operation.  Note that after an init, mode is set to
+ * zero automatically when the structure is created.
+ */
+#define PNG_HAVE_IHDR               0x01
+#define PNG_HAVE_PLTE               0x02
+#define PNG_HAVE_IDAT               0x04
+#define PNG_AFTER_IDAT              0x08
+#define PNG_HAVE_IEND               0x10
+#define PNG_HAVE_gAMA               0x20
+#define PNG_HAVE_cHRM               0x40
+#define PNG_HAVE_sRGB               0x80
+#define PNG_HAVE_CHUNK_HEADER      0x100
+#define PNG_WROTE_tIME             0x200
+#define PNG_WROTE_INFO_BEFORE_PLTE 0x400
+#define PNG_BACKGROUND_IS_GRAY     0x800
+#define PNG_HAVE_PNG_SIGNATURE    0x1000
+
+/* flags for the transformations the PNG library does on the image data */
+#define PNG_BGR                0x0001
+#define PNG_INTERLACE          0x0002
+#define PNG_PACK               0x0004
+#define PNG_SHIFT              0x0008
+#define PNG_SWAP_BYTES         0x0010
+#define PNG_INVERT_MONO        0x0020
+#define PNG_DITHER             0x0040
+#define PNG_BACKGROUND         0x0080
+#define PNG_BACKGROUND_EXPAND  0x0100
+                          /*   0x0200 unused */
+#define PNG_16_TO_8            0x0400
+#define PNG_RGBA               0x0800
+#define PNG_EXPAND             0x1000
+#define PNG_GAMMA              0x2000
+#define PNG_GRAY_TO_RGB        0x4000
+#define PNG_FILLER             0x8000L
+#define PNG_PACKSWAP          0x10000L
+#define PNG_SWAP_ALPHA        0x20000L
+#define PNG_STRIP_ALPHA       0x40000L
+#define PNG_INVERT_ALPHA      0x80000L
+#define PNG_USER_TRANSFORM   0x100000L
+#define PNG_RGB_TO_GRAY_ERR  0x200000L
+#define PNG_RGB_TO_GRAY_WARN 0x400000L
+#define PNG_RGB_TO_GRAY      0x600000L  /* two bits, RGB_TO_GRAY_ERR|WARN */
+                       /*    0x800000L     Unused */
+#define PNG_ADD_ALPHA       0x1000000L  /* Added to libpng-1.2.7 */
+                       /*   0x2000000L  unused */
+                       /*   0x4000000L  unused */
+                       /*   0x8000000L  unused */
+                       /*  0x10000000L  unused */
+                       /*  0x20000000L  unused */
+                       /*  0x40000000L  unused */
+
+/* flags for png_create_struct */
+#define PNG_STRUCT_PNG   0x0001
+#define PNG_STRUCT_INFO  0x0002
+
+/* Scaling factor for filter heuristic weighting calculations */
+#define PNG_WEIGHT_SHIFT 8
+#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
+#define PNG_COST_SHIFT 3
+#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
+
+/* flags for the png_ptr->flags rather than declaring a byte for each one */
+#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY     0x0001
+#define PNG_FLAG_ZLIB_CUSTOM_LEVEL        0x0002
+#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL    0x0004
+#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS  0x0008
+#define PNG_FLAG_ZLIB_CUSTOM_METHOD       0x0010
+#define PNG_FLAG_ZLIB_FINISHED            0x0020
+#define PNG_FLAG_ROW_INIT                 0x0040
+#define PNG_FLAG_FILLER_AFTER             0x0080
+#define PNG_FLAG_CRC_ANCILLARY_USE        0x0100
+#define PNG_FLAG_CRC_ANCILLARY_NOWARN     0x0200
+#define PNG_FLAG_CRC_CRITICAL_USE         0x0400
+#define PNG_FLAG_CRC_CRITICAL_IGNORE      0x0800
+#define PNG_FLAG_FREE_PLTE                0x1000
+#define PNG_FLAG_FREE_TRNS                0x2000
+#define PNG_FLAG_FREE_HIST                0x4000
+#define PNG_FLAG_KEEP_UNKNOWN_CHUNKS      0x8000L
+#define PNG_FLAG_KEEP_UNSAFE_CHUNKS       0x10000L
+#define PNG_FLAG_LIBRARY_MISMATCH         0x20000L
+#define PNG_FLAG_STRIP_ERROR_NUMBERS      0x40000L
+#define PNG_FLAG_STRIP_ERROR_TEXT         0x80000L
+#define PNG_FLAG_MALLOC_NULL_MEM_OK       0x100000L
+#define PNG_FLAG_ADD_ALPHA                0x200000L  /* Added to libpng-1.2.8 */
+#define PNG_FLAG_STRIP_ALPHA              0x400000L  /* Added to libpng-1.2.8 */
+                                  /*      0x800000L  unused */
+                                  /*     0x1000000L  unused */
+                                  /*     0x2000000L  unused */
+                                  /*     0x4000000L  unused */
+                                  /*     0x8000000L  unused */
+                                  /*    0x10000000L  unused */
+                                  /*    0x20000000L  unused */
+                                  /*    0x40000000L  unused */
+
+#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
+                                     PNG_FLAG_CRC_ANCILLARY_NOWARN)
+
+#define PNG_FLAG_CRC_CRITICAL_MASK  (PNG_FLAG_CRC_CRITICAL_USE | \
+                                     PNG_FLAG_CRC_CRITICAL_IGNORE)
+
+#define PNG_FLAG_CRC_MASK           (PNG_FLAG_CRC_ANCILLARY_MASK | \
+                                     PNG_FLAG_CRC_CRITICAL_MASK)
+
+/* save typing and make code easier to understand */
+
+#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
+   abs((int)((c1).green) - (int)((c2).green)) + \
+   abs((int)((c1).blue) - (int)((c2).blue)))
+
+/* Added to libpng-1.2.6 JB */
+#define PNG_ROWBYTES(pixel_bits, width) \
+    ((pixel_bits) >= 8 ? \
+    ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
+    (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
+
+/* PNG_OUT_OF_RANGE returns true if value is outside the range
+   ideal-delta..ideal+delta.  Each argument is evaluated twice.
+   "ideal" and "delta" should be constants, normally simple
+   integers, "value" a variable. Added to libpng-1.2.6 JB */
+#define PNG_OUT_OF_RANGE(value, ideal, delta) \
+        ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
+
+/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
+#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
+/* place to hold the signature string for a PNG file. */
+#ifdef PNG_USE_GLOBAL_ARRAYS
+   PNG_EXPORT_VAR (const png_byte FARDATA) png_sig[8];
+#else
+#define png_sig png_sig_bytes(NULL)
+#endif
+#endif /* PNG_NO_EXTERN */
+
+/* Constant strings for known chunk types.  If you need to add a chunk,
+ * define the name here, and add an invocation of the macro in png.c and
+ * wherever it's needed.
+ */
+#define PNG_IHDR const png_byte png_IHDR[5] = { 73,  72,  68,  82, '\0'}
+#define PNG_IDAT const png_byte png_IDAT[5] = { 73,  68,  65,  84, '\0'}
+#define PNG_IEND const png_byte png_IEND[5] = { 73,  69,  78,  68, '\0'}
+#define PNG_PLTE const png_byte png_PLTE[5] = { 80,  76,  84,  69, '\0'}
+#define PNG_bKGD const png_byte png_bKGD[5] = { 98,  75,  71,  68, '\0'}
+#define PNG_cHRM const png_byte png_cHRM[5] = { 99,  72,  82,  77, '\0'}
+#define PNG_gAMA const png_byte png_gAMA[5] = {103,  65,  77,  65, '\0'}
+#define PNG_hIST const png_byte png_hIST[5] = {104,  73,  83,  84, '\0'}
+#define PNG_iCCP const png_byte png_iCCP[5] = {105,  67,  67,  80, '\0'}
+#define PNG_iTXt const png_byte png_iTXt[5] = {105,  84,  88, 116, '\0'}
+#define PNG_oFFs const png_byte png_oFFs[5] = {111,  70,  70, 115, '\0'}
+#define PNG_pCAL const png_byte png_pCAL[5] = {112,  67,  65,  76, '\0'}
+#define PNG_sCAL const png_byte png_sCAL[5] = {115,  67,  65,  76, '\0'}
+#define PNG_pHYs const png_byte png_pHYs[5] = {112,  72,  89, 115, '\0'}
+#define PNG_sBIT const png_byte png_sBIT[5] = {115,  66,  73,  84, '\0'}
+#define PNG_sPLT const png_byte png_sPLT[5] = {115,  80,  76,  84, '\0'}
+#define PNG_sRGB const png_byte png_sRGB[5] = {115,  82,  71,  66, '\0'}
+#define PNG_tEXt const png_byte png_tEXt[5] = {116,  69,  88, 116, '\0'}
+#define PNG_tIME const png_byte png_tIME[5] = {116,  73,  77,  69, '\0'}
+#define PNG_tRNS const png_byte png_tRNS[5] = {116,  82,  78,  83, '\0'}
+#define PNG_zTXt const png_byte png_zTXt[5] = {122,  84,  88, 116, '\0'}
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IHDR[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IDAT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IEND[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_PLTE[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_bKGD[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_cHRM[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_gAMA[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_hIST[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_iCCP[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_iTXt[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_oFFs[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_pCAL[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sCAL[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_pHYs[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sBIT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sPLT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sRGB[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tEXt[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tIME[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tRNS[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_zTXt[5];
+#endif /* PNG_USE_GLOBAL_ARRAYS */
+
+
+/* Inline macros to do direct reads of bytes from the input buffer.  These
+ * require that you are using an architecture that uses PNG byte ordering
+ * (MSB first) and supports unaligned data storage.  I think that PowerPC
+ * in big-endian mode and 680x0 are the only ones that will support this.
+ * The x86 line of processors definitely do not.  The png_get_int_32()
+ * routine also assumes we are using two's complement format for negative
+ * values, which is almost certainly true.
+ */
+#if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
+#  if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED)
+#    define png_get_int_32(buf) ( *((png_int_32p) (buf)))
+#  endif
+#  define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
+#  define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
+#else
+#  if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED)
+PNG_EXTERN png_int_32 png_get_int_32 PNGARG((png_bytep buf));
+#  endif
+PNG_EXTERN png_uint_32 png_get_uint_32 PNGARG((png_bytep buf));
+PNG_EXTERN png_uint_16 png_get_uint_16 PNGARG((png_bytep buf));
+#endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
+PNG_EXTERN png_uint_32 png_get_uint_31 PNGARG((png_structp png_ptr,
+  png_bytep buf));
+
+/* Initialize png_ptr struct for reading, and allocate any other memory.
+ * (old interface - DEPRECATED - use png_create_read_struct instead).
+ */
+extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
+#undef png_read_init
+#define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
+    PNG_LIBPNG_VER_STRING,  png_sizeof(png_struct));
+extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size));
+extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
+    png_info_size));
+
+/* Initialize png_ptr struct for writing, and allocate any other memory.
+ * (old interface - DEPRECATED - use png_create_write_struct instead).
+ */
+extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
+#undef png_write_init
+#define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
+    PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
+extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size));
+extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
+    png_info_size));
+
+/* Allocate memory for an internal libpng struct */
+PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
+
+/* Free memory from internal libpng struct */
+PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
+
+PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
+  malloc_fn, png_voidp mem_ptr));
+PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
+   png_free_ptr free_fn, png_voidp mem_ptr));
+
+/* Free any memory that info_ptr points to and reset struct. */
+PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_1_0_X
+/* Function to allocate memory for zlib. */
+PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
+
+/* Function to free memory for zlib */
+PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
+
+#ifdef PNG_SIZE_T
+/* Function to convert a sizeof an item to png_sizeof item */
+   PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
+#endif
+
+/* Next four functions are used internally as callbacks.  PNGAPI is required
+ * but not PNG_EXPORT.  PNGAPI added at libpng version 1.2.3. */
+
+PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t length));
+#endif
+
+PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+#if !defined(PNG_NO_STDIO)
+PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
+#endif
+#endif
+#else /* PNG_1_0_X */
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t length));
+#endif
+#endif /* PNG_1_0_X */
+
+/* Reset the CRC variable */
+PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
+
+/* Write the "data" buffer to whatever output you are using. */
+PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+/* Read data from whatever input you are using into the "data" buffer */
+PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+/* Read bytes into buf, and update png_ptr->crc */
+PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
+   png_size_t length));
+
+/* Decompress data in a chunk that uses compression */
+#if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
+    defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
+PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
+   int comp_type, png_charp chunkdata, png_size_t chunklength,
+   png_size_t prefix_length, png_size_t *data_length));
+#endif
+
+/* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
+PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
+
+/* Read the CRC from the file and compare it to the libpng calculated CRC */
+PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
+
+/* Calculate the CRC over a section of data.  Note that we are only
+ * passing a maximum of 64K on systems that have this as a memory limit,
+ * since this is the maximum buffer size we can specify.
+ */
+PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
+   png_size_t length));
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
+#endif
+
+
+/* Place a 32-bit number into a buffer in PNG byte order (big-endian).
+ * The only currently known PNG chunks that use signed numbers are
+ * the ancillary extension chunks, oFFs and pCAL.
+ */
+PNG_EXTERN void png_save_uint_32 PNGARG((png_bytep buf, png_uint_32 i));
+
+#if defined(PNG_WRITE_pCAL_SUPPORTED) || defined(PNG_WRITE_oFFs_SUPPORTED)
+PNG_EXTERN void png_save_int_32 PNGARG((png_bytep buf, png_int_32 i));
+#endif
+
+/* Place a 16-bit number into a buffer in PNG byte order.
+ * The parameter is declared unsigned int, not png_uint_16,
+ * just to avoid potential problems on pre-ANSI C compilers.
+ */
+PNG_EXTERN void png_save_uint_16 PNGARG((png_bytep buf, unsigned int i));
+
+/* simple function to write the signature */
+PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
+
+/* write various chunks */
+
+/* Write the IHDR chunk, and update the png_struct with the necessary
+ * information.
+ */
+PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
+   png_uint_32 height,
+   int bit_depth, int color_type, int compression_method, int filter_method,
+   int interlace_method));
+
+PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
+   png_uint_32 num_pal));
+
+PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
+
+#if defined(PNG_WRITE_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
+    file_gamma));
+#endif
+#endif
+
+#if defined(PNG_WRITE_sBIT_SUPPORTED)
+PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
+   int color_type));
+#endif
+
+#if defined(PNG_WRITE_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
+   double white_x, double white_y,
+   double red_x, double red_y, double green_x, double green_y,
+   double blue_x, double blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
+   png_fixed_point int_white_x, png_fixed_point int_white_y,
+   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+   png_fixed_point int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_WRITE_sRGB_SUPPORTED)
+PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
+   int intent));
+#endif
+
+#if defined(PNG_WRITE_iCCP_SUPPORTED)
+PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
+   png_charp name, int compression_type,
+   png_charp profile, int proflen));
+   /* Note to maintainer: profile should be png_bytep */
+#endif
+
+#if defined(PNG_WRITE_sPLT_SUPPORTED)
+PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
+   png_sPLT_tp palette));
+#endif
+
+#if defined(PNG_WRITE_tRNS_SUPPORTED)
+PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
+   png_color_16p values, int number, int color_type));
+#endif
+
+#if defined(PNG_WRITE_bKGD_SUPPORTED)
+PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
+   png_color_16p values, int color_type));
+#endif
+
+#if defined(PNG_WRITE_hIST_SUPPORTED)
+PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
+   int num_hist));
+#endif
+
+#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
+    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
+PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
+   png_charp key, png_charpp new_key));
+#endif
+
+#if defined(PNG_WRITE_tEXt_SUPPORTED)
+PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
+   png_charp text, png_size_t text_len));
+#endif
+
+#if defined(PNG_WRITE_zTXt_SUPPORTED)
+PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
+   png_charp text, png_size_t text_len, int compression));
+#endif
+
+#if defined(PNG_WRITE_iTXt_SUPPORTED)
+PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
+   int compression, png_charp key, png_charp lang, png_charp lang_key,
+   png_charp text));
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)  /* Added at version 1.0.14 and 1.2.4 */
+PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp text_ptr, int num_text));
+#endif
+
+#if defined(PNG_WRITE_oFFs_SUPPORTED)
+PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
+   png_int_32 x_offset, png_int_32 y_offset, int unit_type));
+#endif
+
+#if defined(PNG_WRITE_pCAL_SUPPORTED)
+PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
+   png_int_32 X0, png_int_32 X1, int type, int nparams,
+   png_charp units, png_charpp params));
+#endif
+
+#if defined(PNG_WRITE_pHYs_SUPPORTED)
+PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
+   png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
+   int unit_type));
+#endif
+
+#if defined(PNG_WRITE_tIME_SUPPORTED)
+PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
+   png_timep mod_time));
+#endif
+
+#if defined(PNG_WRITE_sCAL_SUPPORTED)
+#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
+PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
+   int unit, double width, double height));
+#else
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
+   int unit, png_charp width, png_charp height));
+#endif
+#endif
+#endif
+
+/* Called when finished processing a row of data */
+PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
+
+/* Internal use only.   Called before first row of data */
+PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
+#endif
+
+/* combine a row of data, dealing with alpha, etc. if requested */
+PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
+   int mask));
+
+#if defined(PNG_READ_INTERLACING_SUPPORTED)
+/* expand an interlaced row */
+/* OLD pre-1.0.9 interface:
+PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
+   png_bytep row, int pass, png_uint_32 transformations));
+ */
+PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
+#endif
+
+/* GRR TO DO (2.0 or whenever):  simplify other internal calling interfaces */
+
+#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
+/* grab pixels out of a row for an interlaced pass */
+PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
+   png_bytep row, int pass));
+#endif
+
+/* unfilter a row */
+PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
+   png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
+
+/* Choose the best filter to use and filter the row data */
+PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
+   png_row_infop row_info));
+
+/* Write out the filtered row. */
+PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
+   png_bytep filtered_row));
+/* finish a row while reading, dealing with interlacing passes, etc. */
+PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
+
+/* initialize the row buffers, etc. */
+PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
+/* optional call to update the users info structure */
+PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+/* these are the functions that do the transformations */
+#if defined(PNG_READ_FILLER_SUPPORTED)
+PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 filler, png_uint_32 flags));
+#endif
+
+#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
+    defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 flags));
+#endif
+
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
+   row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
+PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_READ_PACK_SUPPORTED)
+PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED)
+PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_8p sig_bits));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_16_TO_8_SUPPORTED)
+PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
+   png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
+
+#  if defined(PNG_CORRECT_PALETTE_SUPPORTED)
+PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
+   png_colorp palette, int num_palette));
+#  endif
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_PACK_SUPPORTED)
+PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 bit_depth));
+#endif
+
+#if defined(PNG_WRITE_SHIFT_SUPPORTED)
+PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_8p bit_depth));
+#endif
+
+#if defined(PNG_READ_BACKGROUND_SUPPORTED)
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_16p trans_values, png_color_16p background,
+   png_color_16p background_1,
+   png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
+   png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
+   png_uint_16pp gamma_16_to_1, int gamma_shift));
+#else
+PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_16p trans_values, png_color_16p background));
+#endif
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
+   png_bytep gamma_table, png_uint_16pp gamma_16_table,
+   int gamma_shift));
+#endif
+
+#if defined(PNG_READ_EXPAND_SUPPORTED)
+PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
+   png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
+PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
+   png_bytep row, png_color_16p trans_value));
+#endif
+
+/* The following decodes the appropriate chunks, and does error correction,
+ * then calls the appropriate callback for the chunk if it is valid.
+ */
+
+/* decode the IHDR chunk */
+PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+
+#if defined(PNG_READ_bKGD_SUPPORTED)
+PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_cHRM_SUPPORTED)
+PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_gAMA_SUPPORTED)
+PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_hIST_SUPPORTED)
+PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_iCCP_SUPPORTED)
+extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif /* PNG_READ_iCCP_SUPPORTED */
+
+#if defined(PNG_READ_iTXt_SUPPORTED)
+PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_oFFs_SUPPORTED)
+PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_pCAL_SUPPORTED)
+PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_pHYs_SUPPORTED)
+PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sBIT_SUPPORTED)
+PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sCAL_SUPPORTED)
+PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sPLT_SUPPORTED)
+extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif /* PNG_READ_sPLT_SUPPORTED */
+
+#if defined(PNG_READ_sRGB_SUPPORTED)
+PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tEXt_SUPPORTED)
+PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tIME_SUPPORTED)
+PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tRNS_SUPPORTED)
+PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_zTXt_SUPPORTED)
+PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+
+PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
+   png_bytep chunk_name));
+
+/* handle the transformations for reading and writing */
+PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
+
+PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
+PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
+#if defined(PNG_READ_tEXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+#if defined(PNG_READ_zTXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+#if defined(PNG_READ_iTXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
+   png_bytep row));
+PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+/* png.c */ /* PRIVATE */
+PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
+#endif
+/* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
+
+#endif /* PNG_INTERNAL */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PNG_VERSION_INFO_ONLY */
+/* do not put anything past this line */
+#endif /* PNG_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng/pngconf.h ./aperios/include/libpng/pngconf.h
--- ../Tekkotsu_2.3/aperios/include/libpng/pngconf.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng/pngconf.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,1437 @@
+
+/* pngconf.h - machine configurable file for libpng
+ *
+ * libpng version 1.2.8 - December 3, 2004
+ * For conditions of distribution and use, see copyright notice in png.h
+ * Copyright (c) 1998-2004 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ */
+
+/* Any machine specific code is near the front of this file, so if you
+ * are configuring libpng for a machine, you may want to read the section
+ * starting here down to where it starts to typedef png_color, png_text,
+ * and png_info.
+ */
+
+#ifndef PNGCONF_H
+#define PNGCONF_H
+
+#define PNG_1_2_X
+
+/* 
+ * PNG_USER_CONFIG has to be defined on the compiler command line. This
+ * includes the resource compiler for Windows DLL configurations.
+ */
+#ifdef PNG_USER_CONFIG
+#include "pngusr.h"
+#endif
+
+/*
+ * Added at libpng-1.2.8
+ *  
+ * If you create a private DLL you need to define in "pngusr.h" the followings:
+ * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
+ *        the DLL was built>
+ *  e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
+ * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
+ *        distinguish your DLL from those of the official release. These
+ *        correspond to the trailing letters that come after the version
+ *        number and must match your private DLL name>
+ *  e.g. // private DLL "libpng13gx.dll"
+ *       #define PNG_USER_DLLFNAME_POSTFIX "gx"
+ * 
+ * The following macros are also at your disposal if you want to complete the 
+ * DLL VERSIONINFO structure.
+ * - PNG_USER_VERSIONINFO_COMMENTS
+ * - PNG_USER_VERSIONINFO_COMPANYNAME
+ * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
+ */
+
+#ifdef __STDC__
+#ifdef SPECIALBUILD
+#  pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
+ are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
+#endif
+
+#ifdef PRIVATEBUILD
+# pragma message("PRIVATEBUILD is deprecated. Use\
+ PNG_USER_PRIVATEBUILD instead.")
+# define PNG_USER_PRIVATEBUILD PRIVATEBUILD
+#endif
+#endif /* __STDC__ */
+
+#ifndef PNG_VERSION_INFO_ONLY
+
+/* End of material added to libpng-1.2.8 */
+
+/* This is the size of the compression buffer, and thus the size of
+ * an IDAT chunk.  Make this whatever size you feel is best for your
+ * machine.  One of these will be allocated per png_struct.  When this
+ * is full, it writes the data to the disk, and does some other
+ * calculations.  Making this an extremely small size will slow
+ * the library down, but you may want to experiment to determine
+ * where it becomes significant, if you are concerned with memory
+ * usage.  Note that zlib allocates at least 32Kb also.  For readers,
+ * this describes the size of the buffer available to read the data in.
+ * Unless this gets smaller than the size of a row (compressed),
+ * it should not make much difference how big this is.
+ */
+
+#ifndef PNG_ZBUF_SIZE
+#  define PNG_ZBUF_SIZE 8192
+#endif
+
+/* Enable if you want a write-only libpng */
+
+#ifndef PNG_NO_READ_SUPPORTED
+#  define PNG_READ_SUPPORTED
+#endif
+
+/* Enable if you want a read-only libpng */
+
+#ifndef PNG_NO_WRITE_SUPPORTED
+#  define PNG_WRITE_SUPPORTED
+#endif
+
+/* Enabled by default in 1.2.0.  You can disable this if you don't need to
+   support PNGs that are embedded in MNG datastreams */
+#if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
+#  ifndef PNG_MNG_FEATURES_SUPPORTED
+#    define PNG_MNG_FEATURES_SUPPORTED
+#  endif
+#endif
+
+#ifndef PNG_NO_FLOATING_POINT_SUPPORTED
+#  ifndef PNG_FLOATING_POINT_SUPPORTED
+#    define PNG_FLOATING_POINT_SUPPORTED
+#  endif
+#endif
+
+/* If you are running on a machine where you cannot allocate more
+ * than 64K of memory at once, uncomment this.  While libpng will not
+ * normally need that much memory in a chunk (unless you load up a very
+ * large file), zlib needs to know how big of a chunk it can use, and
+ * libpng thus makes sure to check any memory allocation to verify it
+ * will fit into memory.
+#define PNG_MAX_MALLOC_64K
+ */
+#if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
+#  define PNG_MAX_MALLOC_64K
+#endif
+
+/* Special munging to support doing things the 'cygwin' way:
+ * 'Normal' png-on-win32 defines/defaults:
+ *   PNG_BUILD_DLL -- building dll
+ *   PNG_USE_DLL   -- building an application, linking to dll
+ *   (no define)   -- building static library, or building an
+ *                    application and linking to the static lib
+ * 'Cygwin' defines/defaults:
+ *   PNG_BUILD_DLL -- (ignored) building the dll
+ *   (no define)   -- (ignored) building an application, linking to the dll
+ *   PNG_STATIC    -- (ignored) building the static lib, or building an 
+ *                    application that links to the static lib.
+ *   ALL_STATIC    -- (ignored) building various static libs, or building an 
+ *                    application that links to the static libs.
+ * Thus,
+ * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
+ * this bit of #ifdefs will define the 'correct' config variables based on
+ * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
+ * unnecessary.
+ *
+ * Also, the precedence order is:
+ *   ALL_STATIC (since we can't #undef something outside our namespace)
+ *   PNG_BUILD_DLL
+ *   PNG_STATIC
+ *   (nothing) == PNG_USE_DLL
+ * 
+ * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
+ *   of auto-import in binutils, we no longer need to worry about 
+ *   __declspec(dllexport) / __declspec(dllimport) and friends.  Therefore,
+ *   we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
+ *   to __declspec() stuff.  However, we DO need to worry about 
+ *   PNG_BUILD_DLL and PNG_STATIC because those change some defaults
+ *   such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
+ */
+#if defined(__CYGWIN__)
+#  if defined(ALL_STATIC)
+#    if defined(PNG_BUILD_DLL)
+#      undef PNG_BUILD_DLL
+#    endif
+#    if defined(PNG_USE_DLL)
+#      undef PNG_USE_DLL
+#    endif
+#    if defined(PNG_DLL)
+#      undef PNG_DLL
+#    endif
+#    if !defined(PNG_STATIC)
+#      define PNG_STATIC
+#    endif
+#  else
+#    if defined (PNG_BUILD_DLL)
+#      if defined(PNG_STATIC)
+#        undef PNG_STATIC
+#      endif
+#      if defined(PNG_USE_DLL)
+#        undef PNG_USE_DLL
+#      endif
+#      if !defined(PNG_DLL)
+#        define PNG_DLL
+#      endif
+#    else
+#      if defined(PNG_STATIC)
+#        if defined(PNG_USE_DLL)
+#          undef PNG_USE_DLL
+#        endif
+#        if defined(PNG_DLL)
+#          undef PNG_DLL
+#        endif
+#      else
+#        if !defined(PNG_USE_DLL)
+#          define PNG_USE_DLL
+#        endif
+#        if !defined(PNG_DLL)
+#          define PNG_DLL
+#        endif
+#      endif  
+#    endif  
+#  endif
+#endif
+
+/* This protects us against compilers that run on a windowing system
+ * and thus don't have or would rather us not use the stdio types:
+ * stdin, stdout, and stderr.  The only one currently used is stderr
+ * in png_error() and png_warning().  #defining PNG_NO_CONSOLE_IO will
+ * prevent these from being compiled and used. #defining PNG_NO_STDIO
+ * will also prevent these, plus will prevent the entire set of stdio
+ * macros and functions (FILE *, printf, etc.) from being compiled and used,
+ * unless (PNG_DEBUG > 0) has been #defined.
+ *
+ * #define PNG_NO_CONSOLE_IO
+ * #define PNG_NO_STDIO
+ */
+
+#if defined(_WIN32_WCE)
+#  include <windows.h>
+   /* Console I/O functions are not supported on WindowsCE */
+#  define PNG_NO_CONSOLE_IO
+#  ifdef PNG_DEBUG
+#    undef PNG_DEBUG
+#  endif
+#endif
+
+#ifdef PNG_BUILD_DLL
+#  ifndef PNG_CONSOLE_IO_SUPPORTED
+#    ifndef PNG_NO_CONSOLE_IO
+#      define PNG_NO_CONSOLE_IO
+#    endif
+#  endif
+#endif
+
+#  ifdef PNG_NO_STDIO
+#    ifndef PNG_NO_CONSOLE_IO
+#      define PNG_NO_CONSOLE_IO
+#    endif
+#    ifdef PNG_DEBUG
+#      if (PNG_DEBUG > 0)
+#        include <stdio.h>
+#      endif
+#    endif
+#  else
+#    if !defined(_WIN32_WCE)
+/* "stdio.h" functions are not supported on WindowsCE */
+#      include <stdio.h>
+#    endif
+#  endif
+
+/* This macro protects us against machines that don't have function
+ * prototypes (ie K&R style headers).  If your compiler does not handle
+ * function prototypes, define this macro and use the included ansi2knr.
+ * I've always been able to use _NO_PROTO as the indicator, but you may
+ * need to drag the empty declaration out in front of here, or change the
+ * ifdef to suit your own needs.
+ */
+#ifndef PNGARG
+
+#ifdef OF /* zlib prototype munger */
+#  define PNGARG(arglist) OF(arglist)
+#else
+
+#ifdef _NO_PROTO
+#  define PNGARG(arglist) ()
+#  ifndef PNG_TYPECAST_NULL
+#     define PNG_TYPECAST_NULL
+#  endif
+#else
+#  define PNGARG(arglist) arglist
+#endif /* _NO_PROTO */
+
+#endif /* OF */
+
+#endif /* PNGARG */
+
+/* Try to determine if we are compiling on a Mac.  Note that testing for
+ * just __MWERKS__ is not good enough, because the Codewarrior is now used
+ * on non-Mac platforms.
+ */
+#ifndef MACOS
+#  if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
+      defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
+#    define MACOS
+#  endif
+#endif
+
+/* enough people need this for various reasons to include it here */
+#if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
+#  include <sys/types.h>
+#endif
+
+#if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
+#  define PNG_SETJMP_SUPPORTED
+#endif
+
+#ifdef PNG_SETJMP_SUPPORTED
+/* This is an attempt to force a single setjmp behaviour on Linux.  If
+ * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
+ */
+
+#  ifdef __linux__
+#    ifdef _BSD_SOURCE
+#      define PNG_SAVE_BSD_SOURCE
+#      undef _BSD_SOURCE
+#    endif
+#    ifdef _SETJMP_H
+     /* If you encounter a compiler error here, see the explanation
+      * near the end of INSTALL.
+      */
+         __png.h__ already includes setjmp.h;
+         __dont__ include it again.;
+#    endif
+#  endif /* __linux__ */
+
+   /* include setjmp.h for error handling */
+#  include <setjmp.h>
+
+#  ifdef __linux__
+#    ifdef PNG_SAVE_BSD_SOURCE
+#      define _BSD_SOURCE
+#      undef PNG_SAVE_BSD_SOURCE
+#    endif
+#  endif /* __linux__ */
+#endif /* PNG_SETJMP_SUPPORTED */
+
+#ifdef BSD
+#  include <strings.h>
+#else
+#  include <string.h>
+#endif
+
+/* Other defines for things like memory and the like can go here.  */
+#ifdef PNG_INTERNAL
+
+#include <stdlib.h>
+
+/* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
+ * aren't usually used outside the library (as far as I know), so it is
+ * debatable if they should be exported at all.  In the future, when it is
+ * possible to have run-time registry of chunk-handling functions, some of
+ * these will be made available again.
+#define PNG_EXTERN extern
+ */
+#define PNG_EXTERN
+
+/* Other defines specific to compilers can go here.  Try to keep
+ * them inside an appropriate ifdef/endif pair for portability.
+ */
+
+#if defined(PNG_FLOATING_POINT_SUPPORTED)
+#  if defined(MACOS)
+     /* We need to check that <math.h> hasn't already been included earlier
+      * as it seems it doesn't agree with <fp.h>, yet we should really use
+      * <fp.h> if possible.
+      */
+#    if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
+#      include <fp.h>
+#    endif
+#  else
+#    include <math.h>
+#  endif
+#  if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
+     /* Amiga SAS/C: We must include builtin FPU functions when compiling using
+      * MATH=68881
+      */
+#    include <m68881.h>
+#  endif
+#endif
+
+/* Codewarrior on NT has linking problems without this. */
+#if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
+#  define PNG_ALWAYS_EXTERN
+#endif
+
+/* This provides the non-ANSI (far) memory allocation routines. */
+#if defined(__TURBOC__) && defined(__MSDOS__)
+#  include <mem.h>
+#  include <alloc.h>
+#endif
+
+/* I have no idea why is this necessary... */
+#if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
+    defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
+#  include <malloc.h>
+#endif
+
+/* This controls how fine the dithering gets.  As this allocates
+ * a largish chunk of memory (32K), those who are not as concerned
+ * with dithering quality can decrease some or all of these.
+ */
+#ifndef PNG_DITHER_RED_BITS
+#  define PNG_DITHER_RED_BITS 5
+#endif
+#ifndef PNG_DITHER_GREEN_BITS
+#  define PNG_DITHER_GREEN_BITS 5
+#endif
+#ifndef PNG_DITHER_BLUE_BITS
+#  define PNG_DITHER_BLUE_BITS 5
+#endif
+
+/* This controls how fine the gamma correction becomes when you
+ * are only interested in 8 bits anyway.  Increasing this value
+ * results in more memory being used, and more pow() functions
+ * being called to fill in the gamma tables.  Don't set this value
+ * less then 8, and even that may not work (I haven't tested it).
+ */
+
+#ifndef PNG_MAX_GAMMA_8
+#  define PNG_MAX_GAMMA_8 11
+#endif
+
+/* This controls how much a difference in gamma we can tolerate before
+ * we actually start doing gamma conversion.
+ */
+#ifndef PNG_GAMMA_THRESHOLD
+#  define PNG_GAMMA_THRESHOLD 0.05
+#endif
+
+#endif /* PNG_INTERNAL */
+
+/* The following uses const char * instead of char * for error
+ * and warning message functions, so some compilers won't complain.
+ * If you do not want to use const, define PNG_NO_CONST here.
+ */
+
+#ifndef PNG_NO_CONST
+#  define PNG_CONST const
+#else
+#  define PNG_CONST
+#endif
+
+/* The following defines give you the ability to remove code from the
+ * library that you will not be using.  I wish I could figure out how to
+ * automate this, but I can't do that without making it seriously hard
+ * on the users.  So if you are not using an ability, change the #define
+ * to and #undef, and that part of the library will not be compiled.  If
+ * your linker can't find a function, you may want to make sure the
+ * ability is defined here.  Some of these depend upon some others being
+ * defined.  I haven't figured out all the interactions here, so you may
+ * have to experiment awhile to get everything to compile.  If you are
+ * creating or using a shared library, you probably shouldn't touch this,
+ * as it will affect the size of the structures, and this will cause bad
+ * things to happen if the library and/or application ever change.
+ */
+
+/* Any features you will not be using can be undef'ed here */
+
+/* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
+ * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
+ * on the compile line, then pick and choose which ones to define without
+ * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
+ * if you only want to have a png-compliant reader/writer but don't need
+ * any of the extra transformations.  This saves about 80 kbytes in a
+ * typical installation of the library. (PNG_NO_* form added in version
+ * 1.0.1c, for consistency)
+ */
+
+/* The size of the png_text structure changed in libpng-1.0.6 when
+ * iTXt is supported.  It is turned off by default, to support old apps
+ * that malloc the png_text structure instead of calling png_set_text()
+ * and letting libpng malloc it.  It will be turned on by default in
+ * libpng-1.3.0.
+ */
+
+#ifndef PNG_iTXt_SUPPORTED
+#  if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
+#    define PNG_NO_READ_iTXt
+#  endif
+#  if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
+#    define PNG_NO_WRITE_iTXt
+#  endif
+#endif
+
+/* The following support, added after version 1.0.0, can be turned off here en
+ * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
+ * with old applications that require the length of png_struct and png_info
+ * to remain unchanged.
+ */
+
+#ifdef PNG_LEGACY_SUPPORTED
+#  define PNG_NO_FREE_ME
+#  define PNG_NO_READ_UNKNOWN_CHUNKS
+#  define PNG_NO_WRITE_UNKNOWN_CHUNKS
+#  define PNG_NO_READ_USER_CHUNKS
+#  define PNG_NO_READ_iCCP
+#  define PNG_NO_WRITE_iCCP
+#  define PNG_NO_READ_iTXt
+#  define PNG_NO_WRITE_iTXt
+#  define PNG_NO_READ_sCAL
+#  define PNG_NO_WRITE_sCAL
+#  define PNG_NO_READ_sPLT
+#  define PNG_NO_WRITE_sPLT
+#  define PNG_NO_INFO_IMAGE
+#  define PNG_NO_READ_RGB_TO_GRAY
+#  define PNG_NO_READ_USER_TRANSFORM
+#  define PNG_NO_WRITE_USER_TRANSFORM
+#  define PNG_NO_USER_MEM
+#  define PNG_NO_READ_EMPTY_PLTE
+#  define PNG_NO_MNG_FEATURES
+#  define PNG_NO_FIXED_POINT_SUPPORTED
+#endif
+
+/* Ignore attempt to turn off both floating and fixed point support */
+#if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
+    !defined(PNG_NO_FIXED_POINT_SUPPORTED)
+#  define PNG_FIXED_POINT_SUPPORTED
+#endif
+
+#ifndef PNG_NO_FREE_ME
+#  define PNG_FREE_ME_SUPPORTED
+#endif
+
+#if defined(PNG_READ_SUPPORTED)
+
+#if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
+      !defined(PNG_NO_READ_TRANSFORMS)
+#  define PNG_READ_TRANSFORMS_SUPPORTED
+#endif
+
+#ifdef PNG_READ_TRANSFORMS_SUPPORTED
+#  ifndef PNG_NO_READ_EXPAND
+#    define PNG_READ_EXPAND_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SHIFT
+#    define PNG_READ_SHIFT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_PACK
+#    define PNG_READ_PACK_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_BGR
+#    define PNG_READ_BGR_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SWAP
+#    define PNG_READ_SWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_PACKSWAP
+#    define PNG_READ_PACKSWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_INVERT
+#    define PNG_READ_INVERT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_DITHER
+#    define PNG_READ_DITHER_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_BACKGROUND
+#    define PNG_READ_BACKGROUND_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_16_TO_8
+#    define PNG_READ_16_TO_8_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_FILLER
+#    define PNG_READ_FILLER_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_GAMMA
+#    define PNG_READ_GAMMA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_GRAY_TO_RGB
+#    define PNG_READ_GRAY_TO_RGB_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SWAP_ALPHA
+#    define PNG_READ_SWAP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_INVERT_ALPHA
+#    define PNG_READ_INVERT_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_STRIP_ALPHA
+#    define PNG_READ_STRIP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_USER_TRANSFORM
+#    define PNG_READ_USER_TRANSFORM_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_RGB_TO_GRAY
+#    define PNG_READ_RGB_TO_GRAY_SUPPORTED
+#  endif
+#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
+
+#if !defined(PNG_NO_PROGRESSIVE_READ) && \
+ !defined(PNG_PROGRESSIVE_READ_NOT_SUPPORTED)  /* if you don't do progressive */
+#  define PNG_PROGRESSIVE_READ_SUPPORTED     /* reading.  This is not talking */
+#endif                               /* about interlacing capability!  You'll */
+              /* still have interlacing unless you change the following line: */
+
+#define PNG_READ_INTERLACING_SUPPORTED /* required for PNG-compliant decoders */
+
+#ifndef PNG_NO_READ_COMPOSITE_NODIV
+#  ifndef PNG_NO_READ_COMPOSITED_NODIV  /* libpng-1.0.x misspelling */
+#    define PNG_READ_COMPOSITE_NODIV_SUPPORTED   /* well tested on Intel, SGI */
+#  endif
+#endif
+
+/* Deprecated, will be removed from version 2.0.0.
+   Use PNG_MNG_FEATURES_SUPPORTED instead. */
+#ifndef PNG_NO_READ_EMPTY_PLTE
+#  define PNG_READ_EMPTY_PLTE_SUPPORTED
+#endif
+
+#endif /* PNG_READ_SUPPORTED */
+
+#if defined(PNG_WRITE_SUPPORTED)
+
+# if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_WRITE_TRANSFORMS)
+#  define PNG_WRITE_TRANSFORMS_SUPPORTED
+#endif
+
+#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
+#  ifndef PNG_NO_WRITE_SHIFT
+#    define PNG_WRITE_SHIFT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_PACK
+#    define PNG_WRITE_PACK_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_BGR
+#    define PNG_WRITE_BGR_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_SWAP
+#    define PNG_WRITE_SWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_PACKSWAP
+#    define PNG_WRITE_PACKSWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_INVERT
+#    define PNG_WRITE_INVERT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_FILLER
+#    define PNG_WRITE_FILLER_SUPPORTED   /* same as WRITE_STRIP_ALPHA */
+#  endif
+#  ifndef PNG_NO_WRITE_SWAP_ALPHA
+#    define PNG_WRITE_SWAP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_INVERT_ALPHA
+#    define PNG_WRITE_INVERT_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_USER_TRANSFORM
+#    define PNG_WRITE_USER_TRANSFORM_SUPPORTED
+#  endif
+#endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
+
+#define PNG_WRITE_INTERLACING_SUPPORTED  /* not required for PNG-compliant
+                                            encoders, but can cause trouble
+                                            if left undefined */
+
+#if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
+     defined(PNG_FLOATING_POINT_SUPPORTED)
+#  define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
+#endif
+
+#ifndef PNG_NO_WRITE_FLUSH
+#  define PNG_WRITE_FLUSH_SUPPORTED
+#endif
+
+/* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
+#ifndef PNG_NO_WRITE_EMPTY_PLTE
+#  define PNG_WRITE_EMPTY_PLTE_SUPPORTED
+#endif
+
+#endif /* PNG_WRITE_SUPPORTED */
+
+#ifndef PNG_1_0_X
+#  ifndef PNG_NO_ERROR_NUMBERS
+#    define PNG_ERROR_NUMBERS_SUPPORTED
+#  endif
+#endif /* PNG_1_0_X */
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+#  ifndef PNG_NO_USER_TRANSFORM_PTR
+#    define PNG_USER_TRANSFORM_PTR_SUPPORTED
+#  endif
+#endif
+
+#ifndef PNG_NO_STDIO
+#  define PNG_TIME_RFC1123_SUPPORTED
+#endif
+
+/* This adds extra functions in pngget.c for accessing data from the
+ * info pointer (added in version 0.99)
+ * png_get_image_width()
+ * png_get_image_height()
+ * png_get_bit_depth()
+ * png_get_color_type()
+ * png_get_compression_type()
+ * png_get_filter_type()
+ * png_get_interlace_type()
+ * png_get_pixel_aspect_ratio()
+ * png_get_pixels_per_meter()
+ * png_get_x_offset_pixels()
+ * png_get_y_offset_pixels()
+ * png_get_x_offset_microns()
+ * png_get_y_offset_microns()
+ */
+#if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
+#  define PNG_EASY_ACCESS_SUPPORTED
+#endif
+
+/* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0 
+   even when PNG_USE_PNGVCRD or PNG_USE_PNGGCCRD is not defined */
+#if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
+#  ifndef PNG_ASSEMBLER_CODE_SUPPORTED
+#    define PNG_ASSEMBLER_CODE_SUPPORTED
+#  endif
+#  if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
+#    define PNG_MMX_CODE_SUPPORTED
+#  endif
+#endif
+
+/* If you are sure that you don't need thread safety and you are compiling
+   with PNG_USE_PNGCCRD for an MMX application, you can define this for
+   faster execution.  See pnggccrd.c.
+#define PNG_THREAD_UNSAFE_OK
+*/
+
+#if !defined(PNG_1_0_X)
+#if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
+#  define PNG_USER_MEM_SUPPORTED
+#endif
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.2.6 */
+#if !defined(PNG_1_0_X)
+#ifndef PNG_SET_USER_LIMITS_SUPPORTED
+#if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
+#  define PNG_SET_USER_LIMITS_SUPPORTED
+#endif
+#endif
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.0.16 and 1.2.6.  To accept all valid PNGS no matter
+ * how large, set these limits to 0x7fffffffL
+ */
+#ifndef PNG_USER_WIDTH_MAX
+#  define PNG_USER_WIDTH_MAX 1000000L
+#endif
+#ifndef PNG_USER_HEIGHT_MAX
+#  define PNG_USER_HEIGHT_MAX 1000000L
+#endif
+
+/* These are currently experimental features, define them if you want */
+
+/* very little testing */
+/*
+#ifdef PNG_READ_SUPPORTED
+#  ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
+#    define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
+#  endif
+#endif
+*/
+
+/* This is only for PowerPC big-endian and 680x0 systems */
+/* some testing */
+/*
+#ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
+#  define PNG_READ_BIG_ENDIAN_SUPPORTED
+#endif
+*/
+
+/* Buggy compilers (e.g., gcc 2.7.2.2) need this */
+/*
+#define PNG_NO_POINTER_INDEXING
+*/
+
+/* These functions are turned off by default, as they will be phased out. */
+/*
+#define  PNG_USELESS_TESTS_SUPPORTED
+#define  PNG_CORRECT_PALETTE_SUPPORTED
+*/
+
+/* Any chunks you are not interested in, you can undef here.  The
+ * ones that allocate memory may be expecially important (hIST,
+ * tEXt, zTXt, tRNS, pCAL).  Others will just save time and make png_info
+ * a bit smaller.
+ */
+
+#if defined(PNG_READ_SUPPORTED) && \
+    !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
+#  define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
+#endif
+
+#if defined(PNG_WRITE_SUPPORTED) && \
+    !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
+#  define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
+#endif
+
+#ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
+
+#ifdef PNG_NO_READ_TEXT
+#  define PNG_NO_READ_iTXt
+#  define PNG_NO_READ_tEXt
+#  define PNG_NO_READ_zTXt
+#endif
+#ifndef PNG_NO_READ_bKGD
+#  define PNG_READ_bKGD_SUPPORTED
+#  define PNG_bKGD_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_cHRM
+#  define PNG_READ_cHRM_SUPPORTED
+#  define PNG_cHRM_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_gAMA
+#  define PNG_READ_gAMA_SUPPORTED
+#  define PNG_gAMA_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_hIST
+#  define PNG_READ_hIST_SUPPORTED
+#  define PNG_hIST_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_iCCP
+#  define PNG_READ_iCCP_SUPPORTED
+#  define PNG_iCCP_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_iTXt
+#  ifndef PNG_READ_iTXt_SUPPORTED
+#    define PNG_READ_iTXt_SUPPORTED
+#  endif
+#  ifndef PNG_iTXt_SUPPORTED
+#    define PNG_iTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_READ_oFFs
+#  define PNG_READ_oFFs_SUPPORTED
+#  define PNG_oFFs_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_pCAL
+#  define PNG_READ_pCAL_SUPPORTED
+#  define PNG_pCAL_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sCAL
+#  define PNG_READ_sCAL_SUPPORTED
+#  define PNG_sCAL_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_pHYs
+#  define PNG_READ_pHYs_SUPPORTED
+#  define PNG_pHYs_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sBIT
+#  define PNG_READ_sBIT_SUPPORTED
+#  define PNG_sBIT_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sPLT
+#  define PNG_READ_sPLT_SUPPORTED
+#  define PNG_sPLT_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sRGB
+#  define PNG_READ_sRGB_SUPPORTED
+#  define PNG_sRGB_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tEXt
+#  define PNG_READ_tEXt_SUPPORTED
+#  define PNG_tEXt_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tIME
+#  define PNG_READ_tIME_SUPPORTED
+#  define PNG_tIME_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tRNS
+#  define PNG_READ_tRNS_SUPPORTED
+#  define PNG_tRNS_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_zTXt
+#  define PNG_READ_zTXt_SUPPORTED
+#  define PNG_zTXt_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_UNKNOWN_CHUNKS
+#  define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
+#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
+#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
+#  endif
+#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
+#    define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#  endif
+#endif
+#if !defined(PNG_NO_READ_USER_CHUNKS) && \
+     defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
+#  define PNG_READ_USER_CHUNKS_SUPPORTED
+#  define PNG_USER_CHUNKS_SUPPORTED
+#  ifdef PNG_NO_READ_UNKNOWN_CHUNKS
+#    undef PNG_NO_READ_UNKNOWN_CHUNKS
+#  endif
+#  ifdef PNG_NO_HANDLE_AS_UNKNOWN
+#    undef PNG_NO_HANDLE_AS_UNKNOWN
+#  endif
+#endif
+#ifndef PNG_NO_READ_OPT_PLTE
+#  define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
+#endif                      /* optional PLTE chunk in RGB and RGBA images */
+#if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
+    defined(PNG_READ_zTXt_SUPPORTED)
+#  define PNG_READ_TEXT_SUPPORTED
+#  define PNG_TEXT_SUPPORTED
+#endif
+
+#endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
+
+#ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
+
+#ifdef PNG_NO_WRITE_TEXT
+#  define PNG_NO_WRITE_iTXt
+#  define PNG_NO_WRITE_tEXt
+#  define PNG_NO_WRITE_zTXt
+#endif
+#ifndef PNG_NO_WRITE_bKGD
+#  define PNG_WRITE_bKGD_SUPPORTED
+#  ifndef PNG_bKGD_SUPPORTED
+#    define PNG_bKGD_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_cHRM
+#  define PNG_WRITE_cHRM_SUPPORTED
+#  ifndef PNG_cHRM_SUPPORTED
+#    define PNG_cHRM_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_gAMA
+#  define PNG_WRITE_gAMA_SUPPORTED
+#  ifndef PNG_gAMA_SUPPORTED
+#    define PNG_gAMA_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_hIST
+#  define PNG_WRITE_hIST_SUPPORTED
+#  ifndef PNG_hIST_SUPPORTED
+#    define PNG_hIST_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_iCCP
+#  define PNG_WRITE_iCCP_SUPPORTED
+#  ifndef PNG_iCCP_SUPPORTED
+#    define PNG_iCCP_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_iTXt
+#  ifndef PNG_WRITE_iTXt_SUPPORTED
+#    define PNG_WRITE_iTXt_SUPPORTED
+#  endif
+#  ifndef PNG_iTXt_SUPPORTED
+#    define PNG_iTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_oFFs
+#  define PNG_WRITE_oFFs_SUPPORTED
+#  ifndef PNG_oFFs_SUPPORTED
+#    define PNG_oFFs_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_pCAL
+#  define PNG_WRITE_pCAL_SUPPORTED
+#  ifndef PNG_pCAL_SUPPORTED
+#    define PNG_pCAL_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sCAL
+#  define PNG_WRITE_sCAL_SUPPORTED
+#  ifndef PNG_sCAL_SUPPORTED
+#    define PNG_sCAL_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_pHYs
+#  define PNG_WRITE_pHYs_SUPPORTED
+#  ifndef PNG_pHYs_SUPPORTED
+#    define PNG_pHYs_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sBIT
+#  define PNG_WRITE_sBIT_SUPPORTED
+#  ifndef PNG_sBIT_SUPPORTED
+#    define PNG_sBIT_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sPLT
+#  define PNG_WRITE_sPLT_SUPPORTED
+#  ifndef PNG_sPLT_SUPPORTED
+#    define PNG_sPLT_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sRGB
+#  define PNG_WRITE_sRGB_SUPPORTED
+#  ifndef PNG_sRGB_SUPPORTED
+#    define PNG_sRGB_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tEXt
+#  define PNG_WRITE_tEXt_SUPPORTED
+#  ifndef PNG_tEXt_SUPPORTED
+#    define PNG_tEXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tIME
+#  define PNG_WRITE_tIME_SUPPORTED
+#  ifndef PNG_tIME_SUPPORTED
+#    define PNG_tIME_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tRNS
+#  define PNG_WRITE_tRNS_SUPPORTED
+#  ifndef PNG_tRNS_SUPPORTED
+#    define PNG_tRNS_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_zTXt
+#  define PNG_WRITE_zTXt_SUPPORTED
+#  ifndef PNG_zTXt_SUPPORTED
+#    define PNG_zTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
+#  define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
+#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
+#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
+#  endif
+#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
+#     ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#       define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#     endif
+#  endif
+#endif
+#if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
+    defined(PNG_WRITE_zTXt_SUPPORTED)
+#  define PNG_WRITE_TEXT_SUPPORTED
+#  ifndef PNG_TEXT_SUPPORTED
+#    define PNG_TEXT_SUPPORTED
+#  endif
+#endif
+
+#endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
+
+/* Turn this off to disable png_read_png() and
+ * png_write_png() and leave the row_pointers member
+ * out of the info structure.
+ */
+#ifndef PNG_NO_INFO_IMAGE
+#  define PNG_INFO_IMAGE_SUPPORTED
+#endif
+
+/* need the time information for reading tIME chunks */
+#if defined(PNG_tIME_SUPPORTED)
+#  if !defined(_WIN32_WCE)
+     /* "time.h" functions are not supported on WindowsCE */
+#    include <time.h>
+#  endif
+#endif
+
+/* Some typedefs to get us started.  These should be safe on most of the
+ * common platforms.  The typedefs should be at least as large as the
+ * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
+ * don't have to be exactly that size.  Some compilers dislike passing
+ * unsigned shorts as function parameters, so you may be better off using
+ * unsigned int for png_uint_16.  Likewise, for 64-bit systems, you may
+ * want to have unsigned int for png_uint_32 instead of unsigned long.
+ */
+
+typedef unsigned long png_uint_32;
+typedef long png_int_32;
+typedef unsigned short png_uint_16;
+typedef short png_int_16;
+typedef unsigned char png_byte;
+
+/* This is usually size_t.  It is typedef'ed just in case you need it to
+   change (I'm not sure if you will or not, so I thought I'd be safe) */
+#ifdef PNG_SIZE_T
+   typedef PNG_SIZE_T png_size_t;
+#  define png_sizeof(x) png_convert_size(sizeof (x))
+#else
+   typedef size_t png_size_t;
+#  define png_sizeof(x) sizeof (x)
+#endif
+
+/* The following is needed for medium model support.  It cannot be in the
+ * PNG_INTERNAL section.  Needs modification for other compilers besides
+ * MSC.  Model independent support declares all arrays and pointers to be
+ * large using the far keyword.  The zlib version used must also support
+ * model independent data.  As of version zlib 1.0.4, the necessary changes
+ * have been made in zlib.  The USE_FAR_KEYWORD define triggers other
+ * changes that are needed. (Tim Wegner)
+ */
+
+/* Separate compiler dependencies (problem here is that zlib.h always
+   defines FAR. (SJT) */
+#ifdef __BORLANDC__
+#  if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
+#    define LDATA 1
+#  else
+#    define LDATA 0
+#  endif
+   /* GRR:  why is Cygwin in here?  Cygwin is not Borland C... */
+#  if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
+#    define PNG_MAX_MALLOC_64K
+#    if (LDATA != 1)
+#      ifndef FAR
+#        define FAR __far
+#      endif
+#      define USE_FAR_KEYWORD
+#    endif   /* LDATA != 1 */
+     /* Possibly useful for moving data out of default segment.
+      * Uncomment it if you want. Could also define FARDATA as
+      * const if your compiler supports it. (SJT)
+#    define FARDATA FAR
+      */
+#  endif  /* __WIN32__, __FLAT__, __CYGWIN__ */
+#endif   /* __BORLANDC__ */
+
+
+/* Suggest testing for specific compiler first before testing for
+ * FAR.  The Watcom compiler defines both __MEDIUM__ and M_I86MM,
+ * making reliance oncertain keywords suspect. (SJT)
+ */
+
+/* MSC Medium model */
+#if defined(FAR)
+#  if defined(M_I86MM)
+#    define USE_FAR_KEYWORD
+#    define FARDATA FAR
+#    include <dos.h>
+#  endif
+#endif
+
+/* SJT: default case */
+#ifndef FAR
+#  define FAR
+#endif
+
+/* At this point FAR is always defined */
+#ifndef FARDATA
+#  define FARDATA
+#endif
+
+/* Typedef for floating-point numbers that are converted
+   to fixed-point with a multiple of 100,000, e.g., int_gamma */
+typedef png_int_32 png_fixed_point;
+
+/* Add typedefs for pointers */
+typedef void            FAR * png_voidp;
+typedef png_byte        FAR * png_bytep;
+typedef png_uint_32     FAR * png_uint_32p;
+typedef png_int_32      FAR * png_int_32p;
+typedef png_uint_16     FAR * png_uint_16p;
+typedef png_int_16      FAR * png_int_16p;
+typedef PNG_CONST char  FAR * png_const_charp;
+typedef char            FAR * png_charp;
+typedef png_fixed_point FAR * png_fixed_point_p;
+
+#ifndef PNG_NO_STDIO
+#if defined(_WIN32_WCE)
+typedef HANDLE                png_FILE_p;
+#else
+typedef FILE                * png_FILE_p;
+#endif
+#endif
+
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double          FAR * png_doublep;
+#endif
+
+/* Pointers to pointers; i.e. arrays */
+typedef png_byte        FAR * FAR * png_bytepp;
+typedef png_uint_32     FAR * FAR * png_uint_32pp;
+typedef png_int_32      FAR * FAR * png_int_32pp;
+typedef png_uint_16     FAR * FAR * png_uint_16pp;
+typedef png_int_16      FAR * FAR * png_int_16pp;
+typedef PNG_CONST char  FAR * FAR * png_const_charpp;
+typedef char            FAR * FAR * png_charpp;
+typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double          FAR * FAR * png_doublepp;
+#endif
+
+/* Pointers to pointers to pointers; i.e., pointer to array */
+typedef char            FAR * FAR * FAR * png_charppp;
+
+#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
+/* SPC -  Is this stuff deprecated? */
+/* It'll be removed as of libpng-1.3.0 - GR-P */
+/* libpng typedefs for types in zlib. If zlib changes
+ * or another compression library is used, then change these.
+ * Eliminates need to change all the source files.
+ */
+typedef charf *         png_zcharp;
+typedef charf * FAR *   png_zcharpp;
+typedef z_stream FAR *  png_zstreamp;
+#endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
+
+/*
+ * Define PNG_BUILD_DLL if the module being built is a Windows
+ * LIBPNG DLL.
+ *
+ * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
+ * It is equivalent to Microsoft predefined macro _DLL that is
+ * automatically defined when you compile using the share
+ * version of the CRT (C Run-Time library)
+ *
+ * The cygwin mods make this behavior a little different:
+ * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
+ * Define PNG_STATIC if you are building a static library for use with cygwin,
+ *   -or- if you are building an application that you want to link to the
+ *   static library.
+ * PNG_USE_DLL is defined by default (no user action needed) unless one of
+ *   the other flags is defined.
+ */
+
+#if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
+#  define PNG_DLL
+#endif
+/* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
+ * When building a static lib, default to no GLOBAL ARRAYS, but allow
+ * command-line override
+ */
+#if defined(__CYGWIN__)
+#  if !defined(PNG_STATIC)
+#    if defined(PNG_USE_GLOBAL_ARRAYS)
+#      undef PNG_USE_GLOBAL_ARRAYS
+#    endif
+#    if !defined(PNG_USE_LOCAL_ARRAYS)
+#      define PNG_USE_LOCAL_ARRAYS
+#    endif
+#  else
+#    if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
+#      if defined(PNG_USE_GLOBAL_ARRAYS)
+#        undef PNG_USE_GLOBAL_ARRAYS
+#      endif
+#    endif
+#  endif
+#  if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
+#    define PNG_USE_LOCAL_ARRAYS
+#  endif
+#endif
+
+/* Do not use global arrays (helps with building DLL's)
+ * They are no longer used in libpng itself, since version 1.0.5c,
+ * but might be required for some pre-1.0.5c applications.
+ */
+#if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
+#  if defined(PNG_NO_GLOBAL_ARRAYS) || (defined(__GNUC__) && defined(PNG_DLL))
+#    define PNG_USE_LOCAL_ARRAYS
+#  else
+#    define PNG_USE_GLOBAL_ARRAYS
+#  endif
+#endif
+
+#if defined(__CYGWIN__)
+#  undef PNGAPI
+#  define PNGAPI __cdecl
+#  undef PNG_IMPEXP
+#  define PNG_IMPEXP
+#endif  
+
+/* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
+ * you may get warnings regarding the linkage of png_zalloc and png_zfree.
+ * Don't ignore those warnings; you must also reset the default calling
+ * convention in your compiler to match your PNGAPI, and you must build
+ * zlib and your applications the same way you build libpng.
+ */
+
+#if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
+#  ifndef PNG_NO_MODULEDEF
+#    define PNG_NO_MODULEDEF
+#  endif
+#endif
+
+#if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
+#  define PNG_IMPEXP
+#endif
+
+#if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
+    (( defined(_Windows) || defined(_WINDOWS) || \
+       defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
+
+#  ifndef PNGAPI
+#     if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
+#        define PNGAPI __cdecl
+#     else
+#        define PNGAPI _cdecl
+#     endif
+#  endif
+
+#  if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
+       0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
+#     define PNG_IMPEXP
+#  endif
+
+#  if !defined(PNG_IMPEXP)
+
+#     define PNG_EXPORT_TYPE1(type,symbol)  PNG_IMPEXP type PNGAPI symbol
+#     define PNG_EXPORT_TYPE2(type,symbol)  type PNG_IMPEXP PNGAPI symbol
+
+      /* Borland/Microsoft */
+#     if defined(_MSC_VER) || defined(__BORLANDC__)
+#        if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
+#           define PNG_EXPORT PNG_EXPORT_TYPE1
+#        else
+#           define PNG_EXPORT PNG_EXPORT_TYPE2
+#           if defined(PNG_BUILD_DLL)
+#              define PNG_IMPEXP __export
+#           else
+#              define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
+                                                 VC++ */
+#           endif                             /* Exists in Borland C++ for
+                                                 C++ classes (== huge) */
+#        endif
+#     endif
+
+#     if !defined(PNG_IMPEXP)
+#        if defined(PNG_BUILD_DLL)
+#           define PNG_IMPEXP __declspec(dllexport)
+#        else
+#           define PNG_IMPEXP __declspec(dllimport)
+#        endif
+#     endif
+#  endif  /* PNG_IMPEXP */
+#else /* !(DLL || non-cygwin WINDOWS) */
+#   if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
+#      ifndef PNGAPI
+#         define PNGAPI _System
+#      endif
+#   else
+#      if 0 /* ... other platforms, with other meanings */
+#      endif
+#   endif
+#endif
+
+#ifndef PNGAPI
+#  define PNGAPI
+#endif
+#ifndef PNG_IMPEXP
+#  define PNG_IMPEXP
+#endif
+
+#ifdef PNG_BUILDSYMS
+#  ifndef PNG_EXPORT
+#    define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
+#  endif
+#  ifdef PNG_USE_GLOBAL_ARRAYS
+#    ifndef PNG_EXPORT_VAR
+#      define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
+#    endif
+#  endif
+#endif
+
+#ifndef PNG_EXPORT
+#  define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
+#endif
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+#  ifndef PNG_EXPORT_VAR
+#    define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
+#  endif
+#endif
+
+/* User may want to use these so they are not in PNG_INTERNAL. Any library
+ * functions that are passed far data must be model independent.
+ */
+
+#ifndef PNG_ABORT
+#  define PNG_ABORT() abort()
+#endif
+
+#ifdef PNG_SETJMP_SUPPORTED
+#  define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
+#else
+#  define png_jmpbuf(png_ptr) \
+   (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
+#endif
+
+#if defined(USE_FAR_KEYWORD)  /* memory model independent fns */
+/* use this to make far-to-near assignments */
+#  define CHECK   1
+#  define NOCHECK 0
+#  define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
+#  define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
+#  define png_strcpy  _fstrcpy
+#  define png_strncpy _fstrncpy   /* Added to v 1.2.6 */
+#  define png_strlen  _fstrlen
+#  define png_memcmp  _fmemcmp    /* SJT: added */
+#  define png_memcpy  _fmemcpy
+#  define png_memset  _fmemset
+#else /* use the usual functions */
+#  define CVT_PTR(ptr)         (ptr)
+#  define CVT_PTR_NOCHECK(ptr) (ptr)
+#  define png_strcpy  strcpy
+#  define png_strncpy strncpy     /* Added to v 1.2.6 */
+#  define png_strlen  strlen
+#  define png_memcmp  memcmp      /* SJT: added */
+#  define png_memcpy  memcpy
+#  define png_memset  memset
+#endif
+/* End of memory model independent support */
+
+/* Just a little check that someone hasn't tried to define something
+ * contradictory.
+ */
+#if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
+#  undef PNG_ZBUF_SIZE
+#  define PNG_ZBUF_SIZE 65536L
+#endif
+
+#ifdef PNG_READ_SUPPORTED
+/* Prior to libpng-1.0.9, this block was in pngasmrd.h */
+#if defined(PNG_INTERNAL)
+
+/* These are the default thresholds before the MMX code kicks in; if either
+ * rowbytes or bitdepth is below the threshold, plain C code is used.  These
+ * can be overridden at runtime via the png_set_mmx_thresholds() call in
+ * libpng 1.2.0 and later.  The values below were chosen by Intel.
+ */
+
+#ifndef PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT
+#  define PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT  128  /*  >=  */
+#endif
+#ifndef PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT
+#  define PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT  9    /*  >=  */   
+#endif
+
+/* Set this in the makefile for VC++ on Pentium, not here. */
+/* Platform must be Pentium.  Makefile must assemble and load pngvcrd.c .
+ * MMX will be detected at run time and used if present.
+ */
+#ifdef PNG_USE_PNGVCRD
+#  define PNG_HAVE_ASSEMBLER_COMBINE_ROW
+#  define PNG_HAVE_ASSEMBLER_READ_INTERLACE
+#  define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW
+#endif
+
+/* Set this in the makefile for gcc/as on Pentium, not here. */
+/* Platform must be Pentium.  Makefile must assemble and load pnggccrd.c .
+ * MMX will be detected at run time and used if present.
+ */
+#ifdef PNG_USE_PNGGCCRD
+#  define PNG_HAVE_ASSEMBLER_COMBINE_ROW
+#  define PNG_HAVE_ASSEMBLER_READ_INTERLACE
+#  define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW
+#endif
+/* - see pnggccrd.c for info about what is currently enabled */
+
+#endif /* PNG_INTERNAL */
+#endif /* PNG_READ_SUPPORTED */
+
+/* Added at libpng-1.2.8 */
+#endif /* PNG_VERSION_INFO_ONLY */
+
+#endif /* PNGCONF_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Entries ./aperios/include/libpng12/CVS/Entries
--- ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng12/CVS/Entries	Wed Aug 10 11:03:22 2005
@@ -0,0 +1,3 @@
+/png.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/pngconf.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Repository ./aperios/include/libpng12/CVS/Repository
--- ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng12/CVS/Repository	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/include/libpng12
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Root ./aperios/include/libpng12/CVS/Root
--- ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng12/CVS/Root	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Tag ./aperios/include/libpng12/CVS/Tag
--- ../Tekkotsu_2.3/aperios/include/libpng12/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng12/CVS/Tag	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng12/png.h ./aperios/include/libpng12/png.h
--- ../Tekkotsu_2.3/aperios/include/libpng12/png.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng12/png.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,3419 @@
+/* png.h - header file for PNG reference library
+ *
+ * libpng version 1.2.8 - December 3, 2004
+ * Copyright (c) 1998-2004 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * Authors and maintainers:
+ *  libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
+ *  libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
+ *  libpng versions 0.97, January 1998, through 1.2.8 - December 3, 2004: Glenn
+ *  See also "Contributing Authors", below.
+ *
+ * Note about libpng version numbers:
+ *
+ *    Due to various miscommunications, unforeseen code incompatibilities
+ *    and occasional factors outside the authors' control, version numbering
+ *    on the library has not always been consistent and straightforward.
+ *    The following table summarizes matters since version 0.89c, which was
+ *    the first widely used release:
+ *
+ *    source                 png.h  png.h  shared-lib
+ *    version                string   int  version
+ *    -------                ------ -----  ----------
+ *    0.89c "1.0 beta 3"     0.89      89  1.0.89
+ *    0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
+ *    0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
+ *    0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
+ *    0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
+ *    0.97c                  0.97      97  2.0.97
+ *    0.98                   0.98      98  2.0.98
+ *    0.99                   0.99      98  2.0.99
+ *    0.99a-m                0.99      99  2.0.99
+ *    1.00                   1.00     100  2.1.0 [100 should be 10000]
+ *    1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
+ *    1.0.1       png.h string is   10001  2.1.0
+ *    1.0.1a-e    identical to the  10002  from here on, the shared library
+ *    1.0.2       source version)   10002  is 2.V where V is the source code
+ *    1.0.2a-b                      10003  version, except as noted.
+ *    1.0.3                         10003
+ *    1.0.3a-d                      10004
+ *    1.0.4                         10004
+ *    1.0.4a-f                      10005
+ *    1.0.5 (+ 2 patches)           10005
+ *    1.0.5a-d                      10006
+ *    1.0.5e-r                      10100 (not source compatible)
+ *    1.0.5s-v                      10006 (not binary compatible)
+ *    1.0.6 (+ 3 patches)           10006 (still binary incompatible)
+ *    1.0.6d-f                      10007 (still binary incompatible)
+ *    1.0.6g                        10007
+ *    1.0.6h                        10007  10.6h (testing xy.z so-numbering)
+ *    1.0.6i                        10007  10.6i
+ *    1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)
+ *    1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)
+ *    1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)
+ *    1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
+ *    1.0.7                    1    10007  (still compatible)
+ *    1.0.8beta1-4             1    10008  2.1.0.8beta1-4
+ *    1.0.8rc1                 1    10008  2.1.0.8rc1
+ *    1.0.8                    1    10008  2.1.0.8
+ *    1.0.9beta1-6             1    10009  2.1.0.9beta1-6
+ *    1.0.9rc1                 1    10009  2.1.0.9rc1
+ *    1.0.9beta7-10            1    10009  2.1.0.9beta7-10
+ *    1.0.9rc2                 1    10009  2.1.0.9rc2
+ *    1.0.9                    1    10009  2.1.0.9
+ *    1.0.10beta1              1    10010  2.1.0.10beta1
+ *    1.0.10rc1                1    10010  2.1.0.10rc1
+ *    1.0.10                   1    10010  2.1.0.10
+ *    1.0.11beta1-3            1    10011  2.1.0.11beta1-3
+ *    1.0.11rc1                1    10011  2.1.0.11rc1
+ *    1.0.11                   1    10011  2.1.0.11
+ *    1.0.12beta1-2            2    10012  2.1.0.12beta1-2
+ *    1.0.12rc1                2    10012  2.1.0.12rc1
+ *    1.0.12                   2    10012  2.1.0.12
+ *    1.1.0a-f                 -    10100  2.1.1.0a-f (branch abandoned)
+ *    1.2.0beta1-2             2    10200  2.1.2.0beta1-2
+ *    1.2.0beta3-5             3    10200  3.1.2.0beta3-5
+ *    1.2.0rc1                 3    10200  3.1.2.0rc1
+ *    1.2.0                    3    10200  3.1.2.0
+ *    1.2.1beta1-4             3    10201  3.1.2.1beta1-4
+ *    1.2.1rc1-2               3    10201  3.1.2.1rc1-2
+ *    1.2.1                    3    10201  3.1.2.1
+ *    1.2.2beta1-6            12    10202  12.so.0.1.2.2beta1-6
+ *    1.0.13beta1             10    10013  10.so.0.1.0.13beta1
+ *    1.0.13rc1               10    10013  10.so.0.1.0.13rc1
+ *    1.2.2rc1                12    10202  12.so.0.1.2.2rc1
+ *    1.0.13                  10    10013  10.so.0.1.0.13
+ *    1.2.2                   12    10202  12.so.0.1.2.2
+ *    1.2.3rc1-6              12    10203  12.so.0.1.2.3rc1-6
+ *    1.2.3                   12    10203  12.so.0.1.2.3
+ *    1.2.4beta1-3            13    10204  12.so.0.1.2.4beta1-3
+ *    1.0.14rc1               13    10014  10.so.0.1.0.14rc1
+ *    1.2.4rc1                13    10204  12.so.0.1.2.4rc1
+ *    1.0.14                  10    10014  10.so.0.1.0.14
+ *    1.2.4                   13    10204  12.so.0.1.2.4
+ *    1.2.5beta1-2            13    10205  12.so.0.1.2.5beta1-2
+ *    1.0.15rc1-3             10    10015  10.so.0.1.0.15rc1-3
+ *    1.2.5rc1-3              13    10205  12.so.0.1.2.5rc1-3
+ *    1.0.15                  10    10015  10.so.0.1.0.15
+ *    1.2.5                   13    10205  12.so.0.1.2.5
+ *    1.2.6beta1-4            13    10206  12.so.0.1.2.6beta1-4
+ *    1.0.16                  10    10016  10.so.0.1.0.16
+ *    1.2.6                   13    10206  12.so.0.1.2.6
+ *    1.2.7beta1-2            13    10207  12.so.0.1.2.7beta1-2
+ *    1.0.17rc1               10    10017  12.so.0.1.0.17rc1
+ *    1.2.7rc1                13    10207  12.so.0.1.2.7rc1
+ *    1.0.17                  10    10017  12.so.0.1.0.17
+ *    1.2.7                   13    10207  12.so.0.1.2.7
+ *    1.2.8beta1-5            13    10208  12.so.0.1.2.8beta1-5
+ *    1.0.18rc1-5             10    10018  12.so.0.1.0.18rc1-5
+ *    1.2.8rc1-5              13    10208  12.so.0.1.2.8rc1-5
+ *    1.0.18                  10    10018  12.so.0.1.0.18
+ *    1.2.8                   13    10208  12.so.0.1.2.8
+ *
+ *    Henceforth the source version will match the shared-library major
+ *    and minor numbers; the shared-library major version number will be
+ *    used for changes in backward compatibility, as it is intended.  The
+ *    PNG_LIBPNG_VER macro, which is not used within libpng but is available
+ *    for applications, is an unsigned integer of the form xyyzz corresponding
+ *    to the source version x.y.z (leading zeros in y and z).  Beta versions
+ *    were given the previous public release number plus a letter, until
+ *    version 1.0.6j; from then on they were given the upcoming public
+ *    release number plus "betaNN" or "rcN".
+ *
+ *    Binary incompatibility exists only when applications make direct access
+ *    to the info_ptr or png_ptr members through png.h, and the compiled
+ *    application is loaded with a different version of the library.
+ *
+ *    DLLNUM will change each time there are forward or backward changes
+ *    in binary compatibility (e.g., when a new feature is added).
+ *
+ * See libpng.txt or libpng.3 for more information.  The PNG specification
+ * is available as a W3C Recommendation and as an ISO Specification,
+ * <http://www.w3.org/TR/2003/REC-PNG-20031110/
+ */
+
+/*
+ * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
+ *
+ * If you modify libpng you may insert additional notices immediately following
+ * this sentence.
+ *
+ * libpng versions 1.2.6, August 15, 2004, through 1.2.8, December 3, 2004, are
+ * Copyright (c) 2004 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.2.5
+ * with the following individual added to the list of Contributing Authors:
+ *
+ *    Cosmin Truta
+ *
+ * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
+ * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.0.6
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Simon-Pierre Cadieux
+ *    Eric S. Raymond
+ *    Gilles Vollant
+ *
+ * and with the following additions to the disclaimer:
+ *
+ *    There is no warranty against interference with your enjoyment of the
+ *    library or against infringement.  There is no warranty that our
+ *    efforts or the library will fulfill any of your particular purposes
+ *    or needs.  This library is provided with all faults, and the entire
+ *    risk of satisfactory quality, performance, accuracy, and effort is with
+ *    the user.
+ *
+ * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+ * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-0.96,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Tom Lane
+ *    Glenn Randers-Pehrson
+ *    Willem van Schaik
+ *
+ * libpng versions 0.89, June 1996, through 0.96, May 1997, are
+ * Copyright (c) 1996, 1997 Andreas Dilger
+ * Distributed according to the same disclaimer and license as libpng-0.88,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    John Bowler
+ *    Kevin Bracey
+ *    Sam Bushell
+ *    Magnus Holmgren
+ *    Greg Roelofs
+ *    Tom Tanner
+ *
+ * libpng versions 0.5, May 1995, through 0.88, January 1996, are
+ * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+ *
+ * For the purposes of this copyright and license, "Contributing Authors"
+ * is defined as the following set of individuals:
+ *
+ *    Andreas Dilger
+ *    Dave Martindale
+ *    Guy Eric Schalnat
+ *    Paul Schmidt
+ *    Tim Wegner
+ *
+ * The PNG Reference Library is supplied "AS IS".  The Contributing Authors
+ * and Group 42, Inc. disclaim all warranties, expressed or implied,
+ * including, without limitation, the warranties of merchantability and of
+ * fitness for any purpose.  The Contributing Authors and Group 42, Inc.
+ * assume no liability for direct, indirect, incidental, special, exemplary,
+ * or consequential damages, which may result from the use of the PNG
+ * Reference Library, even if advised of the possibility of such damage.
+ *
+ * Permission is hereby granted to use, copy, modify, and distribute this
+ * source code, or portions hereof, for any purpose, without fee, subject
+ * to the following restrictions:
+ *
+ * 1. The origin of this source code must not be misrepresented.
+ *
+ * 2. Altered versions must be plainly marked as such and
+ * must not be misrepresented as being the original source.
+ *
+ * 3. This Copyright notice may not be removed or altered from
+ *    any source or altered source distribution.
+ *
+ * The Contributing Authors and Group 42, Inc. specifically permit, without
+ * fee, and encourage the use of this source code as a component to
+ * supporting the PNG file format in commercial products.  If you use this
+ * source code in a product, acknowledgment is not required but would be
+ * appreciated.
+ */
+
+/*
+ * A "png_get_copyright" function is available, for convenient use in "about"
+ * boxes and the like:
+ *
+ * printf("%s",png_get_copyright(NULL));
+ *
+ * Also, the PNG logo (in PNG format, of course) is supplied in the
+ * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
+ */
+
+/*
+ * Libpng is OSI Certified Open Source Software.  OSI Certified is a
+ * certification mark of the Open Source Initiative.
+ */
+
+/*
+ * The contributing authors would like to thank all those who helped
+ * with testing, bug fixes, and patience.  This wouldn't have been
+ * possible without all of you.
+ *
+ * Thanks to Frank J. T. Wojcik for helping with the documentation.
+ */
+
+/*
+ * Y2K compliance in libpng:
+ * =========================
+ *
+ *    December 3, 2004
+ *
+ *    Since the PNG Development group is an ad-hoc body, we can't make
+ *    an official declaration.
+ *
+ *    This is your unofficial assurance that libpng from version 0.71 and
+ *    upward through 1.2.8 are Y2K compliant.  It is my belief that earlier
+ *    versions were also Y2K compliant.
+ *
+ *    Libpng only has three year fields.  One is a 2-byte unsigned integer
+ *    that will hold years up to 65535.  The other two hold the date in text
+ *    format, and will hold years up to 9999.
+ *
+ *    The integer is
+ *        "png_uint_16 year" in png_time_struct.
+ *
+ *    The strings are
+ *        "png_charp time_buffer" in png_struct and
+ *        "near_time_buffer", which is a local character string in png.c.
+ *
+ *    There are seven time-related functions:
+ *        png.c: png_convert_to_rfc_1123() in png.c
+ *          (formerly png_convert_to_rfc_1152() in error)
+ *        png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
+ *        png_convert_from_time_t() in pngwrite.c
+ *        png_get_tIME() in pngget.c
+ *        png_handle_tIME() in pngrutil.c, called in pngread.c
+ *        png_set_tIME() in pngset.c
+ *        png_write_tIME() in pngwutil.c, called in pngwrite.c
+ *
+ *    All handle dates properly in a Y2K environment.  The
+ *    png_convert_from_time_t() function calls gmtime() to convert from system
+ *    clock time, which returns (year - 1900), which we properly convert to
+ *    the full 4-digit year.  There is a possibility that applications using
+ *    libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
+ *    function, or that they are incorrectly passing only a 2-digit year
+ *    instead of "year - 1900" into the png_convert_from_struct_tm() function,
+ *    but this is not under our control.  The libpng documentation has always
+ *    stated that it works with 4-digit years, and the APIs have been
+ *    documented as such.
+ *
+ *    The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
+ *    integer to hold the year, and can hold years as large as 65535.
+ *
+ *    zlib, upon which libpng depends, is also Y2K compliant.  It contains
+ *    no date-related code.
+ *
+ *       Glenn Randers-Pehrson
+ *       libpng maintainer
+ *       PNG Development Group
+ */
+
+#ifndef PNG_H
+#define PNG_H
+
+/* This is not the place to learn how to use libpng.  The file libpng.txt
+ * describes how to use libpng, and the file example.c summarizes it
+ * with some code on which to build.  This file is useful for looking
+ * at the actual function definitions and structure components.
+ */
+
+/* Version information for png.h - this should match the version in png.c */
+#define PNG_LIBPNG_VER_STRING "1.2.8"
+#define PNG_HEADER_VERSION_STRING \
+   " libpng version 1.2.8 - December 3, 2004 (header)\n"
+
+#define PNG_LIBPNG_VER_SONUM   0
+#define PNG_LIBPNG_VER_DLLNUM  13
+
+/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
+#define PNG_LIBPNG_VER_MAJOR   1
+#define PNG_LIBPNG_VER_MINOR   2
+#define PNG_LIBPNG_VER_RELEASE 8
+/* This should match the numeric part of the final component of
+ * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
+
+#define PNG_LIBPNG_VER_BUILD  0
+
+/* Release Status */
+#define PNG_LIBPNG_BUILD_ALPHA    1
+#define PNG_LIBPNG_BUILD_BETA     2
+#define PNG_LIBPNG_BUILD_RC       3
+#define PNG_LIBPNG_BUILD_STABLE   4
+#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
+  
+/* Release-Specific Flags */
+#define PNG_LIBPNG_BUILD_PATCH    8 /* Can be OR'ed with
+                                       PNG_LIBPNG_BUILD_STABLE only */
+#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_SPECIAL */
+#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_PRIVATE */
+
+#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
+
+/* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
+ * We must not include leading zeros.
+ * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
+ * version 1.0.0 was mis-numbered 100 instead of 10000).  From
+ * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release */
+#define PNG_LIBPNG_VER 10208 /* 1.2.8 */
+
+#ifndef PNG_VERSION_INFO_ONLY
+/* include the compression library's header */
+#include "zlib.h"
+#endif
+
+/* include all user configurable info, including optional assembler routines */
+#include "pngconf.h"
+
+/*
+ * Added at libpng-1.2.8 */
+/* Ref MSDN: Private as priority over Special
+ * VS_FF_PRIVATEBUILD File *was not* built using standard release
+ * procedures. If this value is given, the StringFileInfo block must
+ * contain a PrivateBuild string. 
+ *
+ * VS_FF_SPECIALBUILD File *was* built by the original company using
+ * standard release procedures but is a variation of the standard
+ * file of the same version number. If this value is given, the
+ * StringFileInfo block must contain a SpecialBuild string. 
+ */
+
+#if defined(PNG_USER_PRIVATEBUILD)
+#  define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE | \
+          PNG_LIBPNG_BUILD_PRIVATE
+#else
+#  if defined(PNG_LIBPNG_SPECIALBUILD)
+#    define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE | \
+            PNG_LIBPNG_BUILD_SPECIAL
+#  else
+#    define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE
+#  endif
+#endif
+
+#ifndef PNG_VERSION_INFO_ONLY
+
+/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* This file is arranged in several sections.  The first section contains
+ * structure and type definitions.  The second section contains the external
+ * library functions, while the third has the internal library functions,
+ * which applications aren't expected to use directly.
+ */
+
+#ifndef PNG_NO_TYPECAST_NULL
+#define int_p_NULL                (int *)NULL
+#define png_bytep_NULL            (png_bytep)NULL
+#define png_bytepp_NULL           (png_bytepp)NULL
+#define png_doublep_NULL          (png_doublep)NULL
+#define png_error_ptr_NULL        (png_error_ptr)NULL
+#define png_flush_ptr_NULL        (png_flush_ptr)NULL
+#define png_free_ptr_NULL         (png_free_ptr)NULL
+#define png_infopp_NULL           (png_infopp)NULL
+#define png_malloc_ptr_NULL       (png_malloc_ptr)NULL
+#define png_read_status_ptr_NULL  (png_read_status_ptr)NULL
+#define png_rw_ptr_NULL           (png_rw_ptr)NULL
+#define png_structp_NULL          (png_structp)NULL
+#define png_uint_16p_NULL         (png_uint_16p)NULL
+#define png_voidp_NULL            (png_voidp)NULL
+#define png_write_status_ptr_NULL (png_write_status_ptr)NULL
+#else
+#define int_p_NULL                NULL
+#define png_bytep_NULL            NULL
+#define png_bytepp_NULL           NULL
+#define png_doublep_NULL          NULL
+#define png_error_ptr_NULL        NULL
+#define png_flush_ptr_NULL        NULL
+#define png_free_ptr_NULL         NULL
+#define png_infopp_NULL           NULL
+#define png_malloc_ptr_NULL       NULL
+#define png_read_status_ptr_NULL  NULL
+#define png_rw_ptr_NULL           NULL
+#define png_structp_NULL          NULL
+#define png_uint_16p_NULL         NULL
+#define png_voidp_NULL            NULL
+#define png_write_status_ptr_NULL NULL
+#endif
+
+/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
+#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
+/* Version information for C files, stored in png.c.  This had better match
+ * the version above.
+ */
+#ifdef PNG_USE_GLOBAL_ARRAYS
+PNG_EXPORT_VAR (const char) png_libpng_ver[18];
+  /* need room for 99.99.99beta99z */
+#else
+#define png_libpng_ver png_get_header_ver(NULL)
+#endif
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+/* This was removed in version 1.0.5c */
+/* Structures to facilitate easy interlacing.  See png.c for more details */
+PNG_EXPORT_VAR (const int FARDATA) png_pass_start[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_inc[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_ystart[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_yinc[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_mask[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_dsp_mask[7];
+#ifdef PNG_HAVE_ASSEMBLER_COMBINE_ROW
+PNG_EXPORT_VAR (const int FARDATA) png_pass_width[7];
+#endif
+/* This isn't currently used.  If you need it, see png.c for more details.
+PNG_EXPORT_VAR (const int FARDATA) png_pass_height[7];
+*/
+#endif
+
+#endif /* PNG_NO_EXTERN */
+
+/* Three color definitions.  The order of the red, green, and blue, (and the
+ * exact size) is not important, although the size of the fields need to
+ * be png_byte or png_uint_16 (as defined below).
+ */
+typedef struct png_color_struct
+{
+   png_byte red;
+   png_byte green;
+   png_byte blue;
+} png_color;
+typedef png_color FAR * png_colorp;
+typedef png_color FAR * FAR * png_colorpp;
+
+typedef struct png_color_16_struct
+{
+   png_byte index;    /* used for palette files */
+   png_uint_16 red;   /* for use in red green blue files */
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 gray;  /* for use in grayscale files */
+} png_color_16;
+typedef png_color_16 FAR * png_color_16p;
+typedef png_color_16 FAR * FAR * png_color_16pp;
+
+typedef struct png_color_8_struct
+{
+   png_byte red;   /* for use in red green blue files */
+   png_byte green;
+   png_byte blue;
+   png_byte gray;  /* for use in grayscale files */
+   png_byte alpha; /* for alpha channel files */
+} png_color_8;
+typedef png_color_8 FAR * png_color_8p;
+typedef png_color_8 FAR * FAR * png_color_8pp;
+
+/*
+ * The following two structures are used for the in-core representation
+ * of sPLT chunks.
+ */
+typedef struct png_sPLT_entry_struct
+{
+   png_uint_16 red;
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 alpha;
+   png_uint_16 frequency;
+} png_sPLT_entry;
+typedef png_sPLT_entry FAR * png_sPLT_entryp;
+typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
+
+/*  When the depth of the sPLT palette is 8 bits, the color and alpha samples
+ *  occupy the LSB of their respective members, and the MSB of each member
+ *  is zero-filled.  The frequency member always occupies the full 16 bits.
+ */
+
+typedef struct png_sPLT_struct
+{
+   png_charp name;           /* palette name */
+   png_byte depth;           /* depth of palette samples */
+   png_sPLT_entryp entries;  /* palette entries */
+   png_int_32 nentries;      /* number of palette entries */
+} png_sPLT_t;
+typedef png_sPLT_t FAR * png_sPLT_tp;
+typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
+
+#ifdef PNG_TEXT_SUPPORTED
+/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
+ * and whether that contents is compressed or not.  The "key" field
+ * points to a regular zero-terminated C string.  The "text", "lang", and
+ * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
+ * However, the * structure returned by png_get_text() will always contain
+ * regular zero-terminated C strings (possibly empty), never NULL pointers,
+ * so they can be safely used in printf() and other string-handling functions.
+ */
+typedef struct png_text_struct
+{
+   int  compression;       /* compression value:
+                             -1: tEXt, none
+                              0: zTXt, deflate
+                              1: iTXt, none
+                              2: iTXt, deflate  */
+   png_charp key;          /* keyword, 1-79 character description of "text" */
+   png_charp text;         /* comment, may be an empty string (ie "")
+                              or a NULL pointer */
+   png_size_t text_length; /* length of the text string */
+#ifdef PNG_iTXt_SUPPORTED
+   png_size_t itxt_length; /* length of the itxt string */
+   png_charp lang;         /* language code, 0-79 characters
+                              or a NULL pointer */
+   png_charp lang_key;     /* keyword translated UTF-8 string, 0 or more
+                              chars or a NULL pointer */
+#endif
+} png_text;
+typedef png_text FAR * png_textp;
+typedef png_text FAR * FAR * png_textpp;
+#endif
+
+/* Supported compression types for text in PNG files (tEXt, and zTXt).
+ * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
+#define PNG_TEXT_COMPRESSION_NONE_WR -3
+#define PNG_TEXT_COMPRESSION_zTXt_WR -2
+#define PNG_TEXT_COMPRESSION_NONE    -1
+#define PNG_TEXT_COMPRESSION_zTXt     0
+#define PNG_ITXT_COMPRESSION_NONE     1
+#define PNG_ITXT_COMPRESSION_zTXt     2
+#define PNG_TEXT_COMPRESSION_LAST     3  /* Not a valid value */
+
+/* png_time is a way to hold the time in an machine independent way.
+ * Two conversions are provided, both from time_t and struct tm.  There
+ * is no portable way to convert to either of these structures, as far
+ * as I know.  If you know of a portable way, send it to me.  As a side
+ * note - PNG has always been Year 2000 compliant!
+ */
+typedef struct png_time_struct
+{
+   png_uint_16 year; /* full year, as in, 1995 */
+   png_byte month;   /* month of year, 1 - 12 */
+   png_byte day;     /* day of month, 1 - 31 */
+   png_byte hour;    /* hour of day, 0 - 23 */
+   png_byte minute;  /* minute of hour, 0 - 59 */
+   png_byte second;  /* second of minute, 0 - 60 (for leap seconds) */
+} png_time;
+typedef png_time FAR * png_timep;
+typedef png_time FAR * FAR * png_timepp;
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+/* png_unknown_chunk is a structure to hold queued chunks for which there is
+ * no specific support.  The idea is that we can use this to queue
+ * up private chunks for output even though the library doesn't actually
+ * know about their semantics.
+ */
+typedef struct png_unknown_chunk_t
+{
+    png_byte name[5];
+    png_byte *data;
+    png_size_t size;
+
+    /* libpng-using applications should NOT directly modify this byte. */
+    png_byte location; /* mode of operation at read time */
+}
+png_unknown_chunk;
+typedef png_unknown_chunk FAR * png_unknown_chunkp;
+typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
+#endif
+
+/* png_info is a structure that holds the information in a PNG file so
+ * that the application can find out the characteristics of the image.
+ * If you are reading the file, this structure will tell you what is
+ * in the PNG file.  If you are writing the file, fill in the information
+ * you want to put into the PNG file, then call png_write_info().
+ * The names chosen should be very close to the PNG specification, so
+ * consult that document for information about the meaning of each field.
+ *
+ * With libpng < 0.95, it was only possible to directly set and read the
+ * the values in the png_info_struct, which meant that the contents and
+ * order of the values had to remain fixed.  With libpng 0.95 and later,
+ * however, there are now functions that abstract the contents of
+ * png_info_struct from the application, so this makes it easier to use
+ * libpng with dynamic libraries, and even makes it possible to use
+ * libraries that don't have all of the libpng ancillary chunk-handing
+ * functionality.
+ *
+ * In any case, the order of the parameters in png_info_struct should NOT
+ * be changed for as long as possible to keep compatibility with applications
+ * that use the old direct-access method with png_info_struct.
+ *
+ * The following members may have allocated storage attached that should be
+ * cleaned up before the structure is discarded: palette, trans, text,
+ * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
+ * splt_palettes, scal_unit, row_pointers, and unknowns.   By default, these
+ * are automatically freed when the info structure is deallocated, if they were
+ * allocated internally by libpng.  This behavior can be changed by means
+ * of the png_data_freer() function.
+ *
+ * More allocation details: all the chunk-reading functions that
+ * change these members go through the corresponding png_set_*
+ * functions.  A function to clear these members is available: see
+ * png_free_data().  The png_set_* functions do not depend on being
+ * able to point info structure members to any of the storage they are
+ * passed (they make their own copies), EXCEPT that the png_set_text
+ * functions use the same storage passed to them in the text_ptr or
+ * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
+ * functions do not make their own copies.
+ */
+typedef struct png_info_struct
+{
+   /* the following are necessary for every PNG file */
+   png_uint_32 width;       /* width of image in pixels (from IHDR) */
+   png_uint_32 height;      /* height of image in pixels (from IHDR) */
+   png_uint_32 valid;       /* valid chunk data (see PNG_INFO_ below) */
+   png_uint_32 rowbytes;    /* bytes needed to hold an untransformed row */
+   png_colorp palette;      /* array of color values (valid & PNG_INFO_PLTE) */
+   png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
+   png_uint_16 num_trans;   /* number of transparent palette color (tRNS) */
+   png_byte bit_depth;      /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
+   png_byte color_type;     /* see PNG_COLOR_TYPE_ below (from IHDR) */
+   /* The following three should have been named *_method not *_type */
+   png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
+   png_byte filter_type;    /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
+   png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+
+   /* The following is informational only on read, and not used on writes. */
+   png_byte channels;       /* number of data channels per pixel (1, 2, 3, 4) */
+   png_byte pixel_depth;    /* number of bits per pixel */
+   png_byte spare_byte;     /* to align the data, and for future use */
+   png_byte signature[8];   /* magic bytes read by libpng from start of file */
+
+   /* The rest of the data is optional.  If you are reading, check the
+    * valid field to see if the information in these are valid.  If you
+    * are writing, set the valid field to those chunks you want written,
+    * and initialize the appropriate fields below.
+    */
+
+#if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
+   /* The gAMA chunk describes the gamma characteristics of the system
+    * on which the image was created, normally in the range [1.0, 2.5].
+    * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
+    */
+   float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+    /* GR-P, 0.96a */
+    /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
+   png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)
+   /* The tEXt, and zTXt chunks contain human-readable textual data in
+    * uncompressed, compressed, and optionally compressed forms, respectively.
+    * The data in "text" is an array of pointers to uncompressed,
+    * null-terminated C strings. Each chunk has a keyword that describes the
+    * textual data contained in that chunk.  Keywords are not required to be
+    * unique, and the text string may be empty.  Any number of text chunks may
+    * be in an image.
+    */
+   int num_text; /* number of comments read/to write */
+   int max_text; /* current size of text array */
+   png_textp text; /* array of comments read/to write */
+#endif /* PNG_TEXT_SUPPORTED */
+
+#if defined(PNG_tIME_SUPPORTED)
+   /* The tIME chunk holds the last time the displayed image data was
+    * modified.  See the png_time struct for the contents of this struct.
+    */
+   png_time mod_time;
+#endif
+
+#if defined(PNG_sBIT_SUPPORTED)
+   /* The sBIT chunk specifies the number of significant high-order bits
+    * in the pixel data.  Values are in the range [1, bit_depth], and are
+    * only specified for the channels in the pixel data.  The contents of
+    * the low-order bits is not specified.  Data is valid if
+    * (valid & PNG_INFO_sBIT) is non-zero.
+    */
+   png_color_8 sig_bit; /* significant bits in color channels */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
+defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The tRNS chunk supplies transparency data for paletted images and
+    * other image types that don't need a full alpha channel.  There are
+    * "num_trans" transparency values for a paletted image, stored in the
+    * same order as the palette colors, starting from index 0.  Values
+    * for the data are in the range [0, 255], ranging from fully transparent
+    * to fully opaque, respectively.  For non-paletted images, there is a
+    * single color specified that should be treated as fully transparent.
+    * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
+    */
+   png_bytep trans; /* transparent values for paletted image */
+   png_color_16 trans_values; /* transparent color for non-palette image */
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The bKGD chunk gives the suggested image background color if the
+    * display program does not have its own background color and the image
+    * is needs to composited onto a background before display.  The colors
+    * in "background" are normally in the same color space/depth as the
+    * pixel data.  Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
+    */
+   png_color_16 background;
+#endif
+
+#if defined(PNG_oFFs_SUPPORTED)
+   /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
+    * and downwards from the top-left corner of the display, page, or other
+    * application-specific co-ordinate space.  See the PNG_OFFSET_ defines
+    * below for the unit types.  Valid if (valid & PNG_INFO_oFFs) non-zero.
+    */
+   png_int_32 x_offset; /* x offset on page */
+   png_int_32 y_offset; /* y offset on page */
+   png_byte offset_unit_type; /* offset units type */
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+   /* The pHYs chunk gives the physical pixel density of the image for
+    * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
+    * defines below).  Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
+    */
+   png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
+   png_uint_32 y_pixels_per_unit; /* vertical pixel density */
+   png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+   /* The hIST chunk contains the relative frequency or importance of the
+    * various palette entries, so that a viewer can intelligently select a
+    * reduced-color palette, if required.  Data is an array of "num_palette"
+    * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
+    * is non-zero.
+    */
+   png_uint_16p hist;
+#endif
+
+#ifdef PNG_cHRM_SUPPORTED
+   /* The cHRM chunk describes the CIE color characteristics of the monitor
+    * on which the PNG was created.  This data allows the viewer to do gamut
+    * mapping of the input image to ensure that the viewer sees the same
+    * colors in the image as the creator.  Values are in the range
+    * [0.0, 0.8].  Data valid if (valid & PNG_INFO_cHRM) non-zero.
+    */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   float x_white;
+   float y_white;
+   float x_red;
+   float y_red;
+   float x_green;
+   float y_green;
+   float x_blue;
+   float y_blue;
+#endif
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+   /* The pCAL chunk describes a transformation between the stored pixel
+    * values and original physical data values used to create the image.
+    * The integer range [0, 2^bit_depth - 1] maps to the floating-point
+    * range given by [pcal_X0, pcal_X1], and are further transformed by a
+    * (possibly non-linear) transformation function given by "pcal_type"
+    * and "pcal_params" into "pcal_units".  Please see the PNG_EQUATION_
+    * defines below, and the PNG-Group's PNG extensions document for a
+    * complete description of the transformations and how they should be
+    * implemented, and for a description of the ASCII parameter strings.
+    * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
+    */
+   png_charp pcal_purpose;  /* pCAL chunk description string */
+   png_int_32 pcal_X0;      /* minimum value */
+   png_int_32 pcal_X1;      /* maximum value */
+   png_charp pcal_units;    /* Latin-1 string giving physical units */
+   png_charpp pcal_params;  /* ASCII strings containing parameter values */
+   png_byte pcal_type;      /* equation type (see PNG_EQUATION_ below) */
+   png_byte pcal_nparams;   /* number of parameters given in pcal_params */
+#endif
+
+/* New members added in libpng-1.0.6 */
+#ifdef PNG_FREE_ME_SUPPORTED
+   png_uint_32 free_me;     /* flags items libpng is responsible for freeing */
+#endif
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+   /* storage for unknown chunks that the library doesn't recognize. */
+   png_unknown_chunkp unknown_chunks;
+   png_size_t unknown_chunks_num;
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+   /* iCCP chunk data. */
+   png_charp iccp_name;     /* profile name */
+   png_charp iccp_profile;  /* International Color Consortium profile data */
+                            /* Note to maintainer: should be png_bytep */
+   png_uint_32 iccp_proflen;  /* ICC profile data length */
+   png_byte iccp_compression; /* Always zero */
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+   /* data on sPLT chunks (there may be more than one). */
+   png_sPLT_tp splt_palettes;
+   png_uint_32 splt_palettes_num;
+#endif
+
+#if defined(PNG_sCAL_SUPPORTED)
+   /* The sCAL chunk describes the actual physical dimensions of the
+    * subject matter of the graphic.  The chunk contains a unit specification
+    * a byte value, and two ASCII strings representing floating-point
+    * values.  The values are width and height corresponsing to one pixel
+    * in the image.  This external representation is converted to double
+    * here.  Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
+    */
+   png_byte scal_unit;         /* unit of physical scale */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   double scal_pixel_width;    /* width of one pixel */
+   double scal_pixel_height;   /* height of one pixel */
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+   png_charp scal_s_width;     /* string containing height */
+   png_charp scal_s_height;    /* string containing width */
+#endif
+#endif
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+   /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
+   /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
+   png_bytepp row_pointers;        /* the image bits */
+#endif
+
+#if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
+   png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
+   png_fixed_point int_x_white;
+   png_fixed_point int_y_white;
+   png_fixed_point int_x_red;
+   png_fixed_point int_y_red;
+   png_fixed_point int_x_green;
+   png_fixed_point int_y_green;
+   png_fixed_point int_x_blue;
+   png_fixed_point int_y_blue;
+#endif
+
+} png_info;
+
+typedef png_info FAR * png_infop;
+typedef png_info FAR * FAR * png_infopp;
+
+/* Maximum positive integer used in PNG is (2^31)-1 */
+#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
+#define PNG_UINT_32_MAX ((png_uint_32)(-1))
+#define PNG_SIZE_MAX ((png_size_t)(-1))
+/* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
+#define PNG_MAX_UINT PNG_UINT_31_MAX
+
+/* These describe the color_type field in png_info. */
+/* color type masks */
+#define PNG_COLOR_MASK_PALETTE    1
+#define PNG_COLOR_MASK_COLOR      2
+#define PNG_COLOR_MASK_ALPHA      4
+
+/* color types.  Note that not all combinations are legal */
+#define PNG_COLOR_TYPE_GRAY 0
+#define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
+#define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
+#define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
+#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
+/* aliases */
+#define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
+#define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
+
+/* This is for compression type. PNG 1.0-1.2 only define the single type. */
+#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
+#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
+
+/* This is for filter type. PNG 1.0-1.2 only define the single type. */
+#define PNG_FILTER_TYPE_BASE      0 /* Single row per-byte filtering */
+#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
+#define PNG_FILTER_TYPE_DEFAULT   PNG_FILTER_TYPE_BASE
+
+/* These are for the interlacing type.  These values should NOT be changed. */
+#define PNG_INTERLACE_NONE        0 /* Non-interlaced image */
+#define PNG_INTERLACE_ADAM7       1 /* Adam7 interlacing */
+#define PNG_INTERLACE_LAST        2 /* Not a valid value */
+
+/* These are for the oFFs chunk.  These values should NOT be changed. */
+#define PNG_OFFSET_PIXEL          0 /* Offset in pixels */
+#define PNG_OFFSET_MICROMETER     1 /* Offset in micrometers (1/10^6 meter) */
+#define PNG_OFFSET_LAST           2 /* Not a valid value */
+
+/* These are for the pCAL chunk.  These values should NOT be changed. */
+#define PNG_EQUATION_LINEAR       0 /* Linear transformation */
+#define PNG_EQUATION_BASE_E       1 /* Exponential base e transform */
+#define PNG_EQUATION_ARBITRARY    2 /* Arbitrary base exponential transform */
+#define PNG_EQUATION_HYPERBOLIC   3 /* Hyperbolic sine transformation */
+#define PNG_EQUATION_LAST         4 /* Not a valid value */
+
+/* These are for the sCAL chunk.  These values should NOT be changed. */
+#define PNG_SCALE_UNKNOWN         0 /* unknown unit (image scale) */
+#define PNG_SCALE_METER           1 /* meters per pixel */
+#define PNG_SCALE_RADIAN          2 /* radians per pixel */
+#define PNG_SCALE_LAST            3 /* Not a valid value */
+
+/* These are for the pHYs chunk.  These values should NOT be changed. */
+#define PNG_RESOLUTION_UNKNOWN    0 /* pixels/unknown unit (aspect ratio) */
+#define PNG_RESOLUTION_METER      1 /* pixels/meter */
+#define PNG_RESOLUTION_LAST       2 /* Not a valid value */
+
+/* These are for the sRGB chunk.  These values should NOT be changed. */
+#define PNG_sRGB_INTENT_PERCEPTUAL 0
+#define PNG_sRGB_INTENT_RELATIVE   1
+#define PNG_sRGB_INTENT_SATURATION 2
+#define PNG_sRGB_INTENT_ABSOLUTE   3
+#define PNG_sRGB_INTENT_LAST       4 /* Not a valid value */
+
+/* This is for text chunks */
+#define PNG_KEYWORD_MAX_LENGTH     79
+
+/* Maximum number of entries in PLTE/sPLT/tRNS arrays */
+#define PNG_MAX_PALETTE_LENGTH    256
+
+/* These determine if an ancillary chunk's data has been successfully read
+ * from the PNG header, or if the application has filled in the corresponding
+ * data in the info_struct to be written into the output file.  The values
+ * of the PNG_INFO_<chunk> defines should NOT be changed.
+ */
+#define PNG_INFO_gAMA 0x0001
+#define PNG_INFO_sBIT 0x0002
+#define PNG_INFO_cHRM 0x0004
+#define PNG_INFO_PLTE 0x0008
+#define PNG_INFO_tRNS 0x0010
+#define PNG_INFO_bKGD 0x0020
+#define PNG_INFO_hIST 0x0040
+#define PNG_INFO_pHYs 0x0080
+#define PNG_INFO_oFFs 0x0100
+#define PNG_INFO_tIME 0x0200
+#define PNG_INFO_pCAL 0x0400
+#define PNG_INFO_sRGB 0x0800   /* GR-P, 0.96a */
+#define PNG_INFO_iCCP 0x1000   /* ESR, 1.0.6 */
+#define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
+#define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
+#define PNG_INFO_IDAT 0x8000L  /* ESR, 1.0.6 */
+
+/* This is used for the transformation routines, as some of them
+ * change these values for the row.  It also should enable using
+ * the routines for other purposes.
+ */
+typedef struct png_row_info_struct
+{
+   png_uint_32 width; /* width of row */
+   png_uint_32 rowbytes; /* number of bytes in row */
+   png_byte color_type; /* color type of row */
+   png_byte bit_depth; /* bit depth of row */
+   png_byte channels; /* number of channels (1, 2, 3, or 4) */
+   png_byte pixel_depth; /* bits per pixel (depth * channels) */
+} png_row_info;
+
+typedef png_row_info FAR * png_row_infop;
+typedef png_row_info FAR * FAR * png_row_infopp;
+
+/* These are the function types for the I/O functions and for the functions
+ * that allow the user to override the default I/O functions with his or her
+ * own.  The png_error_ptr type should match that of user-supplied warning
+ * and error functions, while the png_rw_ptr type should match that of the
+ * user read/write data functions.
+ */
+typedef struct png_struct_def png_struct;
+typedef png_struct FAR * png_structp;
+
+typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
+typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
+typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
+typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
+   int));
+typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
+   int));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
+typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
+typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
+   png_uint_32, int));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
+    png_row_infop, png_bytep));
+#endif
+
+#if defined(PNG_USER_CHUNKS_SUPPORTED)
+typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
+#endif
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
+#endif
+
+/* Transform masks for the high-level interface */
+#define PNG_TRANSFORM_IDENTITY       0x0000    /* read and write */
+#define PNG_TRANSFORM_STRIP_16       0x0001    /* read only */
+#define PNG_TRANSFORM_STRIP_ALPHA    0x0002    /* read only */
+#define PNG_TRANSFORM_PACKING        0x0004    /* read and write */
+#define PNG_TRANSFORM_PACKSWAP       0x0008    /* read and write */
+#define PNG_TRANSFORM_EXPAND         0x0010    /* read only */
+#define PNG_TRANSFORM_INVERT_MONO    0x0020    /* read and write */
+#define PNG_TRANSFORM_SHIFT          0x0040    /* read and write */
+#define PNG_TRANSFORM_BGR            0x0080    /* read and write */
+#define PNG_TRANSFORM_SWAP_ALPHA     0x0100    /* read and write */
+#define PNG_TRANSFORM_SWAP_ENDIAN    0x0200    /* read and write */
+#define PNG_TRANSFORM_INVERT_ALPHA   0x0400    /* read and write */
+#define PNG_TRANSFORM_STRIP_FILLER   0x0800    /* WRITE only */
+
+/* Flags for MNG supported features */
+#define PNG_FLAG_MNG_EMPTY_PLTE     0x01
+#define PNG_FLAG_MNG_FILTER_64      0x04
+#define PNG_ALL_MNG_FEATURES        0x05
+
+typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
+typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
+
+/* The structure that holds the information to read and write PNG files.
+ * The only people who need to care about what is inside of this are the
+ * people who will be modifying the library for their own special needs.
+ * It should NOT be accessed directly by an application, except to store
+ * the jmp_buf.
+ */
+
+struct png_struct_def
+{
+#ifdef PNG_SETJMP_SUPPORTED
+   jmp_buf jmpbuf;            /* used in png_error */
+#endif
+   png_error_ptr error_fn;    /* function for printing errors and aborting */
+   png_error_ptr warning_fn;  /* function for printing warnings */
+   png_voidp error_ptr;       /* user supplied struct for error functions */
+   png_rw_ptr write_data_fn;  /* function for writing output data */
+   png_rw_ptr read_data_fn;   /* function for reading input data */
+   png_voidp io_ptr;          /* ptr to application struct for I/O functions */
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
+   png_user_transform_ptr read_user_transform_fn; /* user read transform */
+#endif
+
+#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+   png_user_transform_ptr write_user_transform_fn; /* user write transform */
+#endif
+
+/* These were added in libpng-1.0.2 */
+#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+   png_voidp user_transform_ptr; /* user supplied struct for user transform */
+   png_byte user_transform_depth;    /* bit depth of user transformed pixels */
+   png_byte user_transform_channels; /* channels in user transformed pixels */
+#endif
+#endif
+
+   png_uint_32 mode;          /* tells us where we are in the PNG file */
+   png_uint_32 flags;         /* flags indicating various things to libpng */
+   png_uint_32 transformations; /* which transformations to perform */
+
+   z_stream zstream;          /* pointer to decompression structure (below) */
+   png_bytep zbuf;            /* buffer for zlib */
+   png_size_t zbuf_size;      /* size of zbuf */
+   int zlib_level;            /* holds zlib compression level */
+   int zlib_method;           /* holds zlib compression method */
+   int zlib_window_bits;      /* holds zlib compression window bits */
+   int zlib_mem_level;        /* holds zlib compression memory level */
+   int zlib_strategy;         /* holds zlib compression strategy */
+
+   png_uint_32 width;         /* width of image in pixels */
+   png_uint_32 height;        /* height of image in pixels */
+   png_uint_32 num_rows;      /* number of rows in current pass */
+   png_uint_32 usr_width;     /* width of row at start of write */
+   png_uint_32 rowbytes;      /* size of row in bytes */
+   png_uint_32 irowbytes;     /* size of current interlaced row in bytes */
+   png_uint_32 iwidth;        /* width of current interlaced row in pixels */
+   png_uint_32 row_number;    /* current row in interlace pass */
+   png_bytep prev_row;        /* buffer to save previous (unfiltered) row */
+   png_bytep row_buf;         /* buffer to save current (unfiltered) row */
+   png_bytep sub_row;         /* buffer to save "sub" row when filtering */
+   png_bytep up_row;          /* buffer to save "up" row when filtering */
+   png_bytep avg_row;         /* buffer to save "avg" row when filtering */
+   png_bytep paeth_row;       /* buffer to save "Paeth" row when filtering */
+   png_row_info row_info;     /* used for transformation routines */
+
+   png_uint_32 idat_size;     /* current IDAT size for read */
+   png_uint_32 crc;           /* current chunk CRC value */
+   png_colorp palette;        /* palette from the input file */
+   png_uint_16 num_palette;   /* number of color entries in palette */
+   png_uint_16 num_trans;     /* number of transparency values */
+   png_byte chunk_name[5];    /* null-terminated name of current chunk */
+   png_byte compression;      /* file compression type (always 0) */
+   png_byte filter;           /* file filter type (always 0) */
+   png_byte interlaced;       /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+   png_byte pass;             /* current interlace pass (0 - 6) */
+   png_byte do_filter;        /* row filter flags (see PNG_FILTER_ below ) */
+   png_byte color_type;       /* color type of file */
+   png_byte bit_depth;        /* bit depth of file */
+   png_byte usr_bit_depth;    /* bit depth of users row */
+   png_byte pixel_depth;      /* number of bits per pixel */
+   png_byte channels;         /* number of channels in file */
+   png_byte usr_channels;     /* channels at start of write */
+   png_byte sig_bytes;        /* magic bytes read/written from start of file */
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+#ifdef PNG_LEGACY_SUPPORTED
+   png_byte filler;           /* filler byte for pixel expansion */
+#else
+   png_uint_16 filler;           /* filler bytes for pixel expansion */
+#endif
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED)
+   png_byte background_gamma_type;
+#  ifdef PNG_FLOATING_POINT_SUPPORTED
+   float background_gamma;
+#  endif
+   png_color_16 background;   /* background color in screen gamma space */
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+   png_color_16 background_1; /* background normalized to gamma 1.0 */
+#endif
+#endif /* PNG_bKGD_SUPPORTED */
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+   png_flush_ptr output_flush_fn;/* Function for flushing output */
+   png_uint_32 flush_dist;    /* how many rows apart to flush, 0 - no flush */
+   png_uint_32 flush_rows;    /* number of rows written since last flush */
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   int gamma_shift;      /* number of "insignificant" bits 16-bit gamma */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   float gamma;          /* file gamma value */
+   float screen_gamma;   /* screen gamma value (display_exponent) */
+#endif
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_bytep gamma_table;     /* gamma table for 8-bit depth files */
+   png_bytep gamma_from_1;    /* converts from 1.0 to screen */
+   png_bytep gamma_to_1;      /* converts from file to 1.0 */
+   png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
+   png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
+   png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
+   png_color_8 sig_bit;       /* significant bits in each available channel */
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+   png_color_8 shift;         /* shift for significant bit tranformation */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
+ || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_bytep trans;           /* transparency values for paletted files */
+   png_color_16 trans_values; /* transparency values for non-paletted files */
+#endif
+
+   png_read_status_ptr read_row_fn;   /* called after each row is decoded */
+   png_write_status_ptr write_row_fn; /* called after each row is encoded */
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+   png_progressive_info_ptr info_fn; /* called after header data fully read */
+   png_progressive_row_ptr row_fn;   /* called after each prog. row is decoded */
+   png_progressive_end_ptr end_fn;   /* called after image is complete */
+   png_bytep save_buffer_ptr;        /* current location in save_buffer */
+   png_bytep save_buffer;            /* buffer for previously read data */
+   png_bytep current_buffer_ptr;     /* current location in current_buffer */
+   png_bytep current_buffer;         /* buffer for recently used data */
+   png_uint_32 push_length;          /* size of current input chunk */
+   png_uint_32 skip_length;          /* bytes to skip in input data */
+   png_size_t save_buffer_size;      /* amount of data now in save_buffer */
+   png_size_t save_buffer_max;       /* total size of save_buffer */
+   png_size_t buffer_size;           /* total amount of available input data */
+   png_size_t current_buffer_size;   /* amount of data now in current_buffer */
+   int process_mode;                 /* what push library is currently doing */
+   int cur_palette;                  /* current push library palette index */
+
+#  if defined(PNG_TEXT_SUPPORTED)
+     png_size_t current_text_size;   /* current size of text input data */
+     png_size_t current_text_left;   /* how much text left to read in input */
+     png_charp current_text;         /* current text chunk buffer */
+     png_charp current_text_ptr;     /* current location in current_text */
+#  endif /* PNG_PROGRESSIVE_READ_SUPPORTED && PNG_TEXT_SUPPORTED */
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
+/* for the Borland special 64K segment handler */
+   png_bytepp offset_table_ptr;
+   png_bytep offset_table;
+   png_uint_16 offset_table_number;
+   png_uint_16 offset_table_count;
+   png_uint_16 offset_table_count_free;
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+   png_bytep palette_lookup;         /* lookup table for dithering */
+   png_bytep dither_index;           /* index translation for palette files */
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
+   png_uint_16p hist;                /* histogram */
+#endif
+
+#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
+   png_byte heuristic_method;        /* heuristic for row filter selection */
+   png_byte num_prev_filters;        /* number of weights for previous rows */
+   png_bytep prev_filters;           /* filter type(s) of previous row(s) */
+   png_uint_16p filter_weights;      /* weight(s) for previous line(s) */
+   png_uint_16p inv_filter_weights;  /* 1/weight(s) for previous line(s) */
+   png_uint_16p filter_costs;        /* relative filter calculation cost */
+   png_uint_16p inv_filter_costs;    /* 1/relative filter calculation cost */
+#endif
+
+#if defined(PNG_TIME_RFC1123_SUPPORTED)
+   png_charp time_buffer;            /* String to hold RFC 1123 time text */
+#endif
+
+/* New members added in libpng-1.0.6 */
+
+#ifdef PNG_FREE_ME_SUPPORTED
+   png_uint_32 free_me;       /* flags items libpng is responsible for freeing */
+#endif
+
+#if defined(PNG_USER_CHUNKS_SUPPORTED)
+   png_voidp user_chunk_ptr;
+   png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
+#endif
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+   int num_chunk_list;
+   png_bytep chunk_list;
+#endif
+
+/* New members added in libpng-1.0.3 */
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+   png_byte rgb_to_gray_status;
+   /* These were changed from png_byte in libpng-1.0.6 */
+   png_uint_16 rgb_to_gray_red_coeff;
+   png_uint_16 rgb_to_gray_green_coeff;
+   png_uint_16 rgb_to_gray_blue_coeff;
+#endif
+
+/* New member added in libpng-1.0.4 (renamed in 1.0.9) */
+#if defined(PNG_MNG_FEATURES_SUPPORTED) || \
+    defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
+    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
+/* changed from png_byte to png_uint_32 at version 1.2.0 */
+#ifdef PNG_1_0_X
+   png_byte mng_features_permitted;
+#else
+   png_uint_32 mng_features_permitted;
+#endif /* PNG_1_0_X */
+#endif
+
+/* New member added in libpng-1.0.7 */
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_fixed_point int_gamma;
+#endif
+
+/* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
+#if defined(PNG_MNG_FEATURES_SUPPORTED)
+   png_byte filter_type;
+#endif
+
+#if defined(PNG_1_0_X) || (defined(PNG_DEBUG) && defined(PNG_USE_PNGGCCRD))
+/* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
+   png_uint_32 row_buf_size;
+#endif
+
+/* New members added in libpng-1.2.0 */
+#if !defined(PNG_1_0_X) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+   png_byte     mmx_bitdepth_threshold;
+   png_uint_32  mmx_rowbytes_threshold;
+   png_uint_32  asm_flags;
+#endif
+
+/* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
+#ifdef PNG_USER_MEM_SUPPORTED
+   png_voidp mem_ptr;                /* user supplied struct for mem functions */
+   png_malloc_ptr malloc_fn;         /* function for allocating memory */
+   png_free_ptr free_fn;             /* function for freeing memory */
+#endif
+
+/* New member added in libpng-1.0.13 and 1.2.0 */
+   png_bytep big_row_buf;         /* buffer to save current (unfiltered) row */
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+/* The following three members were added at version 1.0.14 and 1.2.4 */
+   png_bytep dither_sort;            /* working sort array */
+   png_bytep index_to_palette;       /* where the original index currently is */
+                                     /* in the palette */
+   png_bytep palette_to_index;       /* which original index points to this */
+                                     /* palette color */
+#endif
+
+/* New members added in libpng-1.0.16 and 1.2.6 */
+   png_byte compression_type;
+
+#ifdef PNG_SET_USER_LIMITS_SUPPORTED
+   png_uint_32 user_width_max;
+   png_uint_32 user_height_max;
+#endif
+
+};
+
+
+/* This triggers a compiler error in png.c, if png.c and png.h
+ * do not agree upon the version number.
+ */
+typedef png_structp version_1_2_8;
+
+typedef png_struct FAR * FAR * png_structpp;
+
+/* Here are the function definitions most commonly used.  This is not
+ * the place to find out how to use libpng.  See libpng.txt for the
+ * full explanation, see example.c for the summary.  This just provides
+ * a simple one line description of the use of each function.
+ */
+
+/* Returns the version number of the library */
+extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
+
+/* Tell lib we have already handled the first <num_bytes> magic bytes.
+ * Handling more than 8 bytes from the beginning of the file is an error.
+ */
+extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
+   int num_bytes));
+
+/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
+ * PNG file.  Returns zero if the supplied bytes match the 8-byte PNG
+ * signature, and non-zero otherwise.  Having num_to_check == 0 or
+ * start > 7 will always fail (ie return non-zero).
+ */
+extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
+   png_size_t num_to_check));
+
+/* Simple signature checking function.  This is the same as calling
+ * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
+ */
+extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
+
+/* Allocate and initialize png_ptr struct for reading, and any other memory. */
+extern PNG_EXPORT(png_structp,png_create_read_struct)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn));
+
+/* Allocate and initialize png_ptr struct for writing, and any other memory */
+extern PNG_EXPORT(png_structp,png_create_write_struct)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn));
+
+#ifdef PNG_WRITE_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
+   PNGARG((png_structp png_ptr));
+#endif
+
+#ifdef PNG_WRITE_SUPPORTED
+extern PNG_EXPORT(void,png_set_compression_buffer_size)
+   PNGARG((png_structp png_ptr, png_uint_32 size));
+#endif
+
+/* Reset the compression stream */
+extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
+
+/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
+#ifdef PNG_USER_MEM_SUPPORTED
+extern PNG_EXPORT(png_structp,png_create_read_struct_2)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
+   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+extern PNG_EXPORT(png_structp,png_create_write_struct_2)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
+   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+#endif
+
+/* Write a PNG chunk - size, type, (optional) data, CRC. */
+extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
+   png_bytep chunk_name, png_bytep data, png_size_t length));
+
+/* Write the start of a PNG chunk - length and chunk name. */
+extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
+   png_bytep chunk_name, png_uint_32 length));
+
+/* Write the data of a PNG chunk started with png_write_chunk_start(). */
+extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+/* Finish a chunk started with png_write_chunk_start() (includes CRC). */
+extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
+
+/* Allocate and initialize the info structure */
+extern PNG_EXPORT(png_infop,png_create_info_struct)
+   PNGARG((png_structp png_ptr));
+
+/* Initialize the info structure (old interface - DEPRECATED) */
+extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
+#undef png_info_init
+#define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
+    png_sizeof(png_info));
+extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
+    png_size_t png_info_struct_size));
+
+/* Writes all the PNG information before the image. */
+extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the information before the actual image data. */
+extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+#if defined(PNG_TIME_RFC1123_SUPPORTED)
+extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
+   PNGARG((png_structp png_ptr, png_timep ptime));
+#endif
+
+#if !defined(_WIN32_WCE)
+/* "time.h" functions are not supported on WindowsCE */
+#if defined(PNG_WRITE_tIME_SUPPORTED)
+/* convert from a struct tm to png_time */
+extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
+   struct tm FAR * ttime));
+
+/* convert from time_t to png_time.  Uses gmtime() */
+extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
+   time_t ttime));
+#endif /* PNG_WRITE_tIME_SUPPORTED */
+#endif /* _WIN32_WCE */
+
+#if defined(PNG_READ_EXPAND_SUPPORTED)
+/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
+extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+/* Use blue, green, red order for pixels. */
+extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
+/* Expand the grayscale to 24-bit RGB if necessary. */
+extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+/* Reduce RGB to grayscale. */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
+   int error_action, double red, double green ));
+#endif
+extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
+   int error_action, png_fixed_point red, png_fixed_point green ));
+extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
+   png_ptr));
+#endif
+
+extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
+   png_colorp palette));
+
+#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
+extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
+   png_uint_32 filler, int flags));
+/* The values of the PNG_FILLER_ defines should NOT be changed */
+#define PNG_FILLER_BEFORE 0
+#define PNG_FILLER_AFTER 1
+/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
+#if !defined(PNG_1_0_X)
+extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
+   png_uint_32 filler, int flags));
+#endif
+#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
+
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+/* Swap bytes in 16-bit depth files. */
+extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
+/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
+extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+/* Swap packing order of pixels in bytes. */
+extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+/* Converts files to legal bit depths. */
+extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
+   png_color_8p true_bits));
+#endif
+
+#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
+    defined(PNG_WRITE_INTERLACING_SUPPORTED)
+/* Have the code handle the interlacing.  Returns the number of passes. */
+extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+/* Invert monochrome files */
+extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_BACKGROUND_SUPPORTED)
+/* Handle alpha and tRNS by replacing with a background color. */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
+   png_color_16p background_color, int background_gamma_code,
+   int need_expand, double background_gamma));
+#endif
+#define PNG_BACKGROUND_GAMMA_UNKNOWN 0
+#define PNG_BACKGROUND_GAMMA_SCREEN  1
+#define PNG_BACKGROUND_GAMMA_FILE    2
+#define PNG_BACKGROUND_GAMMA_UNIQUE  3
+#endif
+
+#if defined(PNG_READ_16_TO_8_SUPPORTED)
+/* strip the second byte of information from a 16-bit depth file. */
+extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+/* Turn on dithering, and reduce the palette to the number of colors available. */
+extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
+   png_colorp palette, int num_palette, int maximum_colors,
+   png_uint_16p histogram, int full_dither));
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+/* Handle gamma correction. Screen_gamma=(display_exponent) */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
+   double screen_gamma, double default_file_gamma));
+#endif
+#endif
+
+#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
+    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
+/* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
+/* Deprecated and will be removed.  Use png_permit_mng_features() instead. */
+extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
+   int empty_plte_permitted));
+#endif
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+/* Set how many lines between output flushes - 0 for no flushing */
+extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
+/* Flush the current PNG output buffer */
+extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
+#endif
+
+/* optional update palette with requested transformations */
+extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
+
+/* optional call to update the users info structure */
+extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read one or more rows of image data. */
+extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
+   png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
+#endif
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read a row of data. */
+extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
+   png_bytep row,
+   png_bytep display_row));
+#endif
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the whole image into memory at once. */
+extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
+   png_bytepp image));
+#endif
+
+/* write a row of image data */
+extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
+   png_bytep row));
+
+/* write a few rows of image data */
+extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
+   png_bytepp row, png_uint_32 num_rows));
+
+/* write the image data */
+extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
+   png_bytepp image));
+
+/* writes the end of the PNG file. */
+extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the end of the PNG file. */
+extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+/* free any memory associated with the png_info_struct */
+extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
+   png_infopp info_ptr_ptr));
+
+/* free any memory associated with the png_struct and the png_info_structs */
+extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
+   png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
+
+/* free all memory used by the read (old method - NOT DLL EXPORTED) */
+extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_infop end_info_ptr));
+
+/* free any memory associated with the png_struct and the png_info_structs */
+extern PNG_EXPORT(void,png_destroy_write_struct)
+   PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
+
+/* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
+extern void png_write_destroy PNGARG((png_structp png_ptr));
+
+/* set the libpng method of handling chunk CRC errors */
+extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
+   int crit_action, int ancil_action));
+
+/* Values for png_set_crc_action() to say how to handle CRC errors in
+ * ancillary and critical chunks, and whether to use the data contained
+ * therein.  Note that it is impossible to "discard" data in a critical
+ * chunk.  For versions prior to 0.90, the action was always error/quit,
+ * whereas in version 0.90 and later, the action for CRC errors in ancillary
+ * chunks is warn/discard.  These values should NOT be changed.
+ *
+ *      value                       action:critical     action:ancillary
+ */
+#define PNG_CRC_DEFAULT       0  /* error/quit          warn/discard data */
+#define PNG_CRC_ERROR_QUIT    1  /* error/quit          error/quit        */
+#define PNG_CRC_WARN_DISCARD  2  /* (INVALID)           warn/discard data */
+#define PNG_CRC_WARN_USE      3  /* warn/use data       warn/use data     */
+#define PNG_CRC_QUIET_USE     4  /* quiet/use data      quiet/use data    */
+#define PNG_CRC_NO_CHANGE     5  /* use current value   use current value */
+
+/* These functions give the user control over the scan-line filtering in
+ * libpng and the compression methods used by zlib.  These functions are
+ * mainly useful for testing, as the defaults should work with most users.
+ * Those users who are tight on memory or want faster performance at the
+ * expense of compression can modify them.  See the compression library
+ * header file (zlib.h) for an explination of the compression functions.
+ */
+
+/* set the filtering method(s) used by libpng.  Currently, the only valid
+ * value for "method" is 0.
+ */
+extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
+   int filters));
+
+/* Flags for png_set_filter() to say which filters to use.  The flags
+ * are chosen so that they don't conflict with real filter types
+ * below, in case they are supplied instead of the #defined constants.
+ * These values should NOT be changed.
+ */
+#define PNG_NO_FILTERS     0x00
+#define PNG_FILTER_NONE    0x08
+#define PNG_FILTER_SUB     0x10
+#define PNG_FILTER_UP      0x20
+#define PNG_FILTER_AVG     0x40
+#define PNG_FILTER_PAETH   0x80
+#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
+                         PNG_FILTER_AVG | PNG_FILTER_PAETH)
+
+/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
+ * These defines should NOT be changed.
+ */
+#define PNG_FILTER_VALUE_NONE  0
+#define PNG_FILTER_VALUE_SUB   1
+#define PNG_FILTER_VALUE_UP    2
+#define PNG_FILTER_VALUE_AVG   3
+#define PNG_FILTER_VALUE_PAETH 4
+#define PNG_FILTER_VALUE_LAST  5
+
+#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
+/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
+ * defines, either the default (minimum-sum-of-absolute-differences), or
+ * the experimental method (weighted-minimum-sum-of-absolute-differences).
+ *
+ * Weights are factors >= 1.0, indicating how important it is to keep the
+ * filter type consistent between rows.  Larger numbers mean the current
+ * filter is that many times as likely to be the same as the "num_weights"
+ * previous filters.  This is cumulative for each previous row with a weight.
+ * There needs to be "num_weights" values in "filter_weights", or it can be
+ * NULL if the weights aren't being specified.  Weights have no influence on
+ * the selection of the first row filter.  Well chosen weights can (in theory)
+ * improve the compression for a given image.
+ *
+ * Costs are factors >= 1.0 indicating the relative decoding costs of a
+ * filter type.  Higher costs indicate more decoding expense, and are
+ * therefore less likely to be selected over a filter with lower computational
+ * costs.  There needs to be a value in "filter_costs" for each valid filter
+ * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
+ * setting the costs.  Costs try to improve the speed of decompression without
+ * unduly increasing the compressed image size.
+ *
+ * A negative weight or cost indicates the default value is to be used, and
+ * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
+ * The default values for both weights and costs are currently 1.0, but may
+ * change if good general weighting/cost heuristics can be found.  If both
+ * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
+ * to the UNWEIGHTED method, but with added encoding time/computation.
+ */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
+   int heuristic_method, int num_weights, png_doublep filter_weights,
+   png_doublep filter_costs));
+#endif
+#endif /*  PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
+
+/* Heuristic used for row filter selection.  These defines should NOT be
+ * changed.
+ */
+#define PNG_FILTER_HEURISTIC_DEFAULT    0  /* Currently "UNWEIGHTED" */
+#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1  /* Used by libpng < 0.95 */
+#define PNG_FILTER_HEURISTIC_WEIGHTED   2  /* Experimental feature */
+#define PNG_FILTER_HEURISTIC_LAST       3  /* Not a valid value */
+
+/* Set the library compression level.  Currently, valid values range from
+ * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
+ * (0 - no compression, 9 - "maximal" compression).  Note that tests have
+ * shown that zlib compression levels 3-6 usually perform as well as level 9
+ * for PNG images, and do considerably fewer caclulations.  In the future,
+ * these values may not correspond directly to the zlib compression levels.
+ */
+extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
+   int level));
+
+extern PNG_EXPORT(void,png_set_compression_mem_level)
+   PNGARG((png_structp png_ptr, int mem_level));
+
+extern PNG_EXPORT(void,png_set_compression_strategy)
+   PNGARG((png_structp png_ptr, int strategy));
+
+extern PNG_EXPORT(void,png_set_compression_window_bits)
+   PNGARG((png_structp png_ptr, int window_bits));
+
+extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
+   int method));
+
+/* These next functions are called for input/output, memory, and error
+ * handling.  They are in the file pngrio.c, pngwio.c, and pngerror.c,
+ * and call standard C I/O routines such as fread(), fwrite(), and
+ * fprintf().  These functions can be made to use other I/O routines
+ * at run time for those applications that need to handle I/O in a
+ * different manner by calling png_set_???_fn().  See libpng.txt for
+ * more information.
+ */
+
+#if !defined(PNG_NO_STDIO)
+/* Initialize the input/output for the PNG file to the default functions. */
+extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
+#endif
+
+/* Replace the (error and abort), and warning functions with user
+ * supplied functions.  If no messages are to be printed you must still
+ * write and use replacement functions. The replacement error_fn should
+ * still do a longjmp to the last setjmp location if you are using this
+ * method of error handling.  If error_fn or warning_fn is NULL, the
+ * default function will be used.
+ */
+
+extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
+   png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
+
+/* Return the user pointer associated with the error functions */
+extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
+
+/* Replace the default data output functions with a user supplied one(s).
+ * If buffered output is not used, then output_flush_fn can be set to NULL.
+ * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
+ * output_flush_fn will be ignored (and thus can be NULL).
+ */
+extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
+   png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
+
+/* Replace the default data input function with a user supplied one. */
+extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
+   png_voidp io_ptr, png_rw_ptr read_data_fn));
+
+/* Return the user pointer associated with the I/O functions */
+extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
+
+extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
+   png_read_status_ptr read_row_fn));
+
+extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
+   png_write_status_ptr write_row_fn));
+
+#ifdef PNG_USER_MEM_SUPPORTED
+/* Replace the default memory allocation functions with user supplied one(s). */
+extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
+   png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+/* Return the user pointer associated with the memory functions */
+extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
+   png_ptr, png_user_transform_ptr read_user_transform_fn));
+#endif
+
+#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
+   png_ptr, png_user_transform_ptr write_user_transform_fn));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
+   png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
+   int user_transform_channels));
+/* Return the user pointer associated with the user transform functions */
+extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
+   PNGARG((png_structp png_ptr));
+#endif
+
+#ifdef PNG_USER_CHUNKS_SUPPORTED
+extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
+   png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
+extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
+   png_ptr));
+#endif
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+/* Sets the function callbacks for the push reader, and a pointer to a
+ * user-defined structure available to the callback functions.
+ */
+extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
+   png_voidp progressive_ptr,
+   png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
+   png_progressive_end_ptr end_fn));
+
+/* returns the user pointer associated with the push read functions */
+extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
+   PNGARG((png_structp png_ptr));
+
+/* function to be called when data becomes available */
+extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
+
+/* function that combines rows.  Not very much different than the
+ * png_combine_row() call.  Is this even used?????
+ */
+extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
+   png_bytep old_row, png_bytep new_row));
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+
+#if defined(PNG_1_0_X)
+#  define png_malloc_warn png_malloc
+#else
+/* Added at libpng version 1.2.4 */
+extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+#endif
+
+/* frees a pointer allocated by png_malloc() */
+extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
+
+#if defined(PNG_1_0_X)
+/* Function to allocate memory for zlib. */
+extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
+   uInt size));
+
+/* Function to free memory for zlib */
+extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
+#endif
+
+/* Free data that was allocated internally */
+extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 free_me, int num));
+#ifdef PNG_FREE_ME_SUPPORTED
+/* Reassign responsibility for freeing existing data, whether allocated
+ * by libpng or by the application */
+extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int freer, png_uint_32 mask));
+#endif
+/* assignments for png_data_freer */
+#define PNG_DESTROY_WILL_FREE_DATA 1
+#define PNG_SET_WILL_FREE_DATA 1
+#define PNG_USER_WILL_FREE_DATA 2
+/* Flags for png_ptr->free_me and info_ptr->free_me */
+#define PNG_FREE_HIST 0x0008
+#define PNG_FREE_ICCP 0x0010
+#define PNG_FREE_SPLT 0x0020
+#define PNG_FREE_ROWS 0x0040
+#define PNG_FREE_PCAL 0x0080
+#define PNG_FREE_SCAL 0x0100
+#define PNG_FREE_UNKN 0x0200
+#define PNG_FREE_LIST 0x0400
+#define PNG_FREE_PLTE 0x1000
+#define PNG_FREE_TRNS 0x2000
+#define PNG_FREE_TEXT 0x4000
+#define PNG_FREE_ALL  0x7fff
+#define PNG_FREE_MUL  0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
+
+#ifdef PNG_USER_MEM_SUPPORTED
+extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
+   png_voidp ptr));
+#endif
+
+extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
+   png_voidp s1, png_voidp s2, png_uint_32 size));
+
+extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
+   png_voidp s1, int value, png_uint_32 size));
+
+#if defined(USE_FAR_KEYWORD)  /* memory model conversion function */
+extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
+   int check));
+#endif /* USE_FAR_KEYWORD */
+
+/* Fatal error in PNG image of libpng - can't continue */
+extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
+   png_const_charp error_message));
+
+/* The same, but the chunk name is prepended to the error string. */
+extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
+   png_const_charp error_message));
+
+/* Non-fatal error in libpng.  Can continue, but may have a problem. */
+extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
+   png_const_charp warning_message));
+
+/* Non-fatal error in libpng, chunk name is prepended to message. */
+extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
+   png_const_charp warning_message));
+
+/* The png_set_<chunk> functions are for storing values in the png_info_struct.
+ * Similarly, the png_get_<chunk> calls are used to read values from the
+ * png_info_struct, either storing the parameters in the passed variables, or
+ * setting pointers into the png_info_struct where the data is stored.  The
+ * png_get_<chunk> functions return a non-zero value if the data was available
+ * in info_ptr, or return zero and do not change any of the parameters if the
+ * data was not available.
+ *
+ * These functions should be used instead of directly accessing png_info
+ * to avoid problems with future changes in the size and internal layout of
+ * png_info_struct.
+ */
+/* Returns "flag" if chunk data is valid in info_ptr. */
+extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
+png_infop info_ptr, png_uint_32 flag));
+
+/* Returns number of bytes needed to hold a transformed row. */
+extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+/* Returns row_pointers, which is an array of pointers to scanlines that was
+returned from png_read_png(). */
+extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+/* Set row_pointers, which is an array of pointers to scanlines for use
+by png_write_png(). */
+extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytepp row_pointers));
+#endif
+
+/* Returns number of color channels in image. */
+extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#ifdef PNG_EASY_ACCESS_SUPPORTED
+/* Returns image width in pixels. */
+extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image height in pixels. */
+extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image bit_depth. */
+extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image color_type. */
+extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image filter_type. */
+extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image interlace_type. */
+extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image compression_type. */
+extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image resolution in pixels per meter, from pHYs chunk data. */
+extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns pixel aspect ratio, computed from pHYs chunk data.  */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+#endif
+
+/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
+extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+#endif /* PNG_EASY_ACCESS_SUPPORTED */
+
+/* Returns pointer to signature string read from PNG header */
+extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#if defined(PNG_bKGD_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_16p *background));
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED)
+extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_16p background));
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double *white_x, double *white_y, double *red_x,
+   double *red_y, double *green_x, double *green_y, double *blue_x,
+   double *blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
+   *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
+   png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
+   *int_blue_x, png_fixed_point *int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double white_x, double white_y, double red_x,
+   double red_y, double green_x, double green_y, double blue_x, double blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
+   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+   png_fixed_point int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double *file_gamma));
+#endif
+extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point *int_file_gamma));
+#endif
+
+#if defined(PNG_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double file_gamma));
+#endif
+extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point int_file_gamma));
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_16p *hist));
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_16p hist));
+#endif
+
+extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
+   int *bit_depth, int *color_type, int *interlace_method,
+   int *compression_method, int *filter_method));
+
+extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
+   int color_type, int interlace_method, int compression_method,
+   int filter_method));
+
+#if defined(PNG_oFFs_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
+   int *unit_type));
+#endif
+
+#if defined(PNG_oFFs_SUPPORTED)
+extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
+   int unit_type));
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
+   int *type, int *nparams, png_charp *units, png_charpp *params));
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
+   int type, int nparams, png_charp units, png_charpp params));
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
+#endif
+
+extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_colorp *palette, int *num_palette));
+
+extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_colorp palette, int num_palette));
+
+#if defined(PNG_sBIT_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_8p *sig_bit));
+#endif
+
+#if defined(PNG_sBIT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_8p sig_bit));
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *intent));
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int intent));
+extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int intent));
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charpp name, int *compression_type,
+   png_charpp profile, png_uint_32 *proflen));
+   /* Note to maintainer: profile should be png_bytepp */
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp name, int compression_type,
+   png_charp profile, png_uint_32 proflen));
+   /* Note to maintainer: profile should be png_bytep */
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_sPLT_tpp entries));
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_sPLT_tp entries, int nentries));
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)
+/* png_get_text also returns the number of text chunks in *num_text */
+extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp *text_ptr, int *num_text));
+#endif
+
+/*
+ *  Note while png_set_text() will accept a structure whose text,
+ *  language, and  translated keywords are NULL pointers, the structure
+ *  returned by png_get_text will always contain regular
+ *  zero-terminated C strings.  They might be empty strings but
+ *  they will never be NULL pointers.
+ */
+
+#if defined(PNG_TEXT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp text_ptr, int num_text));
+#endif
+
+#if defined(PNG_tIME_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_timep *mod_time));
+#endif
+
+#if defined(PNG_tIME_SUPPORTED)
+extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_timep mod_time));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep *trans, int *num_trans,
+   png_color_16p *trans_values));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep trans, int num_trans,
+   png_color_16p trans_values));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+#endif
+
+#if defined(PNG_sCAL_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *unit, double *width, double *height));
+#else
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
+#endif
+#endif
+#endif /* PNG_sCAL_SUPPORTED */
+
+#if defined(PNG_sCAL_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int unit, double width, double height));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
+#endif
+#endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+/* provide a list of chunks and how they are to be handled, if the built-in
+   handling or default unknown chunk handling is not desired.  Any chunks not
+   listed will be handled in the default manner.  The IHDR and IEND chunks
+   must not be listed.
+      keep = 0: follow default behavour
+           = 1: do not keep
+           = 2: keep only if safe-to-copy
+           = 3: keep even if unsafe-to-copy
+*/
+extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
+   png_ptr, int keep, png_bytep chunk_list, int num_chunks));
+extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
+extern PNG_EXPORT(void, png_set_unknown_chunk_location)
+   PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
+extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
+   png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
+#endif
+#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
+   chunk_name));
+#endif
+
+/* Png_free_data() will turn off the "valid" flag for anything it frees.
+   If you need to turn it off for a chunk that your application has freed,
+   you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
+extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int mask));
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+/* The "params" pointer is currently not used and is for future expansion. */
+extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
+                        png_infop info_ptr,
+                        int transforms,
+                        png_voidp params));
+extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
+                        png_infop info_ptr,
+                        int transforms,
+                        png_voidp params));
+#endif
+
+/* Define PNG_DEBUG at compile time for debugging information.  Higher
+ * numbers for PNG_DEBUG mean more debugging information.  This has
+ * only been added since version 0.95 so it is not implemented throughout
+ * libpng yet, but more support will be added as needed.
+ */
+#ifdef PNG_DEBUG
+#if (PNG_DEBUG > 0)
+#if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
+#include <crtdbg.h>
+#if (PNG_DEBUG > 1)
+#define png_debug(l,m)  _RPT0(_CRT_WARN,m)
+#define png_debug1(l,m,p1)  _RPT1(_CRT_WARN,m,p1)
+#define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
+#endif
+#else /* PNG_DEBUG_FILE || !_MSC_VER */
+#ifndef PNG_DEBUG_FILE
+#define PNG_DEBUG_FILE stderr
+#endif /* PNG_DEBUG_FILE */
+#if (PNG_DEBUG > 1)
+#define png_debug(l,m) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
+}
+#define png_debug1(l,m,p1) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
+}
+#define png_debug2(l,m,p1,p2) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
+}
+#endif /* (PNG_DEBUG > 1) */
+#endif /* _MSC_VER */
+#endif /* (PNG_DEBUG > 0) */
+#endif /* PNG_DEBUG */
+#ifndef png_debug
+#define png_debug(l, m)
+#endif
+#ifndef png_debug1
+#define png_debug1(l, m, p1)
+#endif
+#ifndef png_debug2
+#define png_debug2(l, m, p1, p2)
+#endif
+
+extern PNG_EXPORT(png_bytep,png_sig_bytes) PNGARG((void));
+
+extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
+   png_ptr, png_uint_32 mng_features_permitted));
+#endif
+
+/* For use in png_set_keep_unknown, added to version 1.2.6 */
+#define PNG_HANDLE_CHUNK_AS_DEFAULT   0
+#define PNG_HANDLE_CHUNK_NEVER        1
+#define PNG_HANDLE_CHUNK_IF_SAFE      2
+#define PNG_HANDLE_CHUNK_ALWAYS       3
+
+/* Added to version 1.2.0 */
+#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+#define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED  0x01  /* not user-settable */
+#define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU    0x02  /* not user-settable */
+#define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  0x04
+#define PNG_ASM_FLAG_MMX_READ_INTERLACE    0x08
+#define PNG_ASM_FLAG_MMX_READ_FILTER_SUB   0x10
+#define PNG_ASM_FLAG_MMX_READ_FILTER_UP    0x20
+#define PNG_ASM_FLAG_MMX_READ_FILTER_AVG   0x40
+#define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
+#define PNG_ASM_FLAGS_INITIALIZED          0x80000000  /* not user-settable */
+
+#define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  \
+                           | PNG_ASM_FLAG_MMX_READ_INTERLACE    \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_SUB   \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_UP    \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_AVG   \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
+#define PNG_MMX_WRITE_FLAGS ( 0 )
+
+#define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
+                      | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU   \
+                      | PNG_MMX_READ_FLAGS                \
+                      | PNG_MMX_WRITE_FLAGS )
+
+#define PNG_SELECT_READ   1
+#define PNG_SELECT_WRITE  2
+
+#if !defined(PNG_1_0_X)
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
+   PNGARG((int flag_select, int *compilerID));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
+   PNGARG((int flag_select));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
+   PNGARG((png_structp png_ptr));
+
+/* pngget.c */
+extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
+   PNGARG((png_structp png_ptr));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
+   PNGARG((png_structp png_ptr));
+
+/* pngset.c */
+extern PNG_EXPORT(void,png_set_asm_flags)
+   PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
+
+/* pngset.c */
+extern PNG_EXPORT(void,png_set_mmx_thresholds)
+   PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
+   png_uint_32 mmx_rowbytes_threshold));
+
+#endif /* PNG_1_0_X */
+#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
+
+#if !defined(PNG_1_0_X)
+/* png.c, pnggccrd.c, or pngvcrd.c */
+extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
+
+/* Strip the prepended error numbers ("#nnn ") from error and warning
+ * messages before passing them to the error or warning handler. */
+#ifdef PNG_ERROR_NUMBERS_SUPPORTED
+extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
+   png_ptr, png_uint_32 strip_mode));
+#endif
+
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.2.6 */
+#ifdef PNG_SET_USER_LIMITS_SUPPORTED
+extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
+   png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
+extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
+   png_ptr));
+extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
+   png_ptr));
+#endif
+
+/* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
+
+#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
+/* With these routines we avoid an integer divide, which will be slower on
+ * most machines.  However, it does take more operations than the corresponding
+ * divide method, so it may be slower on a few RISC systems.  There are two
+ * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
+ *
+ * Note that the rounding factors are NOT supposed to be the same!  128 and
+ * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
+ * standard method.
+ *
+ * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
+ */
+
+ /* fg and bg should be in `gamma 1.0' space; alpha is the opacity          */
+
+#  define png_composite(composite, fg, alpha, bg)                            \
+     { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
+                        +        (png_uint_16)(bg)*(png_uint_16)(255 -       \
+                        (png_uint_16)(alpha)) + (png_uint_16)128);           \
+       (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
+
+#  define png_composite_16(composite, fg, alpha, bg)                         \
+     { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
+                        + (png_uint_32)(bg)*(png_uint_32)(65535L -           \
+                        (png_uint_32)(alpha)) + (png_uint_32)32768L);        \
+       (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
+
+#else  /* standard method using integer division */
+
+#  define png_composite(composite, fg, alpha, bg)                            \
+     (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) +    \
+       (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) +       \
+       (png_uint_16)127) / 255)
+
+#  define png_composite_16(composite, fg, alpha, bg)                         \
+     (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
+       (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) +      \
+       (png_uint_32)32767) / (png_uint_32)65535L)
+
+#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
+
+/* These next functions are used internally in the code.  They generally
+ * shouldn't be used unless you are writing code to add or replace some
+ * functionality in libpng.  More information about most functions can
+ * be found in the files where the functions are located.
+ */
+
+#if defined(PNG_INTERNAL)
+
+/* Various modes of operation.  Note that after an init, mode is set to
+ * zero automatically when the structure is created.
+ */
+#define PNG_HAVE_IHDR               0x01
+#define PNG_HAVE_PLTE               0x02
+#define PNG_HAVE_IDAT               0x04
+#define PNG_AFTER_IDAT              0x08
+#define PNG_HAVE_IEND               0x10
+#define PNG_HAVE_gAMA               0x20
+#define PNG_HAVE_cHRM               0x40
+#define PNG_HAVE_sRGB               0x80
+#define PNG_HAVE_CHUNK_HEADER      0x100
+#define PNG_WROTE_tIME             0x200
+#define PNG_WROTE_INFO_BEFORE_PLTE 0x400
+#define PNG_BACKGROUND_IS_GRAY     0x800
+#define PNG_HAVE_PNG_SIGNATURE    0x1000
+
+/* flags for the transformations the PNG library does on the image data */
+#define PNG_BGR                0x0001
+#define PNG_INTERLACE          0x0002
+#define PNG_PACK               0x0004
+#define PNG_SHIFT              0x0008
+#define PNG_SWAP_BYTES         0x0010
+#define PNG_INVERT_MONO        0x0020
+#define PNG_DITHER             0x0040
+#define PNG_BACKGROUND         0x0080
+#define PNG_BACKGROUND_EXPAND  0x0100
+                          /*   0x0200 unused */
+#define PNG_16_TO_8            0x0400
+#define PNG_RGBA               0x0800
+#define PNG_EXPAND             0x1000
+#define PNG_GAMMA              0x2000
+#define PNG_GRAY_TO_RGB        0x4000
+#define PNG_FILLER             0x8000L
+#define PNG_PACKSWAP          0x10000L
+#define PNG_SWAP_ALPHA        0x20000L
+#define PNG_STRIP_ALPHA       0x40000L
+#define PNG_INVERT_ALPHA      0x80000L
+#define PNG_USER_TRANSFORM   0x100000L
+#define PNG_RGB_TO_GRAY_ERR  0x200000L
+#define PNG_RGB_TO_GRAY_WARN 0x400000L
+#define PNG_RGB_TO_GRAY      0x600000L  /* two bits, RGB_TO_GRAY_ERR|WARN */
+                       /*    0x800000L     Unused */
+#define PNG_ADD_ALPHA       0x1000000L  /* Added to libpng-1.2.7 */
+                       /*   0x2000000L  unused */
+                       /*   0x4000000L  unused */
+                       /*   0x8000000L  unused */
+                       /*  0x10000000L  unused */
+                       /*  0x20000000L  unused */
+                       /*  0x40000000L  unused */
+
+/* flags for png_create_struct */
+#define PNG_STRUCT_PNG   0x0001
+#define PNG_STRUCT_INFO  0x0002
+
+/* Scaling factor for filter heuristic weighting calculations */
+#define PNG_WEIGHT_SHIFT 8
+#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
+#define PNG_COST_SHIFT 3
+#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
+
+/* flags for the png_ptr->flags rather than declaring a byte for each one */
+#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY     0x0001
+#define PNG_FLAG_ZLIB_CUSTOM_LEVEL        0x0002
+#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL    0x0004
+#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS  0x0008
+#define PNG_FLAG_ZLIB_CUSTOM_METHOD       0x0010
+#define PNG_FLAG_ZLIB_FINISHED            0x0020
+#define PNG_FLAG_ROW_INIT                 0x0040
+#define PNG_FLAG_FILLER_AFTER             0x0080
+#define PNG_FLAG_CRC_ANCILLARY_USE        0x0100
+#define PNG_FLAG_CRC_ANCILLARY_NOWARN     0x0200
+#define PNG_FLAG_CRC_CRITICAL_USE         0x0400
+#define PNG_FLAG_CRC_CRITICAL_IGNORE      0x0800
+#define PNG_FLAG_FREE_PLTE                0x1000
+#define PNG_FLAG_FREE_TRNS                0x2000
+#define PNG_FLAG_FREE_HIST                0x4000
+#define PNG_FLAG_KEEP_UNKNOWN_CHUNKS      0x8000L
+#define PNG_FLAG_KEEP_UNSAFE_CHUNKS       0x10000L
+#define PNG_FLAG_LIBRARY_MISMATCH         0x20000L
+#define PNG_FLAG_STRIP_ERROR_NUMBERS      0x40000L
+#define PNG_FLAG_STRIP_ERROR_TEXT         0x80000L
+#define PNG_FLAG_MALLOC_NULL_MEM_OK       0x100000L
+#define PNG_FLAG_ADD_ALPHA                0x200000L  /* Added to libpng-1.2.8 */
+#define PNG_FLAG_STRIP_ALPHA              0x400000L  /* Added to libpng-1.2.8 */
+                                  /*      0x800000L  unused */
+                                  /*     0x1000000L  unused */
+                                  /*     0x2000000L  unused */
+                                  /*     0x4000000L  unused */
+                                  /*     0x8000000L  unused */
+                                  /*    0x10000000L  unused */
+                                  /*    0x20000000L  unused */
+                                  /*    0x40000000L  unused */
+
+#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
+                                     PNG_FLAG_CRC_ANCILLARY_NOWARN)
+
+#define PNG_FLAG_CRC_CRITICAL_MASK  (PNG_FLAG_CRC_CRITICAL_USE | \
+                                     PNG_FLAG_CRC_CRITICAL_IGNORE)
+
+#define PNG_FLAG_CRC_MASK           (PNG_FLAG_CRC_ANCILLARY_MASK | \
+                                     PNG_FLAG_CRC_CRITICAL_MASK)
+
+/* save typing and make code easier to understand */
+
+#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
+   abs((int)((c1).green) - (int)((c2).green)) + \
+   abs((int)((c1).blue) - (int)((c2).blue)))
+
+/* Added to libpng-1.2.6 JB */
+#define PNG_ROWBYTES(pixel_bits, width) \
+    ((pixel_bits) >= 8 ? \
+    ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
+    (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
+
+/* PNG_OUT_OF_RANGE returns true if value is outside the range
+   ideal-delta..ideal+delta.  Each argument is evaluated twice.
+   "ideal" and "delta" should be constants, normally simple
+   integers, "value" a variable. Added to libpng-1.2.6 JB */
+#define PNG_OUT_OF_RANGE(value, ideal, delta) \
+        ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
+
+/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
+#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
+/* place to hold the signature string for a PNG file. */
+#ifdef PNG_USE_GLOBAL_ARRAYS
+   PNG_EXPORT_VAR (const png_byte FARDATA) png_sig[8];
+#else
+#define png_sig png_sig_bytes(NULL)
+#endif
+#endif /* PNG_NO_EXTERN */
+
+/* Constant strings for known chunk types.  If you need to add a chunk,
+ * define the name here, and add an invocation of the macro in png.c and
+ * wherever it's needed.
+ */
+#define PNG_IHDR const png_byte png_IHDR[5] = { 73,  72,  68,  82, '\0'}
+#define PNG_IDAT const png_byte png_IDAT[5] = { 73,  68,  65,  84, '\0'}
+#define PNG_IEND const png_byte png_IEND[5] = { 73,  69,  78,  68, '\0'}
+#define PNG_PLTE const png_byte png_PLTE[5] = { 80,  76,  84,  69, '\0'}
+#define PNG_bKGD const png_byte png_bKGD[5] = { 98,  75,  71,  68, '\0'}
+#define PNG_cHRM const png_byte png_cHRM[5] = { 99,  72,  82,  77, '\0'}
+#define PNG_gAMA const png_byte png_gAMA[5] = {103,  65,  77,  65, '\0'}
+#define PNG_hIST const png_byte png_hIST[5] = {104,  73,  83,  84, '\0'}
+#define PNG_iCCP const png_byte png_iCCP[5] = {105,  67,  67,  80, '\0'}
+#define PNG_iTXt const png_byte png_iTXt[5] = {105,  84,  88, 116, '\0'}
+#define PNG_oFFs const png_byte png_oFFs[5] = {111,  70,  70, 115, '\0'}
+#define PNG_pCAL const png_byte png_pCAL[5] = {112,  67,  65,  76, '\0'}
+#define PNG_sCAL const png_byte png_sCAL[5] = {115,  67,  65,  76, '\0'}
+#define PNG_pHYs const png_byte png_pHYs[5] = {112,  72,  89, 115, '\0'}
+#define PNG_sBIT const png_byte png_sBIT[5] = {115,  66,  73,  84, '\0'}
+#define PNG_sPLT const png_byte png_sPLT[5] = {115,  80,  76,  84, '\0'}
+#define PNG_sRGB const png_byte png_sRGB[5] = {115,  82,  71,  66, '\0'}
+#define PNG_tEXt const png_byte png_tEXt[5] = {116,  69,  88, 116, '\0'}
+#define PNG_tIME const png_byte png_tIME[5] = {116,  73,  77,  69, '\0'}
+#define PNG_tRNS const png_byte png_tRNS[5] = {116,  82,  78,  83, '\0'}
+#define PNG_zTXt const png_byte png_zTXt[5] = {122,  84,  88, 116, '\0'}
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IHDR[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IDAT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IEND[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_PLTE[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_bKGD[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_cHRM[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_gAMA[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_hIST[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_iCCP[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_iTXt[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_oFFs[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_pCAL[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sCAL[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_pHYs[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sBIT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sPLT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sRGB[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tEXt[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tIME[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tRNS[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_zTXt[5];
+#endif /* PNG_USE_GLOBAL_ARRAYS */
+
+
+/* Inline macros to do direct reads of bytes from the input buffer.  These
+ * require that you are using an architecture that uses PNG byte ordering
+ * (MSB first) and supports unaligned data storage.  I think that PowerPC
+ * in big-endian mode and 680x0 are the only ones that will support this.
+ * The x86 line of processors definitely do not.  The png_get_int_32()
+ * routine also assumes we are using two's complement format for negative
+ * values, which is almost certainly true.
+ */
+#if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
+#  if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED)
+#    define png_get_int_32(buf) ( *((png_int_32p) (buf)))
+#  endif
+#  define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
+#  define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
+#else
+#  if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED)
+PNG_EXTERN png_int_32 png_get_int_32 PNGARG((png_bytep buf));
+#  endif
+PNG_EXTERN png_uint_32 png_get_uint_32 PNGARG((png_bytep buf));
+PNG_EXTERN png_uint_16 png_get_uint_16 PNGARG((png_bytep buf));
+#endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
+PNG_EXTERN png_uint_32 png_get_uint_31 PNGARG((png_structp png_ptr,
+  png_bytep buf));
+
+/* Initialize png_ptr struct for reading, and allocate any other memory.
+ * (old interface - DEPRECATED - use png_create_read_struct instead).
+ */
+extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
+#undef png_read_init
+#define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
+    PNG_LIBPNG_VER_STRING,  png_sizeof(png_struct));
+extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size));
+extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
+    png_info_size));
+
+/* Initialize png_ptr struct for writing, and allocate any other memory.
+ * (old interface - DEPRECATED - use png_create_write_struct instead).
+ */
+extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
+#undef png_write_init
+#define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
+    PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
+extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size));
+extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
+    png_info_size));
+
+/* Allocate memory for an internal libpng struct */
+PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
+
+/* Free memory from internal libpng struct */
+PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
+
+PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
+  malloc_fn, png_voidp mem_ptr));
+PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
+   png_free_ptr free_fn, png_voidp mem_ptr));
+
+/* Free any memory that info_ptr points to and reset struct. */
+PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_1_0_X
+/* Function to allocate memory for zlib. */
+PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
+
+/* Function to free memory for zlib */
+PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
+
+#ifdef PNG_SIZE_T
+/* Function to convert a sizeof an item to png_sizeof item */
+   PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
+#endif
+
+/* Next four functions are used internally as callbacks.  PNGAPI is required
+ * but not PNG_EXPORT.  PNGAPI added at libpng version 1.2.3. */
+
+PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t length));
+#endif
+
+PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+#if !defined(PNG_NO_STDIO)
+PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
+#endif
+#endif
+#else /* PNG_1_0_X */
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t length));
+#endif
+#endif /* PNG_1_0_X */
+
+/* Reset the CRC variable */
+PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
+
+/* Write the "data" buffer to whatever output you are using. */
+PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+/* Read data from whatever input you are using into the "data" buffer */
+PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+/* Read bytes into buf, and update png_ptr->crc */
+PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
+   png_size_t length));
+
+/* Decompress data in a chunk that uses compression */
+#if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
+    defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
+PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
+   int comp_type, png_charp chunkdata, png_size_t chunklength,
+   png_size_t prefix_length, png_size_t *data_length));
+#endif
+
+/* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
+PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
+
+/* Read the CRC from the file and compare it to the libpng calculated CRC */
+PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
+
+/* Calculate the CRC over a section of data.  Note that we are only
+ * passing a maximum of 64K on systems that have this as a memory limit,
+ * since this is the maximum buffer size we can specify.
+ */
+PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
+   png_size_t length));
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
+#endif
+
+
+/* Place a 32-bit number into a buffer in PNG byte order (big-endian).
+ * The only currently known PNG chunks that use signed numbers are
+ * the ancillary extension chunks, oFFs and pCAL.
+ */
+PNG_EXTERN void png_save_uint_32 PNGARG((png_bytep buf, png_uint_32 i));
+
+#if defined(PNG_WRITE_pCAL_SUPPORTED) || defined(PNG_WRITE_oFFs_SUPPORTED)
+PNG_EXTERN void png_save_int_32 PNGARG((png_bytep buf, png_int_32 i));
+#endif
+
+/* Place a 16-bit number into a buffer in PNG byte order.
+ * The parameter is declared unsigned int, not png_uint_16,
+ * just to avoid potential problems on pre-ANSI C compilers.
+ */
+PNG_EXTERN void png_save_uint_16 PNGARG((png_bytep buf, unsigned int i));
+
+/* simple function to write the signature */
+PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
+
+/* write various chunks */
+
+/* Write the IHDR chunk, and update the png_struct with the necessary
+ * information.
+ */
+PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
+   png_uint_32 height,
+   int bit_depth, int color_type, int compression_method, int filter_method,
+   int interlace_method));
+
+PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
+   png_uint_32 num_pal));
+
+PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
+
+#if defined(PNG_WRITE_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
+    file_gamma));
+#endif
+#endif
+
+#if defined(PNG_WRITE_sBIT_SUPPORTED)
+PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
+   int color_type));
+#endif
+
+#if defined(PNG_WRITE_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
+   double white_x, double white_y,
+   double red_x, double red_y, double green_x, double green_y,
+   double blue_x, double blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
+   png_fixed_point int_white_x, png_fixed_point int_white_y,
+   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+   png_fixed_point int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_WRITE_sRGB_SUPPORTED)
+PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
+   int intent));
+#endif
+
+#if defined(PNG_WRITE_iCCP_SUPPORTED)
+PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
+   png_charp name, int compression_type,
+   png_charp profile, int proflen));
+   /* Note to maintainer: profile should be png_bytep */
+#endif
+
+#if defined(PNG_WRITE_sPLT_SUPPORTED)
+PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
+   png_sPLT_tp palette));
+#endif
+
+#if defined(PNG_WRITE_tRNS_SUPPORTED)
+PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
+   png_color_16p values, int number, int color_type));
+#endif
+
+#if defined(PNG_WRITE_bKGD_SUPPORTED)
+PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
+   png_color_16p values, int color_type));
+#endif
+
+#if defined(PNG_WRITE_hIST_SUPPORTED)
+PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
+   int num_hist));
+#endif
+
+#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
+    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
+PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
+   png_charp key, png_charpp new_key));
+#endif
+
+#if defined(PNG_WRITE_tEXt_SUPPORTED)
+PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
+   png_charp text, png_size_t text_len));
+#endif
+
+#if defined(PNG_WRITE_zTXt_SUPPORTED)
+PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
+   png_charp text, png_size_t text_len, int compression));
+#endif
+
+#if defined(PNG_WRITE_iTXt_SUPPORTED)
+PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
+   int compression, png_charp key, png_charp lang, png_charp lang_key,
+   png_charp text));
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)  /* Added at version 1.0.14 and 1.2.4 */
+PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp text_ptr, int num_text));
+#endif
+
+#if defined(PNG_WRITE_oFFs_SUPPORTED)
+PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
+   png_int_32 x_offset, png_int_32 y_offset, int unit_type));
+#endif
+
+#if defined(PNG_WRITE_pCAL_SUPPORTED)
+PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
+   png_int_32 X0, png_int_32 X1, int type, int nparams,
+   png_charp units, png_charpp params));
+#endif
+
+#if defined(PNG_WRITE_pHYs_SUPPORTED)
+PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
+   png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
+   int unit_type));
+#endif
+
+#if defined(PNG_WRITE_tIME_SUPPORTED)
+PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
+   png_timep mod_time));
+#endif
+
+#if defined(PNG_WRITE_sCAL_SUPPORTED)
+#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
+PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
+   int unit, double width, double height));
+#else
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
+   int unit, png_charp width, png_charp height));
+#endif
+#endif
+#endif
+
+/* Called when finished processing a row of data */
+PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
+
+/* Internal use only.   Called before first row of data */
+PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
+#endif
+
+/* combine a row of data, dealing with alpha, etc. if requested */
+PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
+   int mask));
+
+#if defined(PNG_READ_INTERLACING_SUPPORTED)
+/* expand an interlaced row */
+/* OLD pre-1.0.9 interface:
+PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
+   png_bytep row, int pass, png_uint_32 transformations));
+ */
+PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
+#endif
+
+/* GRR TO DO (2.0 or whenever):  simplify other internal calling interfaces */
+
+#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
+/* grab pixels out of a row for an interlaced pass */
+PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
+   png_bytep row, int pass));
+#endif
+
+/* unfilter a row */
+PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
+   png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
+
+/* Choose the best filter to use and filter the row data */
+PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
+   png_row_infop row_info));
+
+/* Write out the filtered row. */
+PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
+   png_bytep filtered_row));
+/* finish a row while reading, dealing with interlacing passes, etc. */
+PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
+
+/* initialize the row buffers, etc. */
+PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
+/* optional call to update the users info structure */
+PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+/* these are the functions that do the transformations */
+#if defined(PNG_READ_FILLER_SUPPORTED)
+PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 filler, png_uint_32 flags));
+#endif
+
+#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
+    defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 flags));
+#endif
+
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
+   row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
+PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_READ_PACK_SUPPORTED)
+PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED)
+PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_8p sig_bits));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_16_TO_8_SUPPORTED)
+PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
+   png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
+
+#  if defined(PNG_CORRECT_PALETTE_SUPPORTED)
+PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
+   png_colorp palette, int num_palette));
+#  endif
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_PACK_SUPPORTED)
+PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 bit_depth));
+#endif
+
+#if defined(PNG_WRITE_SHIFT_SUPPORTED)
+PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_8p bit_depth));
+#endif
+
+#if defined(PNG_READ_BACKGROUND_SUPPORTED)
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_16p trans_values, png_color_16p background,
+   png_color_16p background_1,
+   png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
+   png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
+   png_uint_16pp gamma_16_to_1, int gamma_shift));
+#else
+PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_16p trans_values, png_color_16p background));
+#endif
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
+   png_bytep gamma_table, png_uint_16pp gamma_16_table,
+   int gamma_shift));
+#endif
+
+#if defined(PNG_READ_EXPAND_SUPPORTED)
+PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
+   png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
+PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
+   png_bytep row, png_color_16p trans_value));
+#endif
+
+/* The following decodes the appropriate chunks, and does error correction,
+ * then calls the appropriate callback for the chunk if it is valid.
+ */
+
+/* decode the IHDR chunk */
+PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+
+#if defined(PNG_READ_bKGD_SUPPORTED)
+PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_cHRM_SUPPORTED)
+PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_gAMA_SUPPORTED)
+PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_hIST_SUPPORTED)
+PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_iCCP_SUPPORTED)
+extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif /* PNG_READ_iCCP_SUPPORTED */
+
+#if defined(PNG_READ_iTXt_SUPPORTED)
+PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_oFFs_SUPPORTED)
+PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_pCAL_SUPPORTED)
+PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_pHYs_SUPPORTED)
+PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sBIT_SUPPORTED)
+PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sCAL_SUPPORTED)
+PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sPLT_SUPPORTED)
+extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif /* PNG_READ_sPLT_SUPPORTED */
+
+#if defined(PNG_READ_sRGB_SUPPORTED)
+PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tEXt_SUPPORTED)
+PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tIME_SUPPORTED)
+PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tRNS_SUPPORTED)
+PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_zTXt_SUPPORTED)
+PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+
+PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
+   png_bytep chunk_name));
+
+/* handle the transformations for reading and writing */
+PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
+
+PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
+PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
+#if defined(PNG_READ_tEXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+#if defined(PNG_READ_zTXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+#if defined(PNG_READ_iTXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
+   png_bytep row));
+PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+/* png.c */ /* PRIVATE */
+PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
+#endif
+/* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
+
+#endif /* PNG_INTERNAL */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PNG_VERSION_INFO_ONLY */
+/* do not put anything past this line */
+#endif /* PNG_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/libpng12/pngconf.h ./aperios/include/libpng12/pngconf.h
--- ../Tekkotsu_2.3/aperios/include/libpng12/pngconf.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libpng12/pngconf.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,1437 @@
+
+/* pngconf.h - machine configurable file for libpng
+ *
+ * libpng version 1.2.8 - December 3, 2004
+ * For conditions of distribution and use, see copyright notice in png.h
+ * Copyright (c) 1998-2004 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ */
+
+/* Any machine specific code is near the front of this file, so if you
+ * are configuring libpng for a machine, you may want to read the section
+ * starting here down to where it starts to typedef png_color, png_text,
+ * and png_info.
+ */
+
+#ifndef PNGCONF_H
+#define PNGCONF_H
+
+#define PNG_1_2_X
+
+/* 
+ * PNG_USER_CONFIG has to be defined on the compiler command line. This
+ * includes the resource compiler for Windows DLL configurations.
+ */
+#ifdef PNG_USER_CONFIG
+#include "pngusr.h"
+#endif
+
+/*
+ * Added at libpng-1.2.8
+ *  
+ * If you create a private DLL you need to define in "pngusr.h" the followings:
+ * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
+ *        the DLL was built>
+ *  e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
+ * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
+ *        distinguish your DLL from those of the official release. These
+ *        correspond to the trailing letters that come after the version
+ *        number and must match your private DLL name>
+ *  e.g. // private DLL "libpng13gx.dll"
+ *       #define PNG_USER_DLLFNAME_POSTFIX "gx"
+ * 
+ * The following macros are also at your disposal if you want to complete the 
+ * DLL VERSIONINFO structure.
+ * - PNG_USER_VERSIONINFO_COMMENTS
+ * - PNG_USER_VERSIONINFO_COMPANYNAME
+ * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
+ */
+
+#ifdef __STDC__
+#ifdef SPECIALBUILD
+#  pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
+ are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
+#endif
+
+#ifdef PRIVATEBUILD
+# pragma message("PRIVATEBUILD is deprecated. Use\
+ PNG_USER_PRIVATEBUILD instead.")
+# define PNG_USER_PRIVATEBUILD PRIVATEBUILD
+#endif
+#endif /* __STDC__ */
+
+#ifndef PNG_VERSION_INFO_ONLY
+
+/* End of material added to libpng-1.2.8 */
+
+/* This is the size of the compression buffer, and thus the size of
+ * an IDAT chunk.  Make this whatever size you feel is best for your
+ * machine.  One of these will be allocated per png_struct.  When this
+ * is full, it writes the data to the disk, and does some other
+ * calculations.  Making this an extremely small size will slow
+ * the library down, but you may want to experiment to determine
+ * where it becomes significant, if you are concerned with memory
+ * usage.  Note that zlib allocates at least 32Kb also.  For readers,
+ * this describes the size of the buffer available to read the data in.
+ * Unless this gets smaller than the size of a row (compressed),
+ * it should not make much difference how big this is.
+ */
+
+#ifndef PNG_ZBUF_SIZE
+#  define PNG_ZBUF_SIZE 8192
+#endif
+
+/* Enable if you want a write-only libpng */
+
+#ifndef PNG_NO_READ_SUPPORTED
+#  define PNG_READ_SUPPORTED
+#endif
+
+/* Enable if you want a read-only libpng */
+
+#ifndef PNG_NO_WRITE_SUPPORTED
+#  define PNG_WRITE_SUPPORTED
+#endif
+
+/* Enabled by default in 1.2.0.  You can disable this if you don't need to
+   support PNGs that are embedded in MNG datastreams */
+#if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
+#  ifndef PNG_MNG_FEATURES_SUPPORTED
+#    define PNG_MNG_FEATURES_SUPPORTED
+#  endif
+#endif
+
+#ifndef PNG_NO_FLOATING_POINT_SUPPORTED
+#  ifndef PNG_FLOATING_POINT_SUPPORTED
+#    define PNG_FLOATING_POINT_SUPPORTED
+#  endif
+#endif
+
+/* If you are running on a machine where you cannot allocate more
+ * than 64K of memory at once, uncomment this.  While libpng will not
+ * normally need that much memory in a chunk (unless you load up a very
+ * large file), zlib needs to know how big of a chunk it can use, and
+ * libpng thus makes sure to check any memory allocation to verify it
+ * will fit into memory.
+#define PNG_MAX_MALLOC_64K
+ */
+#if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
+#  define PNG_MAX_MALLOC_64K
+#endif
+
+/* Special munging to support doing things the 'cygwin' way:
+ * 'Normal' png-on-win32 defines/defaults:
+ *   PNG_BUILD_DLL -- building dll
+ *   PNG_USE_DLL   -- building an application, linking to dll
+ *   (no define)   -- building static library, or building an
+ *                    application and linking to the static lib
+ * 'Cygwin' defines/defaults:
+ *   PNG_BUILD_DLL -- (ignored) building the dll
+ *   (no define)   -- (ignored) building an application, linking to the dll
+ *   PNG_STATIC    -- (ignored) building the static lib, or building an 
+ *                    application that links to the static lib.
+ *   ALL_STATIC    -- (ignored) building various static libs, or building an 
+ *                    application that links to the static libs.
+ * Thus,
+ * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
+ * this bit of #ifdefs will define the 'correct' config variables based on
+ * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
+ * unnecessary.
+ *
+ * Also, the precedence order is:
+ *   ALL_STATIC (since we can't #undef something outside our namespace)
+ *   PNG_BUILD_DLL
+ *   PNG_STATIC
+ *   (nothing) == PNG_USE_DLL
+ * 
+ * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
+ *   of auto-import in binutils, we no longer need to worry about 
+ *   __declspec(dllexport) / __declspec(dllimport) and friends.  Therefore,
+ *   we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
+ *   to __declspec() stuff.  However, we DO need to worry about 
+ *   PNG_BUILD_DLL and PNG_STATIC because those change some defaults
+ *   such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
+ */
+#if defined(__CYGWIN__)
+#  if defined(ALL_STATIC)
+#    if defined(PNG_BUILD_DLL)
+#      undef PNG_BUILD_DLL
+#    endif
+#    if defined(PNG_USE_DLL)
+#      undef PNG_USE_DLL
+#    endif
+#    if defined(PNG_DLL)
+#      undef PNG_DLL
+#    endif
+#    if !defined(PNG_STATIC)
+#      define PNG_STATIC
+#    endif
+#  else
+#    if defined (PNG_BUILD_DLL)
+#      if defined(PNG_STATIC)
+#        undef PNG_STATIC
+#      endif
+#      if defined(PNG_USE_DLL)
+#        undef PNG_USE_DLL
+#      endif
+#      if !defined(PNG_DLL)
+#        define PNG_DLL
+#      endif
+#    else
+#      if defined(PNG_STATIC)
+#        if defined(PNG_USE_DLL)
+#          undef PNG_USE_DLL
+#        endif
+#        if defined(PNG_DLL)
+#          undef PNG_DLL
+#        endif
+#      else
+#        if !defined(PNG_USE_DLL)
+#          define PNG_USE_DLL
+#        endif
+#        if !defined(PNG_DLL)
+#          define PNG_DLL
+#        endif
+#      endif  
+#    endif  
+#  endif
+#endif
+
+/* This protects us against compilers that run on a windowing system
+ * and thus don't have or would rather us not use the stdio types:
+ * stdin, stdout, and stderr.  The only one currently used is stderr
+ * in png_error() and png_warning().  #defining PNG_NO_CONSOLE_IO will
+ * prevent these from being compiled and used. #defining PNG_NO_STDIO
+ * will also prevent these, plus will prevent the entire set of stdio
+ * macros and functions (FILE *, printf, etc.) from being compiled and used,
+ * unless (PNG_DEBUG > 0) has been #defined.
+ *
+ * #define PNG_NO_CONSOLE_IO
+ * #define PNG_NO_STDIO
+ */
+
+#if defined(_WIN32_WCE)
+#  include <windows.h>
+   /* Console I/O functions are not supported on WindowsCE */
+#  define PNG_NO_CONSOLE_IO
+#  ifdef PNG_DEBUG
+#    undef PNG_DEBUG
+#  endif
+#endif
+
+#ifdef PNG_BUILD_DLL
+#  ifndef PNG_CONSOLE_IO_SUPPORTED
+#    ifndef PNG_NO_CONSOLE_IO
+#      define PNG_NO_CONSOLE_IO
+#    endif
+#  endif
+#endif
+
+#  ifdef PNG_NO_STDIO
+#    ifndef PNG_NO_CONSOLE_IO
+#      define PNG_NO_CONSOLE_IO
+#    endif
+#    ifdef PNG_DEBUG
+#      if (PNG_DEBUG > 0)
+#        include <stdio.h>
+#      endif
+#    endif
+#  else
+#    if !defined(_WIN32_WCE)
+/* "stdio.h" functions are not supported on WindowsCE */
+#      include <stdio.h>
+#    endif
+#  endif
+
+/* This macro protects us against machines that don't have function
+ * prototypes (ie K&R style headers).  If your compiler does not handle
+ * function prototypes, define this macro and use the included ansi2knr.
+ * I've always been able to use _NO_PROTO as the indicator, but you may
+ * need to drag the empty declaration out in front of here, or change the
+ * ifdef to suit your own needs.
+ */
+#ifndef PNGARG
+
+#ifdef OF /* zlib prototype munger */
+#  define PNGARG(arglist) OF(arglist)
+#else
+
+#ifdef _NO_PROTO
+#  define PNGARG(arglist) ()
+#  ifndef PNG_TYPECAST_NULL
+#     define PNG_TYPECAST_NULL
+#  endif
+#else
+#  define PNGARG(arglist) arglist
+#endif /* _NO_PROTO */
+
+#endif /* OF */
+
+#endif /* PNGARG */
+
+/* Try to determine if we are compiling on a Mac.  Note that testing for
+ * just __MWERKS__ is not good enough, because the Codewarrior is now used
+ * on non-Mac platforms.
+ */
+#ifndef MACOS
+#  if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
+      defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
+#    define MACOS
+#  endif
+#endif
+
+/* enough people need this for various reasons to include it here */
+#if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
+#  include <sys/types.h>
+#endif
+
+#if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
+#  define PNG_SETJMP_SUPPORTED
+#endif
+
+#ifdef PNG_SETJMP_SUPPORTED
+/* This is an attempt to force a single setjmp behaviour on Linux.  If
+ * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
+ */
+
+#  ifdef __linux__
+#    ifdef _BSD_SOURCE
+#      define PNG_SAVE_BSD_SOURCE
+#      undef _BSD_SOURCE
+#    endif
+#    ifdef _SETJMP_H
+     /* If you encounter a compiler error here, see the explanation
+      * near the end of INSTALL.
+      */
+         __png.h__ already includes setjmp.h;
+         __dont__ include it again.;
+#    endif
+#  endif /* __linux__ */
+
+   /* include setjmp.h for error handling */
+#  include <setjmp.h>
+
+#  ifdef __linux__
+#    ifdef PNG_SAVE_BSD_SOURCE
+#      define _BSD_SOURCE
+#      undef PNG_SAVE_BSD_SOURCE
+#    endif
+#  endif /* __linux__ */
+#endif /* PNG_SETJMP_SUPPORTED */
+
+#ifdef BSD
+#  include <strings.h>
+#else
+#  include <string.h>
+#endif
+
+/* Other defines for things like memory and the like can go here.  */
+#ifdef PNG_INTERNAL
+
+#include <stdlib.h>
+
+/* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
+ * aren't usually used outside the library (as far as I know), so it is
+ * debatable if they should be exported at all.  In the future, when it is
+ * possible to have run-time registry of chunk-handling functions, some of
+ * these will be made available again.
+#define PNG_EXTERN extern
+ */
+#define PNG_EXTERN
+
+/* Other defines specific to compilers can go here.  Try to keep
+ * them inside an appropriate ifdef/endif pair for portability.
+ */
+
+#if defined(PNG_FLOATING_POINT_SUPPORTED)
+#  if defined(MACOS)
+     /* We need to check that <math.h> hasn't already been included earlier
+      * as it seems it doesn't agree with <fp.h>, yet we should really use
+      * <fp.h> if possible.
+      */
+#    if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
+#      include <fp.h>
+#    endif
+#  else
+#    include <math.h>
+#  endif
+#  if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
+     /* Amiga SAS/C: We must include builtin FPU functions when compiling using
+      * MATH=68881
+      */
+#    include <m68881.h>
+#  endif
+#endif
+
+/* Codewarrior on NT has linking problems without this. */
+#if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
+#  define PNG_ALWAYS_EXTERN
+#endif
+
+/* This provides the non-ANSI (far) memory allocation routines. */
+#if defined(__TURBOC__) && defined(__MSDOS__)
+#  include <mem.h>
+#  include <alloc.h>
+#endif
+
+/* I have no idea why is this necessary... */
+#if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
+    defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
+#  include <malloc.h>
+#endif
+
+/* This controls how fine the dithering gets.  As this allocates
+ * a largish chunk of memory (32K), those who are not as concerned
+ * with dithering quality can decrease some or all of these.
+ */
+#ifndef PNG_DITHER_RED_BITS
+#  define PNG_DITHER_RED_BITS 5
+#endif
+#ifndef PNG_DITHER_GREEN_BITS
+#  define PNG_DITHER_GREEN_BITS 5
+#endif
+#ifndef PNG_DITHER_BLUE_BITS
+#  define PNG_DITHER_BLUE_BITS 5
+#endif
+
+/* This controls how fine the gamma correction becomes when you
+ * are only interested in 8 bits anyway.  Increasing this value
+ * results in more memory being used, and more pow() functions
+ * being called to fill in the gamma tables.  Don't set this value
+ * less then 8, and even that may not work (I haven't tested it).
+ */
+
+#ifndef PNG_MAX_GAMMA_8
+#  define PNG_MAX_GAMMA_8 11
+#endif
+
+/* This controls how much a difference in gamma we can tolerate before
+ * we actually start doing gamma conversion.
+ */
+#ifndef PNG_GAMMA_THRESHOLD
+#  define PNG_GAMMA_THRESHOLD 0.05
+#endif
+
+#endif /* PNG_INTERNAL */
+
+/* The following uses const char * instead of char * for error
+ * and warning message functions, so some compilers won't complain.
+ * If you do not want to use const, define PNG_NO_CONST here.
+ */
+
+#ifndef PNG_NO_CONST
+#  define PNG_CONST const
+#else
+#  define PNG_CONST
+#endif
+
+/* The following defines give you the ability to remove code from the
+ * library that you will not be using.  I wish I could figure out how to
+ * automate this, but I can't do that without making it seriously hard
+ * on the users.  So if you are not using an ability, change the #define
+ * to and #undef, and that part of the library will not be compiled.  If
+ * your linker can't find a function, you may want to make sure the
+ * ability is defined here.  Some of these depend upon some others being
+ * defined.  I haven't figured out all the interactions here, so you may
+ * have to experiment awhile to get everything to compile.  If you are
+ * creating or using a shared library, you probably shouldn't touch this,
+ * as it will affect the size of the structures, and this will cause bad
+ * things to happen if the library and/or application ever change.
+ */
+
+/* Any features you will not be using can be undef'ed here */
+
+/* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
+ * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
+ * on the compile line, then pick and choose which ones to define without
+ * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
+ * if you only want to have a png-compliant reader/writer but don't need
+ * any of the extra transformations.  This saves about 80 kbytes in a
+ * typical installation of the library. (PNG_NO_* form added in version
+ * 1.0.1c, for consistency)
+ */
+
+/* The size of the png_text structure changed in libpng-1.0.6 when
+ * iTXt is supported.  It is turned off by default, to support old apps
+ * that malloc the png_text structure instead of calling png_set_text()
+ * and letting libpng malloc it.  It will be turned on by default in
+ * libpng-1.3.0.
+ */
+
+#ifndef PNG_iTXt_SUPPORTED
+#  if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
+#    define PNG_NO_READ_iTXt
+#  endif
+#  if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
+#    define PNG_NO_WRITE_iTXt
+#  endif
+#endif
+
+/* The following support, added after version 1.0.0, can be turned off here en
+ * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
+ * with old applications that require the length of png_struct and png_info
+ * to remain unchanged.
+ */
+
+#ifdef PNG_LEGACY_SUPPORTED
+#  define PNG_NO_FREE_ME
+#  define PNG_NO_READ_UNKNOWN_CHUNKS
+#  define PNG_NO_WRITE_UNKNOWN_CHUNKS
+#  define PNG_NO_READ_USER_CHUNKS
+#  define PNG_NO_READ_iCCP
+#  define PNG_NO_WRITE_iCCP
+#  define PNG_NO_READ_iTXt
+#  define PNG_NO_WRITE_iTXt
+#  define PNG_NO_READ_sCAL
+#  define PNG_NO_WRITE_sCAL
+#  define PNG_NO_READ_sPLT
+#  define PNG_NO_WRITE_sPLT
+#  define PNG_NO_INFO_IMAGE
+#  define PNG_NO_READ_RGB_TO_GRAY
+#  define PNG_NO_READ_USER_TRANSFORM
+#  define PNG_NO_WRITE_USER_TRANSFORM
+#  define PNG_NO_USER_MEM
+#  define PNG_NO_READ_EMPTY_PLTE
+#  define PNG_NO_MNG_FEATURES
+#  define PNG_NO_FIXED_POINT_SUPPORTED
+#endif
+
+/* Ignore attempt to turn off both floating and fixed point support */
+#if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
+    !defined(PNG_NO_FIXED_POINT_SUPPORTED)
+#  define PNG_FIXED_POINT_SUPPORTED
+#endif
+
+#ifndef PNG_NO_FREE_ME
+#  define PNG_FREE_ME_SUPPORTED
+#endif
+
+#if defined(PNG_READ_SUPPORTED)
+
+#if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
+      !defined(PNG_NO_READ_TRANSFORMS)
+#  define PNG_READ_TRANSFORMS_SUPPORTED
+#endif
+
+#ifdef PNG_READ_TRANSFORMS_SUPPORTED
+#  ifndef PNG_NO_READ_EXPAND
+#    define PNG_READ_EXPAND_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SHIFT
+#    define PNG_READ_SHIFT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_PACK
+#    define PNG_READ_PACK_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_BGR
+#    define PNG_READ_BGR_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SWAP
+#    define PNG_READ_SWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_PACKSWAP
+#    define PNG_READ_PACKSWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_INVERT
+#    define PNG_READ_INVERT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_DITHER
+#    define PNG_READ_DITHER_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_BACKGROUND
+#    define PNG_READ_BACKGROUND_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_16_TO_8
+#    define PNG_READ_16_TO_8_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_FILLER
+#    define PNG_READ_FILLER_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_GAMMA
+#    define PNG_READ_GAMMA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_GRAY_TO_RGB
+#    define PNG_READ_GRAY_TO_RGB_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SWAP_ALPHA
+#    define PNG_READ_SWAP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_INVERT_ALPHA
+#    define PNG_READ_INVERT_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_STRIP_ALPHA
+#    define PNG_READ_STRIP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_USER_TRANSFORM
+#    define PNG_READ_USER_TRANSFORM_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_RGB_TO_GRAY
+#    define PNG_READ_RGB_TO_GRAY_SUPPORTED
+#  endif
+#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
+
+#if !defined(PNG_NO_PROGRESSIVE_READ) && \
+ !defined(PNG_PROGRESSIVE_READ_NOT_SUPPORTED)  /* if you don't do progressive */
+#  define PNG_PROGRESSIVE_READ_SUPPORTED     /* reading.  This is not talking */
+#endif                               /* about interlacing capability!  You'll */
+              /* still have interlacing unless you change the following line: */
+
+#define PNG_READ_INTERLACING_SUPPORTED /* required for PNG-compliant decoders */
+
+#ifndef PNG_NO_READ_COMPOSITE_NODIV
+#  ifndef PNG_NO_READ_COMPOSITED_NODIV  /* libpng-1.0.x misspelling */
+#    define PNG_READ_COMPOSITE_NODIV_SUPPORTED   /* well tested on Intel, SGI */
+#  endif
+#endif
+
+/* Deprecated, will be removed from version 2.0.0.
+   Use PNG_MNG_FEATURES_SUPPORTED instead. */
+#ifndef PNG_NO_READ_EMPTY_PLTE
+#  define PNG_READ_EMPTY_PLTE_SUPPORTED
+#endif
+
+#endif /* PNG_READ_SUPPORTED */
+
+#if defined(PNG_WRITE_SUPPORTED)
+
+# if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_WRITE_TRANSFORMS)
+#  define PNG_WRITE_TRANSFORMS_SUPPORTED
+#endif
+
+#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
+#  ifndef PNG_NO_WRITE_SHIFT
+#    define PNG_WRITE_SHIFT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_PACK
+#    define PNG_WRITE_PACK_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_BGR
+#    define PNG_WRITE_BGR_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_SWAP
+#    define PNG_WRITE_SWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_PACKSWAP
+#    define PNG_WRITE_PACKSWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_INVERT
+#    define PNG_WRITE_INVERT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_FILLER
+#    define PNG_WRITE_FILLER_SUPPORTED   /* same as WRITE_STRIP_ALPHA */
+#  endif
+#  ifndef PNG_NO_WRITE_SWAP_ALPHA
+#    define PNG_WRITE_SWAP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_INVERT_ALPHA
+#    define PNG_WRITE_INVERT_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_USER_TRANSFORM
+#    define PNG_WRITE_USER_TRANSFORM_SUPPORTED
+#  endif
+#endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
+
+#define PNG_WRITE_INTERLACING_SUPPORTED  /* not required for PNG-compliant
+                                            encoders, but can cause trouble
+                                            if left undefined */
+
+#if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
+     defined(PNG_FLOATING_POINT_SUPPORTED)
+#  define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
+#endif
+
+#ifndef PNG_NO_WRITE_FLUSH
+#  define PNG_WRITE_FLUSH_SUPPORTED
+#endif
+
+/* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
+#ifndef PNG_NO_WRITE_EMPTY_PLTE
+#  define PNG_WRITE_EMPTY_PLTE_SUPPORTED
+#endif
+
+#endif /* PNG_WRITE_SUPPORTED */
+
+#ifndef PNG_1_0_X
+#  ifndef PNG_NO_ERROR_NUMBERS
+#    define PNG_ERROR_NUMBERS_SUPPORTED
+#  endif
+#endif /* PNG_1_0_X */
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+#  ifndef PNG_NO_USER_TRANSFORM_PTR
+#    define PNG_USER_TRANSFORM_PTR_SUPPORTED
+#  endif
+#endif
+
+#ifndef PNG_NO_STDIO
+#  define PNG_TIME_RFC1123_SUPPORTED
+#endif
+
+/* This adds extra functions in pngget.c for accessing data from the
+ * info pointer (added in version 0.99)
+ * png_get_image_width()
+ * png_get_image_height()
+ * png_get_bit_depth()
+ * png_get_color_type()
+ * png_get_compression_type()
+ * png_get_filter_type()
+ * png_get_interlace_type()
+ * png_get_pixel_aspect_ratio()
+ * png_get_pixels_per_meter()
+ * png_get_x_offset_pixels()
+ * png_get_y_offset_pixels()
+ * png_get_x_offset_microns()
+ * png_get_y_offset_microns()
+ */
+#if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
+#  define PNG_EASY_ACCESS_SUPPORTED
+#endif
+
+/* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0 
+   even when PNG_USE_PNGVCRD or PNG_USE_PNGGCCRD is not defined */
+#if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
+#  ifndef PNG_ASSEMBLER_CODE_SUPPORTED
+#    define PNG_ASSEMBLER_CODE_SUPPORTED
+#  endif
+#  if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
+#    define PNG_MMX_CODE_SUPPORTED
+#  endif
+#endif
+
+/* If you are sure that you don't need thread safety and you are compiling
+   with PNG_USE_PNGCCRD for an MMX application, you can define this for
+   faster execution.  See pnggccrd.c.
+#define PNG_THREAD_UNSAFE_OK
+*/
+
+#if !defined(PNG_1_0_X)
+#if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
+#  define PNG_USER_MEM_SUPPORTED
+#endif
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.2.6 */
+#if !defined(PNG_1_0_X)
+#ifndef PNG_SET_USER_LIMITS_SUPPORTED
+#if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
+#  define PNG_SET_USER_LIMITS_SUPPORTED
+#endif
+#endif
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.0.16 and 1.2.6.  To accept all valid PNGS no matter
+ * how large, set these limits to 0x7fffffffL
+ */
+#ifndef PNG_USER_WIDTH_MAX
+#  define PNG_USER_WIDTH_MAX 1000000L
+#endif
+#ifndef PNG_USER_HEIGHT_MAX
+#  define PNG_USER_HEIGHT_MAX 1000000L
+#endif
+
+/* These are currently experimental features, define them if you want */
+
+/* very little testing */
+/*
+#ifdef PNG_READ_SUPPORTED
+#  ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
+#    define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
+#  endif
+#endif
+*/
+
+/* This is only for PowerPC big-endian and 680x0 systems */
+/* some testing */
+/*
+#ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
+#  define PNG_READ_BIG_ENDIAN_SUPPORTED
+#endif
+*/
+
+/* Buggy compilers (e.g., gcc 2.7.2.2) need this */
+/*
+#define PNG_NO_POINTER_INDEXING
+*/
+
+/* These functions are turned off by default, as they will be phased out. */
+/*
+#define  PNG_USELESS_TESTS_SUPPORTED
+#define  PNG_CORRECT_PALETTE_SUPPORTED
+*/
+
+/* Any chunks you are not interested in, you can undef here.  The
+ * ones that allocate memory may be expecially important (hIST,
+ * tEXt, zTXt, tRNS, pCAL).  Others will just save time and make png_info
+ * a bit smaller.
+ */
+
+#if defined(PNG_READ_SUPPORTED) && \
+    !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
+#  define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
+#endif
+
+#if defined(PNG_WRITE_SUPPORTED) && \
+    !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
+#  define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
+#endif
+
+#ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
+
+#ifdef PNG_NO_READ_TEXT
+#  define PNG_NO_READ_iTXt
+#  define PNG_NO_READ_tEXt
+#  define PNG_NO_READ_zTXt
+#endif
+#ifndef PNG_NO_READ_bKGD
+#  define PNG_READ_bKGD_SUPPORTED
+#  define PNG_bKGD_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_cHRM
+#  define PNG_READ_cHRM_SUPPORTED
+#  define PNG_cHRM_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_gAMA
+#  define PNG_READ_gAMA_SUPPORTED
+#  define PNG_gAMA_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_hIST
+#  define PNG_READ_hIST_SUPPORTED
+#  define PNG_hIST_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_iCCP
+#  define PNG_READ_iCCP_SUPPORTED
+#  define PNG_iCCP_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_iTXt
+#  ifndef PNG_READ_iTXt_SUPPORTED
+#    define PNG_READ_iTXt_SUPPORTED
+#  endif
+#  ifndef PNG_iTXt_SUPPORTED
+#    define PNG_iTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_READ_oFFs
+#  define PNG_READ_oFFs_SUPPORTED
+#  define PNG_oFFs_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_pCAL
+#  define PNG_READ_pCAL_SUPPORTED
+#  define PNG_pCAL_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sCAL
+#  define PNG_READ_sCAL_SUPPORTED
+#  define PNG_sCAL_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_pHYs
+#  define PNG_READ_pHYs_SUPPORTED
+#  define PNG_pHYs_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sBIT
+#  define PNG_READ_sBIT_SUPPORTED
+#  define PNG_sBIT_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sPLT
+#  define PNG_READ_sPLT_SUPPORTED
+#  define PNG_sPLT_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sRGB
+#  define PNG_READ_sRGB_SUPPORTED
+#  define PNG_sRGB_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tEXt
+#  define PNG_READ_tEXt_SUPPORTED
+#  define PNG_tEXt_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tIME
+#  define PNG_READ_tIME_SUPPORTED
+#  define PNG_tIME_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tRNS
+#  define PNG_READ_tRNS_SUPPORTED
+#  define PNG_tRNS_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_zTXt
+#  define PNG_READ_zTXt_SUPPORTED
+#  define PNG_zTXt_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_UNKNOWN_CHUNKS
+#  define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
+#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
+#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
+#  endif
+#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
+#    define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#  endif
+#endif
+#if !defined(PNG_NO_READ_USER_CHUNKS) && \
+     defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
+#  define PNG_READ_USER_CHUNKS_SUPPORTED
+#  define PNG_USER_CHUNKS_SUPPORTED
+#  ifdef PNG_NO_READ_UNKNOWN_CHUNKS
+#    undef PNG_NO_READ_UNKNOWN_CHUNKS
+#  endif
+#  ifdef PNG_NO_HANDLE_AS_UNKNOWN
+#    undef PNG_NO_HANDLE_AS_UNKNOWN
+#  endif
+#endif
+#ifndef PNG_NO_READ_OPT_PLTE
+#  define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
+#endif                      /* optional PLTE chunk in RGB and RGBA images */
+#if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
+    defined(PNG_READ_zTXt_SUPPORTED)
+#  define PNG_READ_TEXT_SUPPORTED
+#  define PNG_TEXT_SUPPORTED
+#endif
+
+#endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
+
+#ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
+
+#ifdef PNG_NO_WRITE_TEXT
+#  define PNG_NO_WRITE_iTXt
+#  define PNG_NO_WRITE_tEXt
+#  define PNG_NO_WRITE_zTXt
+#endif
+#ifndef PNG_NO_WRITE_bKGD
+#  define PNG_WRITE_bKGD_SUPPORTED
+#  ifndef PNG_bKGD_SUPPORTED
+#    define PNG_bKGD_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_cHRM
+#  define PNG_WRITE_cHRM_SUPPORTED
+#  ifndef PNG_cHRM_SUPPORTED
+#    define PNG_cHRM_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_gAMA
+#  define PNG_WRITE_gAMA_SUPPORTED
+#  ifndef PNG_gAMA_SUPPORTED
+#    define PNG_gAMA_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_hIST
+#  define PNG_WRITE_hIST_SUPPORTED
+#  ifndef PNG_hIST_SUPPORTED
+#    define PNG_hIST_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_iCCP
+#  define PNG_WRITE_iCCP_SUPPORTED
+#  ifndef PNG_iCCP_SUPPORTED
+#    define PNG_iCCP_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_iTXt
+#  ifndef PNG_WRITE_iTXt_SUPPORTED
+#    define PNG_WRITE_iTXt_SUPPORTED
+#  endif
+#  ifndef PNG_iTXt_SUPPORTED
+#    define PNG_iTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_oFFs
+#  define PNG_WRITE_oFFs_SUPPORTED
+#  ifndef PNG_oFFs_SUPPORTED
+#    define PNG_oFFs_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_pCAL
+#  define PNG_WRITE_pCAL_SUPPORTED
+#  ifndef PNG_pCAL_SUPPORTED
+#    define PNG_pCAL_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sCAL
+#  define PNG_WRITE_sCAL_SUPPORTED
+#  ifndef PNG_sCAL_SUPPORTED
+#    define PNG_sCAL_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_pHYs
+#  define PNG_WRITE_pHYs_SUPPORTED
+#  ifndef PNG_pHYs_SUPPORTED
+#    define PNG_pHYs_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sBIT
+#  define PNG_WRITE_sBIT_SUPPORTED
+#  ifndef PNG_sBIT_SUPPORTED
+#    define PNG_sBIT_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sPLT
+#  define PNG_WRITE_sPLT_SUPPORTED
+#  ifndef PNG_sPLT_SUPPORTED
+#    define PNG_sPLT_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sRGB
+#  define PNG_WRITE_sRGB_SUPPORTED
+#  ifndef PNG_sRGB_SUPPORTED
+#    define PNG_sRGB_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tEXt
+#  define PNG_WRITE_tEXt_SUPPORTED
+#  ifndef PNG_tEXt_SUPPORTED
+#    define PNG_tEXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tIME
+#  define PNG_WRITE_tIME_SUPPORTED
+#  ifndef PNG_tIME_SUPPORTED
+#    define PNG_tIME_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tRNS
+#  define PNG_WRITE_tRNS_SUPPORTED
+#  ifndef PNG_tRNS_SUPPORTED
+#    define PNG_tRNS_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_zTXt
+#  define PNG_WRITE_zTXt_SUPPORTED
+#  ifndef PNG_zTXt_SUPPORTED
+#    define PNG_zTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
+#  define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
+#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
+#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
+#  endif
+#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
+#     ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#       define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#     endif
+#  endif
+#endif
+#if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
+    defined(PNG_WRITE_zTXt_SUPPORTED)
+#  define PNG_WRITE_TEXT_SUPPORTED
+#  ifndef PNG_TEXT_SUPPORTED
+#    define PNG_TEXT_SUPPORTED
+#  endif
+#endif
+
+#endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
+
+/* Turn this off to disable png_read_png() and
+ * png_write_png() and leave the row_pointers member
+ * out of the info structure.
+ */
+#ifndef PNG_NO_INFO_IMAGE
+#  define PNG_INFO_IMAGE_SUPPORTED
+#endif
+
+/* need the time information for reading tIME chunks */
+#if defined(PNG_tIME_SUPPORTED)
+#  if !defined(_WIN32_WCE)
+     /* "time.h" functions are not supported on WindowsCE */
+#    include <time.h>
+#  endif
+#endif
+
+/* Some typedefs to get us started.  These should be safe on most of the
+ * common platforms.  The typedefs should be at least as large as the
+ * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
+ * don't have to be exactly that size.  Some compilers dislike passing
+ * unsigned shorts as function parameters, so you may be better off using
+ * unsigned int for png_uint_16.  Likewise, for 64-bit systems, you may
+ * want to have unsigned int for png_uint_32 instead of unsigned long.
+ */
+
+typedef unsigned long png_uint_32;
+typedef long png_int_32;
+typedef unsigned short png_uint_16;
+typedef short png_int_16;
+typedef unsigned char png_byte;
+
+/* This is usually size_t.  It is typedef'ed just in case you need it to
+   change (I'm not sure if you will or not, so I thought I'd be safe) */
+#ifdef PNG_SIZE_T
+   typedef PNG_SIZE_T png_size_t;
+#  define png_sizeof(x) png_convert_size(sizeof (x))
+#else
+   typedef size_t png_size_t;
+#  define png_sizeof(x) sizeof (x)
+#endif
+
+/* The following is needed for medium model support.  It cannot be in the
+ * PNG_INTERNAL section.  Needs modification for other compilers besides
+ * MSC.  Model independent support declares all arrays and pointers to be
+ * large using the far keyword.  The zlib version used must also support
+ * model independent data.  As of version zlib 1.0.4, the necessary changes
+ * have been made in zlib.  The USE_FAR_KEYWORD define triggers other
+ * changes that are needed. (Tim Wegner)
+ */
+
+/* Separate compiler dependencies (problem here is that zlib.h always
+   defines FAR. (SJT) */
+#ifdef __BORLANDC__
+#  if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
+#    define LDATA 1
+#  else
+#    define LDATA 0
+#  endif
+   /* GRR:  why is Cygwin in here?  Cygwin is not Borland C... */
+#  if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
+#    define PNG_MAX_MALLOC_64K
+#    if (LDATA != 1)
+#      ifndef FAR
+#        define FAR __far
+#      endif
+#      define USE_FAR_KEYWORD
+#    endif   /* LDATA != 1 */
+     /* Possibly useful for moving data out of default segment.
+      * Uncomment it if you want. Could also define FARDATA as
+      * const if your compiler supports it. (SJT)
+#    define FARDATA FAR
+      */
+#  endif  /* __WIN32__, __FLAT__, __CYGWIN__ */
+#endif   /* __BORLANDC__ */
+
+
+/* Suggest testing for specific compiler first before testing for
+ * FAR.  The Watcom compiler defines both __MEDIUM__ and M_I86MM,
+ * making reliance oncertain keywords suspect. (SJT)
+ */
+
+/* MSC Medium model */
+#if defined(FAR)
+#  if defined(M_I86MM)
+#    define USE_FAR_KEYWORD
+#    define FARDATA FAR
+#    include <dos.h>
+#  endif
+#endif
+
+/* SJT: default case */
+#ifndef FAR
+#  define FAR
+#endif
+
+/* At this point FAR is always defined */
+#ifndef FARDATA
+#  define FARDATA
+#endif
+
+/* Typedef for floating-point numbers that are converted
+   to fixed-point with a multiple of 100,000, e.g., int_gamma */
+typedef png_int_32 png_fixed_point;
+
+/* Add typedefs for pointers */
+typedef void            FAR * png_voidp;
+typedef png_byte        FAR * png_bytep;
+typedef png_uint_32     FAR * png_uint_32p;
+typedef png_int_32      FAR * png_int_32p;
+typedef png_uint_16     FAR * png_uint_16p;
+typedef png_int_16      FAR * png_int_16p;
+typedef PNG_CONST char  FAR * png_const_charp;
+typedef char            FAR * png_charp;
+typedef png_fixed_point FAR * png_fixed_point_p;
+
+#ifndef PNG_NO_STDIO
+#if defined(_WIN32_WCE)
+typedef HANDLE                png_FILE_p;
+#else
+typedef FILE                * png_FILE_p;
+#endif
+#endif
+
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double          FAR * png_doublep;
+#endif
+
+/* Pointers to pointers; i.e. arrays */
+typedef png_byte        FAR * FAR * png_bytepp;
+typedef png_uint_32     FAR * FAR * png_uint_32pp;
+typedef png_int_32      FAR * FAR * png_int_32pp;
+typedef png_uint_16     FAR * FAR * png_uint_16pp;
+typedef png_int_16      FAR * FAR * png_int_16pp;
+typedef PNG_CONST char  FAR * FAR * png_const_charpp;
+typedef char            FAR * FAR * png_charpp;
+typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double          FAR * FAR * png_doublepp;
+#endif
+
+/* Pointers to pointers to pointers; i.e., pointer to array */
+typedef char            FAR * FAR * FAR * png_charppp;
+
+#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
+/* SPC -  Is this stuff deprecated? */
+/* It'll be removed as of libpng-1.3.0 - GR-P */
+/* libpng typedefs for types in zlib. If zlib changes
+ * or another compression library is used, then change these.
+ * Eliminates need to change all the source files.
+ */
+typedef charf *         png_zcharp;
+typedef charf * FAR *   png_zcharpp;
+typedef z_stream FAR *  png_zstreamp;
+#endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
+
+/*
+ * Define PNG_BUILD_DLL if the module being built is a Windows
+ * LIBPNG DLL.
+ *
+ * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
+ * It is equivalent to Microsoft predefined macro _DLL that is
+ * automatically defined when you compile using the share
+ * version of the CRT (C Run-Time library)
+ *
+ * The cygwin mods make this behavior a little different:
+ * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
+ * Define PNG_STATIC if you are building a static library for use with cygwin,
+ *   -or- if you are building an application that you want to link to the
+ *   static library.
+ * PNG_USE_DLL is defined by default (no user action needed) unless one of
+ *   the other flags is defined.
+ */
+
+#if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
+#  define PNG_DLL
+#endif
+/* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
+ * When building a static lib, default to no GLOBAL ARRAYS, but allow
+ * command-line override
+ */
+#if defined(__CYGWIN__)
+#  if !defined(PNG_STATIC)
+#    if defined(PNG_USE_GLOBAL_ARRAYS)
+#      undef PNG_USE_GLOBAL_ARRAYS
+#    endif
+#    if !defined(PNG_USE_LOCAL_ARRAYS)
+#      define PNG_USE_LOCAL_ARRAYS
+#    endif
+#  else
+#    if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
+#      if defined(PNG_USE_GLOBAL_ARRAYS)
+#        undef PNG_USE_GLOBAL_ARRAYS
+#      endif
+#    endif
+#  endif
+#  if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
+#    define PNG_USE_LOCAL_ARRAYS
+#  endif
+#endif
+
+/* Do not use global arrays (helps with building DLL's)
+ * They are no longer used in libpng itself, since version 1.0.5c,
+ * but might be required for some pre-1.0.5c applications.
+ */
+#if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
+#  if defined(PNG_NO_GLOBAL_ARRAYS) || (defined(__GNUC__) && defined(PNG_DLL))
+#    define PNG_USE_LOCAL_ARRAYS
+#  else
+#    define PNG_USE_GLOBAL_ARRAYS
+#  endif
+#endif
+
+#if defined(__CYGWIN__)
+#  undef PNGAPI
+#  define PNGAPI __cdecl
+#  undef PNG_IMPEXP
+#  define PNG_IMPEXP
+#endif  
+
+/* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
+ * you may get warnings regarding the linkage of png_zalloc and png_zfree.
+ * Don't ignore those warnings; you must also reset the default calling
+ * convention in your compiler to match your PNGAPI, and you must build
+ * zlib and your applications the same way you build libpng.
+ */
+
+#if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
+#  ifndef PNG_NO_MODULEDEF
+#    define PNG_NO_MODULEDEF
+#  endif
+#endif
+
+#if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
+#  define PNG_IMPEXP
+#endif
+
+#if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
+    (( defined(_Windows) || defined(_WINDOWS) || \
+       defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
+
+#  ifndef PNGAPI
+#     if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
+#        define PNGAPI __cdecl
+#     else
+#        define PNGAPI _cdecl
+#     endif
+#  endif
+
+#  if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
+       0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
+#     define PNG_IMPEXP
+#  endif
+
+#  if !defined(PNG_IMPEXP)
+
+#     define PNG_EXPORT_TYPE1(type,symbol)  PNG_IMPEXP type PNGAPI symbol
+#     define PNG_EXPORT_TYPE2(type,symbol)  type PNG_IMPEXP PNGAPI symbol
+
+      /* Borland/Microsoft */
+#     if defined(_MSC_VER) || defined(__BORLANDC__)
+#        if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
+#           define PNG_EXPORT PNG_EXPORT_TYPE1
+#        else
+#           define PNG_EXPORT PNG_EXPORT_TYPE2
+#           if defined(PNG_BUILD_DLL)
+#              define PNG_IMPEXP __export
+#           else
+#              define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
+                                                 VC++ */
+#           endif                             /* Exists in Borland C++ for
+                                                 C++ classes (== huge) */
+#        endif
+#     endif
+
+#     if !defined(PNG_IMPEXP)
+#        if defined(PNG_BUILD_DLL)
+#           define PNG_IMPEXP __declspec(dllexport)
+#        else
+#           define PNG_IMPEXP __declspec(dllimport)
+#        endif
+#     endif
+#  endif  /* PNG_IMPEXP */
+#else /* !(DLL || non-cygwin WINDOWS) */
+#   if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
+#      ifndef PNGAPI
+#         define PNGAPI _System
+#      endif
+#   else
+#      if 0 /* ... other platforms, with other meanings */
+#      endif
+#   endif
+#endif
+
+#ifndef PNGAPI
+#  define PNGAPI
+#endif
+#ifndef PNG_IMPEXP
+#  define PNG_IMPEXP
+#endif
+
+#ifdef PNG_BUILDSYMS
+#  ifndef PNG_EXPORT
+#    define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
+#  endif
+#  ifdef PNG_USE_GLOBAL_ARRAYS
+#    ifndef PNG_EXPORT_VAR
+#      define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
+#    endif
+#  endif
+#endif
+
+#ifndef PNG_EXPORT
+#  define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
+#endif
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+#  ifndef PNG_EXPORT_VAR
+#    define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
+#  endif
+#endif
+
+/* User may want to use these so they are not in PNG_INTERNAL. Any library
+ * functions that are passed far data must be model independent.
+ */
+
+#ifndef PNG_ABORT
+#  define PNG_ABORT() abort()
+#endif
+
+#ifdef PNG_SETJMP_SUPPORTED
+#  define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
+#else
+#  define png_jmpbuf(png_ptr) \
+   (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
+#endif
+
+#if defined(USE_FAR_KEYWORD)  /* memory model independent fns */
+/* use this to make far-to-near assignments */
+#  define CHECK   1
+#  define NOCHECK 0
+#  define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
+#  define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
+#  define png_strcpy  _fstrcpy
+#  define png_strncpy _fstrncpy   /* Added to v 1.2.6 */
+#  define png_strlen  _fstrlen
+#  define png_memcmp  _fmemcmp    /* SJT: added */
+#  define png_memcpy  _fmemcpy
+#  define png_memset  _fmemset
+#else /* use the usual functions */
+#  define CVT_PTR(ptr)         (ptr)
+#  define CVT_PTR_NOCHECK(ptr) (ptr)
+#  define png_strcpy  strcpy
+#  define png_strncpy strncpy     /* Added to v 1.2.6 */
+#  define png_strlen  strlen
+#  define png_memcmp  memcmp      /* SJT: added */
+#  define png_memcpy  memcpy
+#  define png_memset  memset
+#endif
+/* End of memory model independent support */
+
+/* Just a little check that someone hasn't tried to define something
+ * contradictory.
+ */
+#if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
+#  undef PNG_ZBUF_SIZE
+#  define PNG_ZBUF_SIZE 65536L
+#endif
+
+#ifdef PNG_READ_SUPPORTED
+/* Prior to libpng-1.0.9, this block was in pngasmrd.h */
+#if defined(PNG_INTERNAL)
+
+/* These are the default thresholds before the MMX code kicks in; if either
+ * rowbytes or bitdepth is below the threshold, plain C code is used.  These
+ * can be overridden at runtime via the png_set_mmx_thresholds() call in
+ * libpng 1.2.0 and later.  The values below were chosen by Intel.
+ */
+
+#ifndef PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT
+#  define PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT  128  /*  >=  */
+#endif
+#ifndef PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT
+#  define PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT  9    /*  >=  */   
+#endif
+
+/* Set this in the makefile for VC++ on Pentium, not here. */
+/* Platform must be Pentium.  Makefile must assemble and load pngvcrd.c .
+ * MMX will be detected at run time and used if present.
+ */
+#ifdef PNG_USE_PNGVCRD
+#  define PNG_HAVE_ASSEMBLER_COMBINE_ROW
+#  define PNG_HAVE_ASSEMBLER_READ_INTERLACE
+#  define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW
+#endif
+
+/* Set this in the makefile for gcc/as on Pentium, not here. */
+/* Platform must be Pentium.  Makefile must assemble and load pnggccrd.c .
+ * MMX will be detected at run time and used if present.
+ */
+#ifdef PNG_USE_PNGGCCRD
+#  define PNG_HAVE_ASSEMBLER_COMBINE_ROW
+#  define PNG_HAVE_ASSEMBLER_READ_INTERLACE
+#  define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW
+#endif
+/* - see pnggccrd.c for info about what is currently enabled */
+
+#endif /* PNG_INTERNAL */
+#endif /* PNG_READ_SUPPORTED */
+
+/* Added at libpng-1.2.8 */
+#endif /* PNG_VERSION_INFO_ONLY */
+
+#endif /* PNGCONF_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Entries ./aperios/include/libxml2/CVS/Entries
--- ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+D/libxml////
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Repository ./aperios/include/libxml2/CVS/Repository
--- ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/CVS/Repository	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/include/libxml2
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Root ./aperios/include/libxml2/CVS/Root
--- ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/CVS/Root	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Tag ./aperios/include/libxml2/CVS/Tag
--- ../Tekkotsu_2.3/aperios/include/libxml2/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/CVS/Tag	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Entries ./aperios/include/libxml2/libxml/CVS/Entries
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/CVS/Entries	Wed Aug 10 11:03:22 2005
@@ -0,0 +1,47 @@
+/DOCBparser.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/HTMLparser.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/HTMLtree.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/SAX.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/SAX2.h/1.2/Wed Jun  1 05:48:00 2005//Ttekkotsu-2_4
+/c14n.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/catalog.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/chvalid.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/debugXML.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/dict.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/encoding.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/entities.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/globals.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/hash.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/list.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/nanoftp.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/nanohttp.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/parser.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/parserInternals.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/pattern.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/relaxng.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/schemasInternals.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/threads.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/tree.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/uri.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/valid.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xinclude.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xlink.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlIO.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlautomata.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlerror.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlexports.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlmemory.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlmodule.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlreader.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlregexp.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlsave.h/1.2/Wed Jun  1 05:48:01 2005//Ttekkotsu-2_4
+/xmlschemas.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xmlschemastypes.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xmlstring.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xmlunicode.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xmlversion.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xmlwriter.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xpath.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xpathInternals.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+/xpointer.h/1.2/Wed Jun  1 05:48:02 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Repository ./aperios/include/libxml2/libxml/CVS/Repository
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/CVS/Repository	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/include/libxml2/libxml
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Root ./aperios/include/libxml2/libxml/CVS/Root
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/CVS/Root	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Tag ./aperios/include/libxml2/libxml/CVS/Tag
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/CVS/Tag	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/DOCBparser.h ./aperios/include/libxml2/libxml/DOCBparser.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/DOCBparser.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/DOCBparser.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,96 @@
+/*
+ * Summary: old DocBook SGML parser
+ * Description: interface for a DocBook SGML non-verifying parser
+ * This code is DEPRECATED, and should not be used anymore.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __DOCB_PARSER_H__
+#define __DOCB_PARSER_H__
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_DOCB_ENABLED
+
+#include <libxml/parser.h>
+#include <libxml/parserInternals.h>
+
+#ifndef IN_LIBXML
+#ifdef __GNUC__
+#warning "The DOCBparser module has been deprecated in libxml2-2.6.0"
+#endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Most of the back-end structures from XML and SGML are shared.
+ */
+typedef xmlParserCtxt docbParserCtxt;
+typedef xmlParserCtxtPtr docbParserCtxtPtr;
+typedef xmlSAXHandler docbSAXHandler;
+typedef xmlSAXHandlerPtr docbSAXHandlerPtr;
+typedef xmlParserInput docbParserInput;
+typedef xmlParserInputPtr docbParserInputPtr;
+typedef xmlDocPtr docbDocPtr;
+
+/*
+ * There is only few public functions.
+ */
+XMLPUBFUN int XMLCALL
+		     docbEncodeEntities(unsigned char *out,
+                                        int *outlen,
+                                        const unsigned char *in,
+                                        int *inlen, int quoteChar);
+
+XMLPUBFUN docbDocPtr XMLCALL             
+		     docbSAXParseDoc   (xmlChar *cur,
+                                        const char *encoding,
+                                        docbSAXHandlerPtr sax,
+                                        void *userData);
+XMLPUBFUN docbDocPtr XMLCALL             
+		     docbParseDoc      (xmlChar *cur,
+                                        const char *encoding);
+XMLPUBFUN docbDocPtr XMLCALL             
+		     docbSAXParseFile  (const char *filename,
+                                        const char *encoding,
+                                        docbSAXHandlerPtr sax,
+                                        void *userData);
+XMLPUBFUN docbDocPtr XMLCALL             
+		     docbParseFile     (const char *filename,
+                                        const char *encoding);
+
+/**
+ * Interfaces for the Push mode.
+ */
+XMLPUBFUN void XMLCALL                  
+		     docbFreeParserCtxt      (docbParserCtxtPtr ctxt);
+XMLPUBFUN docbParserCtxtPtr XMLCALL     
+		     docbCreatePushParserCtxt(docbSAXHandlerPtr sax,
+                                              void *user_data,
+                                              const char *chunk,
+                                              int size,
+                                              const char *filename,
+                                              xmlCharEncoding enc);
+XMLPUBFUN int XMLCALL                   
+		     docbParseChunk          (docbParserCtxtPtr ctxt,
+                                              const char *chunk,
+                                              int size,
+                                              int terminate);
+XMLPUBFUN docbParserCtxtPtr XMLCALL       
+		     docbCreateFileParserCtxt(const char *filename,
+                                              const char *encoding);
+XMLPUBFUN int XMLCALL                   
+		     docbParseDocument       (docbParserCtxtPtr ctxt);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_DOCB_ENABLED */
+
+#endif /* __DOCB_PARSER_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/HTMLparser.h ./aperios/include/libxml2/libxml/HTMLparser.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/HTMLparser.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/HTMLparser.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,298 @@
+/*
+ * Summary: interface for an HTML 4.0 non-verifying parser
+ * Description: this module implements an HTML 4.0 non-verifying parser
+ *              with API compatible with the XML parser ones. It should
+ *              be able to parse "real world" HTML, even if severely
+ *              broken from a specification point of view.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __HTML_PARSER_H__
+#define __HTML_PARSER_H__
+#include <libxml/xmlversion.h>
+#include <libxml/parser.h>
+
+#ifdef LIBXML_HTML_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Most of the back-end structures from XML and HTML are shared.
+ */
+typedef xmlParserCtxt htmlParserCtxt;
+typedef xmlParserCtxtPtr htmlParserCtxtPtr;
+typedef xmlParserNodeInfo htmlParserNodeInfo;
+typedef xmlSAXHandler htmlSAXHandler;
+typedef xmlSAXHandlerPtr htmlSAXHandlerPtr;
+typedef xmlParserInput htmlParserInput;
+typedef xmlParserInputPtr htmlParserInputPtr;
+typedef xmlDocPtr htmlDocPtr;
+typedef xmlNodePtr htmlNodePtr;
+
+/*
+ * Internal description of an HTML element, representing HTML 4.01
+ * and XHTML 1.0 (which share the same structure).
+ */
+typedef struct _htmlElemDesc htmlElemDesc;
+typedef htmlElemDesc *htmlElemDescPtr;
+struct _htmlElemDesc {
+    const char *name;	/* The tag name */
+    char startTag;      /* Whether the start tag can be implied */
+    char endTag;        /* Whether the end tag can be implied */
+    char saveEndTag;    /* Whether the end tag should be saved */
+    char empty;         /* Is this an empty element ? */
+    char depr;          /* Is this a deprecated element ? */
+    char dtd;           /* 1: only in Loose DTD, 2: only Frameset one */
+    char isinline;      /* is this a block 0 or inline 1 element */
+    const char *desc;   /* the description */
+
+/* NRK Jan.2003
+ * New fields encapsulating HTML structure
+ *
+ * Bugs:
+ *	This is a very limited representation.  It fails to tell us when
+ *	an element *requires* subelements (we only have whether they're
+ *	allowed or not), and it doesn't tell us where CDATA and PCDATA
+ *	are allowed.  Some element relationships are not fully represented:
+ *	these are flagged with the word MODIFIER
+ */
+    const char** subelts;		/* allowed sub-elements of this element */
+    const char* defaultsubelt;	/* subelement for suggested auto-repair
+					   if necessary or NULL */
+    const char** attrs_opt;		/* Optional Attributes */
+    const char** attrs_depr;		/* Additional deprecated attributes */
+    const char** attrs_req;		/* Required attributes */
+};
+
+/*
+ * Internal description of an HTML entity.
+ */
+typedef struct _htmlEntityDesc htmlEntityDesc;
+typedef htmlEntityDesc *htmlEntityDescPtr;
+struct _htmlEntityDesc {
+    unsigned int value;	/* the UNICODE value for the character */
+    const char *name;	/* The entity name */
+    const char *desc;   /* the description */
+};
+
+/*
+ * There is only few public functions.
+ */
+XMLPUBFUN const htmlElemDesc * XMLCALL 	
+			htmlTagLookup	(const xmlChar *tag);
+XMLPUBFUN const htmlEntityDesc * XMLCALL 	
+			htmlEntityLookup(const xmlChar *name);
+XMLPUBFUN const htmlEntityDesc * XMLCALL 	
+			htmlEntityValueLookup(unsigned int value);
+
+XMLPUBFUN int XMLCALL			
+			htmlIsAutoClosed(htmlDocPtr doc,
+					 htmlNodePtr elem);
+XMLPUBFUN int XMLCALL			
+			htmlAutoCloseTag(htmlDocPtr doc,
+					 const xmlChar *name,
+					 htmlNodePtr elem);
+XMLPUBFUN const htmlEntityDesc * XMLCALL	
+			htmlParseEntityRef(htmlParserCtxtPtr ctxt,
+					 const xmlChar **str);
+XMLPUBFUN int XMLCALL			
+			htmlParseCharRef(htmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			htmlParseElement(htmlParserCtxtPtr ctxt);
+
+XMLPUBFUN htmlParserCtxtPtr XMLCALL	
+			htmlCreateMemoryParserCtxt(const char *buffer,
+						   int size);
+
+XMLPUBFUN int XMLCALL			
+			htmlParseDocument(htmlParserCtxtPtr ctxt);
+XMLPUBFUN htmlDocPtr XMLCALL		
+			htmlSAXParseDoc	(xmlChar *cur,
+					 const char *encoding,
+					 htmlSAXHandlerPtr sax,
+					 void *userData);
+XMLPUBFUN htmlDocPtr XMLCALL		
+			htmlParseDoc	(xmlChar *cur,
+					 const char *encoding);
+XMLPUBFUN htmlDocPtr XMLCALL		
+			htmlSAXParseFile(const char *filename,
+					 const char *encoding,
+					 htmlSAXHandlerPtr sax,
+					 void *userData);
+XMLPUBFUN htmlDocPtr XMLCALL		
+			htmlParseFile	(const char *filename,
+					 const char *encoding);
+XMLPUBFUN int XMLCALL			
+			UTF8ToHtml	(unsigned char *out,
+					 int *outlen,
+					 const unsigned char *in,
+					 int *inlen);
+XMLPUBFUN int XMLCALL			
+			htmlEncodeEntities(unsigned char *out,
+					 int *outlen,
+					 const unsigned char *in,
+					 int *inlen, int quoteChar);
+XMLPUBFUN int XMLCALL			
+			htmlIsScriptAttribute(const xmlChar *name);
+XMLPUBFUN int XMLCALL			
+			htmlHandleOmittedElem(int val);
+
+#ifdef LIBXML_PUSH_ENABLED
+/**
+ * Interfaces for the Push mode.
+ */
+XMLPUBFUN htmlParserCtxtPtr XMLCALL	
+			htmlCreatePushParserCtxt(htmlSAXHandlerPtr sax,
+						 void *user_data,
+						 const char *chunk,
+						 int size,
+						 const char *filename,
+						 xmlCharEncoding enc);
+XMLPUBFUN int XMLCALL			
+			htmlParseChunk		(htmlParserCtxtPtr ctxt,
+						 const char *chunk,
+						 int size,
+						 int terminate);
+#endif /* LIBXML_PUSH_ENABLED */
+
+XMLPUBFUN void XMLCALL			
+			htmlFreeParserCtxt	(htmlParserCtxtPtr ctxt);
+
+/*
+ * New set of simpler/more flexible APIs
+ */
+/**
+ * xmlParserOption:
+ *
+ * This is the set of XML parser options that can be passed down
+ * to the xmlReadDoc() and similar calls.
+ */
+typedef enum {
+    HTML_PARSE_NOERROR	= 1<<5,	/* suppress error reports */
+    HTML_PARSE_NOWARNING= 1<<6,	/* suppress warning reports */
+    HTML_PARSE_PEDANTIC	= 1<<7,	/* pedantic error reporting */
+    HTML_PARSE_NOBLANKS	= 1<<8,	/* remove blank nodes */
+    HTML_PARSE_NONET	= 1<<11 /* Forbid network access */
+} htmlParserOption;
+
+XMLPUBFUN void XMLCALL
+		htmlCtxtReset		(htmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL
+		htmlCtxtUseOptions	(htmlParserCtxtPtr ctxt,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlReadDoc		(const xmlChar *cur,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlReadFile		(const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlReadMemory		(const char *buffer,
+					 int size,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlReadFd		(int fd,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlReadIO		(xmlInputReadCallback ioread,
+					 xmlInputCloseCallback ioclose,
+					 void *ioctx,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlCtxtReadDoc		(xmlParserCtxtPtr ctxt,
+					 const xmlChar *cur,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlCtxtReadFile		(xmlParserCtxtPtr ctxt,
+					 const char *filename,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlCtxtReadMemory		(xmlParserCtxtPtr ctxt,
+					 const char *buffer,
+					 int size,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlCtxtReadFd		(xmlParserCtxtPtr ctxt,
+					 int fd,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlCtxtReadIO		(xmlParserCtxtPtr ctxt,
+					 xmlInputReadCallback ioread,
+					 xmlInputCloseCallback ioclose,
+					 void *ioctx,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+
+/* NRK/Jan2003: further knowledge of HTML structure
+ */
+typedef enum {
+  HTML_NA = 0 ,		/* something we don't check at all */
+  HTML_INVALID = 0x1 ,
+  HTML_DEPRECATED = 0x2 ,
+  HTML_VALID = 0x4 ,
+  HTML_REQUIRED = 0xc /* VALID bit set so ( & HTML_VALID ) is TRUE */
+} htmlStatus ;
+
+/* Using htmlElemDesc rather than name here, to emphasise the fact
+   that otherwise there's a lookup overhead
+*/
+XMLPUBFUN htmlStatus XMLCALL htmlAttrAllowed(const htmlElemDesc*, const xmlChar*, int) ;
+XMLPUBFUN int XMLCALL htmlElementAllowedHere(const htmlElemDesc*, const xmlChar*) ;
+XMLPUBFUN htmlStatus XMLCALL htmlElementStatusHere(const htmlElemDesc*, const htmlElemDesc*) ;
+XMLPUBFUN htmlStatus XMLCALL htmlNodeStatus(const htmlNodePtr, int) ;
+/**
+ * htmlDefaultSubelement:
+ * @elt: HTML element
+ *
+ * Returns the default subelement for this element
+ */
+#define htmlDefaultSubelement(elt) elt->defaultsubelt
+/**
+ * htmlElementAllowedHereDesc:
+ * @parent: HTML parent element
+ * @elt: HTML element
+ *
+ * Checks whether an HTML element description may be a
+ * direct child of the specified element.
+ *
+ * Returns 1 if allowed; 0 otherwise.
+ */
+#define htmlElementAllowedHereDesc(parent,elt) \
+	htmlElementAllowedHere((parent), (elt)->name)
+/**
+ * htmlRequiredAttrs:
+ * @elt: HTML element
+ *
+ * Returns the attributes required for the specified element.
+ */
+#define htmlRequiredAttrs(elt) (elt)->attrs_req
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_HTML_ENABLED */
+#endif /* __HTML_PARSER_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/HTMLtree.h ./aperios/include/libxml2/libxml/HTMLtree.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/HTMLtree.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/HTMLtree.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,142 @@
+/*
+ * Summary: specific APIs to process HTML tree, especially serialization
+ * Description: this module implements a few function needed to process
+ *              tree in an HTML specific way.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __HTML_TREE_H__
+#define __HTML_TREE_H__
+
+#include <stdio.h>
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+#include <libxml/HTMLparser.h>
+
+#ifdef LIBXML_HTML_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * HTML_TEXT_NODE:
+ *
+ * Macro. A text node in a HTML document is really implemented
+ * the same way as a text node in an XML document.
+ */
+#define HTML_TEXT_NODE		XML_TEXT_NODE
+/**
+ * HTML_ENTITY_REF_NODE:
+ *
+ * Macro. An entity reference in a HTML document is really implemented
+ * the same way as an entity reference in an XML document.
+ */
+#define HTML_ENTITY_REF_NODE	XML_ENTITY_REF_NODE
+/**
+ * HTML_COMMENT_NODE:
+ *
+ * Macro. A comment in a HTML document is really implemented
+ * the same way as a comment in an XML document.
+ */
+#define HTML_COMMENT_NODE	XML_COMMENT_NODE
+/**
+ * HTML_PRESERVE_NODE:
+ *
+ * Macro. A preserved node in a HTML document is really implemented
+ * the same way as a CDATA section in an XML document.
+ */
+#define HTML_PRESERVE_NODE	XML_CDATA_SECTION_NODE
+/**
+ * HTML_PI_NODE:
+ *
+ * Macro. A processing instruction in a HTML document is really implemented
+ * the same way as a processing instruction in an XML document.
+ */
+#define HTML_PI_NODE		XML_PI_NODE
+
+XMLPUBFUN htmlDocPtr XMLCALL
+		htmlNewDoc		(const xmlChar *URI,
+					 const xmlChar *ExternalID);
+XMLPUBFUN htmlDocPtr XMLCALL	
+		htmlNewDocNoDtD		(const xmlChar *URI,
+					 const xmlChar *ExternalID);
+XMLPUBFUN const xmlChar * XMLCALL	
+		htmlGetMetaEncoding	(htmlDocPtr doc);
+XMLPUBFUN int XMLCALL		
+		htmlSetMetaEncoding	(htmlDocPtr doc,
+					 const xmlChar *encoding);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL	    
+		htmlDocDumpMemory	(xmlDocPtr cur,
+					 xmlChar **mem,
+					 int *size);
+XMLPUBFUN int XMLCALL		
+		htmlDocDump		(FILE *f,
+					 xmlDocPtr cur);
+XMLPUBFUN int XMLCALL		
+		htmlSaveFile		(const char *filename,
+					 xmlDocPtr cur);
+XMLPUBFUN int XMLCALL		
+		htmlNodeDump		(xmlBufferPtr buf,
+					 xmlDocPtr doc,
+					 xmlNodePtr cur);
+XMLPUBFUN void XMLCALL		
+		htmlNodeDumpFile	(FILE *out,
+					 xmlDocPtr doc,
+					 xmlNodePtr cur);
+XMLPUBFUN int XMLCALL		
+		htmlNodeDumpFileFormat	(FILE *out,
+					 xmlDocPtr doc,
+					 xmlNodePtr cur,
+					 const char *encoding,
+					 int format);
+XMLPUBFUN int XMLCALL		
+		htmlSaveFileEnc		(const char *filename,
+					 xmlDocPtr cur,
+					 const char *encoding);
+XMLPUBFUN int XMLCALL		
+		htmlSaveFileFormat	(const char *filename,
+					 xmlDocPtr cur,
+					 const char *encoding,
+					 int format);
+
+XMLPUBFUN void XMLCALL		
+		htmlNodeDumpFormatOutput(xmlOutputBufferPtr buf,
+					 xmlDocPtr doc,
+					 xmlNodePtr cur,
+					 const char *encoding,
+					 int format);
+XMLPUBFUN void XMLCALL		
+		htmlDocContentDumpOutput(xmlOutputBufferPtr buf,
+					 xmlDocPtr cur,
+					 const char *encoding);
+XMLPUBFUN void XMLCALL		
+		htmlDocContentDumpFormatOutput(xmlOutputBufferPtr buf,
+					 xmlDocPtr cur,
+					 const char *encoding,
+					 int format);
+XMLPUBFUN void XMLCALL 
+		htmlNodeDumpOutput	(xmlOutputBufferPtr buf, 
+					 xmlDocPtr doc,
+					 xmlNodePtr cur, 
+					 const char *encoding);
+
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+XMLPUBFUN int XMLCALL		
+		htmlIsBooleanAttr	(const xmlChar *name);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_HTML_ENABLED */
+
+#endif /* __HTML_TREE_H__ */
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/SAX.h ./aperios/include/libxml2/libxml/SAX.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/SAX.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/SAX.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,173 @@
+/*
+ * Summary: Old SAX version 1 handler, deprecated
+ * Description: DEPRECATED set of SAX version 1 interfaces used to
+ *              build the DOM tree.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+
+#ifndef __XML_SAX_H__
+#define __XML_SAX_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <libxml/xmlversion.h>
+#include <libxml/parser.h>
+#include <libxml/xlink.h>
+
+#ifdef LIBXML_LEGACY_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+XMLPUBFUN const xmlChar * XMLCALL
+		getPublicId			(void *ctx);
+XMLPUBFUN const xmlChar * XMLCALL	
+		getSystemId			(void *ctx);
+XMLPUBFUN void XMLCALL		
+		setDocumentLocator		(void *ctx,
+						 xmlSAXLocatorPtr loc);
+    
+XMLPUBFUN int XMLCALL		
+		getLineNumber			(void *ctx);
+XMLPUBFUN int XMLCALL		
+		getColumnNumber			(void *ctx);
+
+XMLPUBFUN int XMLCALL		
+		isStandalone			(void *ctx);
+XMLPUBFUN int XMLCALL		
+		hasInternalSubset		(void *ctx);
+XMLPUBFUN int XMLCALL		
+		hasExternalSubset		(void *ctx);
+
+XMLPUBFUN void XMLCALL		
+		internalSubset			(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID);
+XMLPUBFUN void XMLCALL		
+		externalSubset			(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID);
+XMLPUBFUN xmlEntityPtr XMLCALL	
+		getEntity			(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN xmlEntityPtr XMLCALL	
+		getParameterEntity		(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN xmlParserInputPtr XMLCALL 
+		resolveEntity			(void *ctx,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId);
+
+XMLPUBFUN void XMLCALL		
+		entityDecl			(void *ctx,
+						 const xmlChar *name,
+						 int type,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId,
+						 xmlChar *content);
+XMLPUBFUN void XMLCALL		
+		attributeDecl			(void *ctx,
+						 const xmlChar *elem,
+						 const xmlChar *fullname,
+						 int type,
+						 int def,
+						 const xmlChar *defaultValue,
+						 xmlEnumerationPtr tree);
+XMLPUBFUN void XMLCALL		
+		elementDecl			(void *ctx,
+						 const xmlChar *name,
+						 int type,
+						 xmlElementContentPtr content);
+XMLPUBFUN void XMLCALL		
+		notationDecl			(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId);
+XMLPUBFUN void XMLCALL		
+		unparsedEntityDecl		(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId,
+						 const xmlChar *notationName);
+
+XMLPUBFUN void XMLCALL		
+		startDocument			(void *ctx);
+XMLPUBFUN void XMLCALL		
+		endDocument			(void *ctx);
+XMLPUBFUN void XMLCALL		
+		attribute			(void *ctx,
+						 const xmlChar *fullname,
+						 const xmlChar *value);
+XMLPUBFUN void XMLCALL		
+		startElement			(void *ctx,
+						 const xmlChar *fullname,
+						 const xmlChar **atts);
+XMLPUBFUN void XMLCALL		
+		endElement			(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN void XMLCALL		
+		reference			(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN void XMLCALL		
+		characters			(void *ctx,
+						 const xmlChar *ch,
+						 int len);
+XMLPUBFUN void XMLCALL		
+		ignorableWhitespace		(void *ctx,
+						 const xmlChar *ch,
+						 int len);
+XMLPUBFUN void XMLCALL		
+		processingInstruction		(void *ctx,
+						 const xmlChar *target,
+						 const xmlChar *data);
+XMLPUBFUN void XMLCALL		
+		globalNamespace			(void *ctx,
+						 const xmlChar *href,
+						 const xmlChar *prefix);
+XMLPUBFUN void XMLCALL		
+		setNamespace			(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN xmlNsPtr XMLCALL	
+		getNamespace			(void *ctx);
+XMLPUBFUN int XMLCALL		
+		checkNamespace			(void *ctx,
+						 xmlChar *nameSpace);
+XMLPUBFUN void XMLCALL		
+		namespaceDecl			(void *ctx,
+						 const xmlChar *href,
+						 const xmlChar *prefix);
+XMLPUBFUN void XMLCALL		
+		comment				(void *ctx,
+						 const xmlChar *value);
+XMLPUBFUN void XMLCALL		
+		cdataBlock			(void *ctx,
+						 const xmlChar *value,
+						 int len);
+
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN void XMLCALL		
+		initxmlDefaultSAXHandler	(xmlSAXHandlerV1 *hdlr,
+						 int warning);
+#ifdef LIBXML_HTML_ENABLED
+XMLPUBFUN void XMLCALL		
+		inithtmlDefaultSAXHandler	(xmlSAXHandlerV1 *hdlr);
+#endif
+#ifdef LIBXML_DOCB_ENABLED
+XMLPUBFUN void XMLCALL		
+		initdocbDefaultSAXHandler	(xmlSAXHandlerV1 *hdlr);
+#endif
+#endif /* LIBXML_SAX1_ENABLED */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_LEGACY_ENABLED */
+
+#endif /* __XML_SAX_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/SAX2.h ./aperios/include/libxml2/libxml/SAX2.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/SAX2.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/SAX2.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,176 @@
+/*
+ * Summary: SAX2 parser interface used to build the DOM tree
+ * Description: those are the default SAX2 interfaces used by
+ *              the library when building DOM tree.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+
+#ifndef __XML_SAX2_H__
+#define __XML_SAX2_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <libxml/xmlversion.h>
+#include <libxml/parser.h>
+#include <libxml/xlink.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+XMLPUBFUN const xmlChar * XMLCALL
+		xmlSAX2GetPublicId		(void *ctx);
+XMLPUBFUN const xmlChar * XMLCALL	
+		xmlSAX2GetSystemId		(void *ctx);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2SetDocumentLocator	(void *ctx,
+						 xmlSAXLocatorPtr loc);
+    
+XMLPUBFUN int XMLCALL		
+		xmlSAX2GetLineNumber		(void *ctx);
+XMLPUBFUN int XMLCALL		
+		xmlSAX2GetColumnNumber		(void *ctx);
+
+XMLPUBFUN int XMLCALL		
+		xmlSAX2IsStandalone		(void *ctx);
+XMLPUBFUN int XMLCALL		
+		xmlSAX2HasInternalSubset	(void *ctx);
+XMLPUBFUN int XMLCALL		
+		xmlSAX2HasExternalSubset	(void *ctx);
+
+XMLPUBFUN void XMLCALL		
+		xmlSAX2InternalSubset		(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2ExternalSubset		(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID);
+XMLPUBFUN xmlEntityPtr XMLCALL	
+		xmlSAX2GetEntity		(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN xmlEntityPtr XMLCALL	
+		xmlSAX2GetParameterEntity	(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN xmlParserInputPtr XMLCALL 
+		xmlSAX2ResolveEntity		(void *ctx,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId);
+
+XMLPUBFUN void XMLCALL		
+		xmlSAX2EntityDecl		(void *ctx,
+						 const xmlChar *name,
+						 int type,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId,
+						 xmlChar *content);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2AttributeDecl		(void *ctx,
+						 const xmlChar *elem,
+						 const xmlChar *fullname,
+						 int type,
+						 int def,
+						 const xmlChar *defaultValue,
+						 xmlEnumerationPtr tree);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2ElementDecl		(void *ctx,
+						 const xmlChar *name,
+						 int type,
+						 xmlElementContentPtr content);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2NotationDecl		(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2UnparsedEntityDecl	(void *ctx,
+						 const xmlChar *name,
+						 const xmlChar *publicId,
+						 const xmlChar *systemId,
+						 const xmlChar *notationName);
+
+XMLPUBFUN void XMLCALL		
+		xmlSAX2StartDocument		(void *ctx);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2EndDocument		(void *ctx);
+#if defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENABLED)
+XMLPUBFUN void XMLCALL		
+		xmlSAX2StartElement		(void *ctx,
+						 const xmlChar *fullname,
+						 const xmlChar **atts);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2EndElement		(void *ctx,
+						 const xmlChar *name);
+#endif /* LIBXML_SAX1_ENABLED or LIBXML_HTML_ENABLED */
+XMLPUBFUN void XMLCALL
+		xmlSAX2StartElementNs		(void *ctx,
+						 const xmlChar *localname,
+						 const xmlChar *prefix,
+						 const xmlChar *URI,
+						 int nb_namespaces,
+						 const xmlChar **namespaces,
+						 int nb_attributes,
+						 int nb_defaulted,
+						 const xmlChar **attributes);
+XMLPUBFUN void XMLCALL
+		xmlSAX2EndElementNs		(void *ctx,
+						 const xmlChar *localname,
+						 const xmlChar *prefix,
+						 const xmlChar *URI);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2Reference		(void *ctx,
+						 const xmlChar *name);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2Characters		(void *ctx,
+						 const xmlChar *ch,
+						 int len);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2IgnorableWhitespace	(void *ctx,
+						 const xmlChar *ch,
+						 int len);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2ProcessingInstruction	(void *ctx,
+						 const xmlChar *target,
+						 const xmlChar *data);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2Comment			(void *ctx,
+						 const xmlChar *value);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2CDataBlock		(void *ctx,
+						 const xmlChar *value,
+						 int len);
+
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN int XMLCALL
+		xmlSAXDefaultVersion		(int version);
+#endif /* LIBXML_SAX1_ENABLED */
+
+XMLPUBFUN int XMLCALL
+		xmlSAXVersion			(xmlSAXHandler *hdlr,
+						 int version);
+XMLPUBFUN void XMLCALL		
+		xmlSAX2InitDefaultSAXHandler    (xmlSAXHandler *hdlr,
+						 int warning);
+#ifdef LIBXML_HTML_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlSAX2InitHtmlDefaultSAXHandler(xmlSAXHandler *hdlr);
+XMLPUBFUN void XMLCALL		
+		htmlDefaultSAXHandlerInit	(void);
+#endif
+#ifdef LIBXML_DOCB_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlSAX2InitDocbDefaultSAXHandler(xmlSAXHandler *hdlr);
+XMLPUBFUN void XMLCALL		
+		docbDefaultSAXHandlerInit	(void);
+#endif
+XMLPUBFUN void XMLCALL		
+		xmlDefaultSAXHandlerInit	(void);
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_SAX2_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/c14n.h ./aperios/include/libxml2/libxml/c14n.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/c14n.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/c14n.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,105 @@
+/*
+ * Summary: Provide Canonical XML and Exclusive XML Canonicalization
+ * Description: the c14n modules provides a
+ *
+ * "Canonical XML" implementation 
+ * http://www.w3.org/TR/xml-c14n
+ * 
+ * and an
+ *
+ * "Exclusive XML Canonicalization" implementation
+ * http://www.w3.org/TR/xml-exc-c14n
+ 
+ * Copy: See Copyright for the status of this software.
+ * 
+ * Author: Aleksey Sanin <aleksey@aleksey.com>
+ */
+#ifndef __XML_C14N_H__
+#define __XML_C14N_H__    
+#ifdef LIBXML_C14N_ENABLED
+#ifdef LIBXML_OUTPUT_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */ 
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+#include <libxml/xpath.h> 
+
+/*
+ * XML Canonicazation
+ * http://www.w3.org/TR/xml-c14n
+ *
+ * Exclusive XML Canonicazation
+ * http://www.w3.org/TR/xml-exc-c14n
+ *
+ * Canonical form of an XML document could be created if and only if
+ *  a) default attributes (if any) are added to all nodes
+ *  b) all character and parsed entity references are resolved
+ * In order to achive this in libxml2 the document MUST be loaded with 
+ * following global setings:
+ *    
+ *    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
+ *    xmlSubstituteEntitiesDefault(1);
+ *
+ * or corresponding parser context setting:
+ *    xmlParserCtxtPtr ctxt;
+ *    
+ *    ... 
+ *    ctxt->loadsubset = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
+ *    ctxt->replaceEntities = 1;
+ *    ...
+ */
+
+
+XMLPUBFUN int XMLCALL 		
+		xmlC14NDocSaveTo	(xmlDocPtr doc,
+					 xmlNodeSetPtr nodes,
+					 int exclusive,
+					 xmlChar **inclusive_ns_prefixes,
+					 int with_comments, 
+					 xmlOutputBufferPtr buf);
+
+XMLPUBFUN int XMLCALL
+		xmlC14NDocDumpMemory	(xmlDocPtr doc,
+					 xmlNodeSetPtr nodes,
+					 int exclusive,
+					 xmlChar **inclusive_ns_prefixes,
+					 int with_comments, 
+					 xmlChar **doc_txt_ptr);
+
+XMLPUBFUN int XMLCALL
+		xmlC14NDocSave		(xmlDocPtr doc,
+					 xmlNodeSetPtr nodes,
+					 int exclusive,
+					 xmlChar **inclusive_ns_prefixes,
+					 int with_comments, 
+					 const char* filename,
+					 int compression);
+
+
+/**
+ * This is the core C14N function
+ */
+typedef int (*xmlC14NIsVisibleCallback)	(void* user_data, 
+					 xmlNodePtr node,
+					 xmlNodePtr parent);
+
+XMLPUBFUN int XMLCALL
+		xmlC14NExecute		(xmlDocPtr doc,
+					 xmlC14NIsVisibleCallback is_visible_callback,
+					 void* user_data,				 
+					 int exclusive,
+					 xmlChar **inclusive_ns_prefixes,
+					 int with_comments, 
+					 xmlOutputBufferPtr buf);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* LIBXML_OUTPUT_ENABLED */
+#endif /* LIBXML_C14N_ENABLED */
+#endif /* __XML_C14N_H__ */
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/catalog.h ./aperios/include/libxml2/libxml/catalog.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/catalog.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/catalog.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,182 @@
+/**
+ * Summary: interfaces to the Catalog handling system
+ * Description: the catalog module implements the support for
+ * XML Catalogs and SGML catalogs
+ *
+ * SGML Open Technical Resolution TR9401:1997.
+ * http://www.jclark.com/sp/catalog.htm
+ *
+ * XML Catalogs Working Draft 06 August 2001
+ * http://www.oasis-open.org/committees/entity/spec-2001-08-06.html
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_CATALOG_H__
+#define __XML_CATALOG_H__
+
+#include <stdio.h>
+
+#include <libxml/xmlversion.h>
+#include <libxml/xmlstring.h>
+#include <libxml/tree.h>
+
+#ifdef LIBXML_CATALOG_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * XML_CATALOGS_NAMESPACE:
+ *
+ * The namespace for the XML Catalogs elements.
+ */
+#define XML_CATALOGS_NAMESPACE					\
+    (const xmlChar *) "urn:oasis:names:tc:entity:xmlns:xml:catalog"
+/**
+ * XML_CATALOG_PI:
+ *
+ * The specific XML Catalog Processing Instuction name.
+ */
+#define XML_CATALOG_PI						\
+    (const xmlChar *) "oasis-xml-catalog"
+
+/*
+ * The API is voluntarily limited to general cataloging.
+ */
+typedef enum {
+    XML_CATA_PREFER_NONE = 0,
+    XML_CATA_PREFER_PUBLIC = 1,
+    XML_CATA_PREFER_SYSTEM
+} xmlCatalogPrefer;
+
+typedef enum {
+    XML_CATA_ALLOW_NONE = 0,
+    XML_CATA_ALLOW_GLOBAL = 1,
+    XML_CATA_ALLOW_DOCUMENT = 2,
+    XML_CATA_ALLOW_ALL = 3
+} xmlCatalogAllow;
+
+typedef struct _xmlCatalog xmlCatalog;
+typedef xmlCatalog *xmlCatalogPtr;
+
+/*
+ * Operations on a given catalog.
+ */
+XMLPUBFUN xmlCatalogPtr XMLCALL
+		xmlNewCatalog		(int sgml);
+XMLPUBFUN xmlCatalogPtr XMLCALL	
+		xmlLoadACatalog		(const char *filename);
+XMLPUBFUN xmlCatalogPtr XMLCALL	
+		xmlLoadSGMLSuperCatalog	(const char *filename);
+XMLPUBFUN int XMLCALL		
+		xmlConvertSGMLCatalog	(xmlCatalogPtr catal);
+XMLPUBFUN int XMLCALL		
+		xmlACatalogAdd		(xmlCatalogPtr catal,
+					 const xmlChar *type,
+					 const xmlChar *orig,
+					 const xmlChar *replace);
+XMLPUBFUN int XMLCALL		
+		xmlACatalogRemove	(xmlCatalogPtr catal,
+					 const xmlChar *value);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlACatalogResolve	(xmlCatalogPtr catal,
+					 const xmlChar *pubID,
+	                                 const xmlChar *sysID);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlACatalogResolveSystem(xmlCatalogPtr catal,
+					 const xmlChar *sysID);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlACatalogResolvePublic(xmlCatalogPtr catal,
+					 const xmlChar *pubID);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlACatalogResolveURI	(xmlCatalogPtr catal,
+					 const xmlChar *URI);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlACatalogDump		(xmlCatalogPtr catal,
+					 FILE *out);
+#endif /* LIBXML_OUTPUT_ENABLED */
+XMLPUBFUN void XMLCALL		
+		xmlFreeCatalog		(xmlCatalogPtr catal);
+XMLPUBFUN int XMLCALL		
+		xmlCatalogIsEmpty	(xmlCatalogPtr catal);
+
+/*
+ * Global operations.
+ */
+XMLPUBFUN void XMLCALL		
+		xmlInitializeCatalog	(void);
+XMLPUBFUN int XMLCALL		
+		xmlLoadCatalog		(const char *filename);
+XMLPUBFUN void XMLCALL		
+		xmlLoadCatalogs		(const char *paths);
+XMLPUBFUN void XMLCALL		
+		xmlCatalogCleanup	(void);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlCatalogDump		(FILE *out);
+#endif /* LIBXML_OUTPUT_ENABLED */
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlCatalogResolve	(const xmlChar *pubID,
+	                                 const xmlChar *sysID);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlCatalogResolveSystem	(const xmlChar *sysID);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlCatalogResolvePublic	(const xmlChar *pubID);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlCatalogResolveURI	(const xmlChar *URI);
+XMLPUBFUN int XMLCALL		
+		xmlCatalogAdd		(const xmlChar *type,
+					 const xmlChar *orig,
+					 const xmlChar *replace);
+XMLPUBFUN int XMLCALL		
+		xmlCatalogRemove	(const xmlChar *value);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlParseCatalogFile	(const char *filename);
+XMLPUBFUN int XMLCALL		
+		xmlCatalogConvert	(void);
+
+/*
+ * Strictly minimal interfaces for per-document catalogs used
+ * by the parser.
+ */
+XMLPUBFUN void XMLCALL		
+		xmlCatalogFreeLocal	(void *catalogs);
+XMLPUBFUN void * XMLCALL		
+		xmlCatalogAddLocal	(void *catalogs,
+					 const xmlChar *URL);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlCatalogLocalResolve	(void *catalogs,
+					 const xmlChar *pubID,
+	                                 const xmlChar *sysID);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlCatalogLocalResolveURI(void *catalogs,
+					 const xmlChar *URI);
+/*
+ * Preference settings.
+ */
+XMLPUBFUN int XMLCALL		
+		xmlCatalogSetDebug	(int level);
+XMLPUBFUN xmlCatalogPrefer XMLCALL 
+		xmlCatalogSetDefaultPrefer(xmlCatalogPrefer prefer);
+XMLPUBFUN void XMLCALL		
+		xmlCatalogSetDefaults	(xmlCatalogAllow allow);
+XMLPUBFUN xmlCatalogAllow XMLCALL	
+		xmlCatalogGetDefaults	(void);
+
+
+/* DEPRECATED interfaces */
+XMLPUBFUN const xmlChar * XMLCALL	
+		xmlCatalogGetSystem	(const xmlChar *sysID);
+XMLPUBFUN const xmlChar * XMLCALL	
+		xmlCatalogGetPublic	(const xmlChar *pubID);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* LIBXML_CATALOG_ENABLED */
+#endif /* __XML_CATALOG_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/chvalid.h ./aperios/include/libxml2/libxml/chvalid.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/chvalid.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/chvalid.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,230 @@
+/*
+ * Summary: Unicode character range checking
+ * Description: this module exports interfaces for the character
+ *		 range validation APIs
+ *
+ * This file is automatically generated from the cvs source
+ * definition files using the genChRanges.py Python script
+ *
+ * Generation date: Tue Nov 18 08:14:21 2003
+ * Sources: chvalid.def
+ * Author: William Brack <wbrack@mmm.com.hk>
+ */
+
+#ifndef __XML_CHVALID_H__
+#define __XML_CHVALID_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/xmlstring.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Define our typedefs and structures
+ *
+ */
+typedef struct _xmlChSRange xmlChSRange;
+typedef xmlChSRange *xmlChSRangePtr;
+struct _xmlChSRange {
+    unsigned short	low;
+    unsigned short	high;
+};
+
+typedef struct _xmlChLRange xmlChLRange;
+typedef xmlChLRange *xmlChLRangePtr;
+struct _xmlChLRange {
+    unsigned int	low;
+    unsigned int	high;
+};
+
+typedef struct _xmlChRangeGroup xmlChRangeGroup;
+typedef xmlChRangeGroup *xmlChRangeGroupPtr;
+struct _xmlChRangeGroup {
+    int			nbShortRange;
+    int			nbLongRange;
+    xmlChSRangePtr	shortRange;	/* points to an array of ranges */
+    xmlChLRangePtr	longRange;
+};
+
+/**
+ * Range checking routine
+ */
+XMLPUBFUN int XMLCALL
+		xmlCharInRange(unsigned int val, const xmlChRangeGroupPtr group);
+
+
+/**
+ * xmlIsBaseChar_ch:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsBaseChar_ch(c)	(((0x41 <= (c)) && ((c) <= 0x5a)) || \
+				 ((0x61 <= (c)) && ((c) <= 0x7a)) || \
+				 ((0xc0 <= (c)) && ((c) <= 0xd6)) || \
+				 ((0xd8 <= (c)) && ((c) <= 0xf6)) || \
+				  (0xf8 <= (c)))
+
+/**
+ * xmlIsBaseCharQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsBaseCharQ(c)	(((c) < 0x100) ? \
+				 xmlIsBaseChar_ch((c)) : \
+				 xmlCharInRange((c), &xmlIsBaseCharGroup))
+
+XMLPUBVAR xmlChRangeGroup xmlIsBaseCharGroup;
+
+/**
+ * xmlIsBlank_ch:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsBlank_ch(c)	(((c) == 0x20) || \
+				 ((0x9 <= (c)) && ((c) <= 0xa)) || \
+				 ((c) == 0xd))
+
+/**
+ * xmlIsBlankQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsBlankQ(c)		(((c) < 0x100) ? \
+				 xmlIsBlank_ch((c)) : 0)
+
+
+/**
+ * xmlIsChar_ch:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsChar_ch(c)		(((0x9 <= (c)) && ((c) <= 0xa)) || \
+				 ((c) == 0xd) || \
+				  (0x20 <= (c)))
+
+/**
+ * xmlIsCharQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsCharQ(c)		(((c) < 0x100) ? \
+				 xmlIsChar_ch((c)) :\
+				(((0x100 <= (c)) && ((c) <= 0xd7ff)) || \
+				 ((0xe000 <= (c)) && ((c) <= 0xfffd)) || \
+				 ((0x10000 <= (c)) && ((c) <= 0x10ffff))))
+
+XMLPUBVAR xmlChRangeGroup xmlIsCharGroup;
+
+/**
+ * xmlIsCombiningQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsCombiningQ(c)	(((c) < 0x100) ? \
+				 0 : \
+				 xmlCharInRange((c), &xmlIsCombiningGroup))
+
+XMLPUBVAR xmlChRangeGroup xmlIsCombiningGroup;
+
+/**
+ * xmlIsDigit_ch:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsDigit_ch(c)	(((0x30 <= (c)) && ((c) <= 0x39)))
+
+/**
+ * xmlIsDigitQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsDigitQ(c)		(((c) < 0x100) ? \
+				 xmlIsDigit_ch((c)) : \
+				 xmlCharInRange((c), &xmlIsDigitGroup))
+
+XMLPUBVAR xmlChRangeGroup xmlIsDigitGroup;
+
+/**
+ * xmlIsExtender_ch:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsExtender_ch(c)	(((c) == 0xb7))
+
+/**
+ * xmlIsExtenderQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsExtenderQ(c)	(((c) < 0x100) ? \
+				 xmlIsExtender_ch((c)) : \
+				 xmlCharInRange((c), &xmlIsExtenderGroup))
+
+XMLPUBVAR xmlChRangeGroup xmlIsExtenderGroup;
+
+/**
+ * xmlIsIdeographicQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsIdeographicQ(c)	(((c) < 0x100) ? \
+				 0 :\
+				(((0x4e00 <= (c)) && ((c) <= 0x9fa5)) || \
+				 ((c) == 0x3007) || \
+				 ((0x3021 <= (c)) && ((c) <= 0x3029))))
+
+XMLPUBVAR xmlChRangeGroup xmlIsIdeographicGroup;
+XMLPUBVAR unsigned char xmlIsPubidChar_tab[256];
+
+/**
+ * xmlIsPubidChar_ch:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsPubidChar_ch(c)	(xmlIsPubidChar_tab[(c)])
+
+/**
+ * xmlIsPubidCharQ:
+ * @c: char to validate
+ *
+ * Automatically generated by genChRanges.py
+ */
+#define xmlIsPubidCharQ(c)	(((c) < 0x100) ? \
+				 xmlIsPubidChar_ch((c)) : 0)
+
+XMLPUBFUN int XMLCALL
+		xmlIsBaseChar(unsigned int ch);
+XMLPUBFUN int XMLCALL
+		xmlIsBlank(unsigned int ch);
+XMLPUBFUN int XMLCALL
+		xmlIsChar(unsigned int ch);
+XMLPUBFUN int XMLCALL
+		xmlIsCombining(unsigned int ch);
+XMLPUBFUN int XMLCALL
+		xmlIsDigit(unsigned int ch);
+XMLPUBFUN int XMLCALL
+		xmlIsExtender(unsigned int ch);
+XMLPUBFUN int XMLCALL
+		xmlIsIdeographic(unsigned int ch);
+XMLPUBFUN int XMLCALL
+		xmlIsPubidChar(unsigned int ch);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_CHVALID_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/debugXML.h ./aperios/include/libxml2/libxml/debugXML.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/debugXML.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/debugXML.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,217 @@
+/*
+ * Summary: Tree debugging APIs
+ * Description: Interfaces to a set of routines used for debugging the tree
+ *              produced by the XML parser.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __DEBUG_XML__
+#define __DEBUG_XML__
+#include <stdio.h>
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+
+#ifdef LIBXML_DEBUG_ENABLED
+
+#include <libxml/xpath.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The standard Dump routines.
+ */
+XMLPUBFUN void XMLCALL	
+	xmlDebugDumpString	(FILE *output,
+				 const xmlChar *str);
+XMLPUBFUN void XMLCALL	
+	xmlDebugDumpAttr	(FILE *output,
+				 xmlAttrPtr attr,
+				 int depth);
+XMLPUBFUN void XMLCALL	
+	xmlDebugDumpAttrList	(FILE *output,
+				 xmlAttrPtr attr,
+				 int depth);
+XMLPUBFUN void XMLCALL	
+	xmlDebugDumpOneNode	(FILE *output,
+				 xmlNodePtr node,
+				 int depth);
+XMLPUBFUN void XMLCALL
+	xmlDebugDumpNode	(FILE *output,
+				 xmlNodePtr node,
+				 int depth);
+XMLPUBFUN void XMLCALL
+	xmlDebugDumpNodeList	(FILE *output,
+				 xmlNodePtr node,
+				 int depth);
+XMLPUBFUN void XMLCALL
+	xmlDebugDumpDocumentHead(FILE *output,
+				 xmlDocPtr doc);
+XMLPUBFUN void XMLCALL
+	xmlDebugDumpDocument	(FILE *output,
+				 xmlDocPtr doc);
+XMLPUBFUN void XMLCALL	
+	xmlDebugDumpDTD		(FILE *output,
+				 xmlDtdPtr dtd);
+XMLPUBFUN void XMLCALL	
+	xmlDebugDumpEntities	(FILE *output,
+				 xmlDocPtr doc);
+
+/****************************************************************
+ *								*
+ *	 		Checking routines			*
+ *								*
+ ****************************************************************/
+
+XMLPUBFUN int XMLCALL
+	xmlDebugCheckDocument	(FILE * output,
+				 xmlDocPtr doc);
+
+/****************************************************************
+ *								*
+ *	 		XML shell helpers			*
+ *								*
+ ****************************************************************/
+
+XMLPUBFUN void XMLCALL	
+	xmlLsOneNode		(FILE *output, xmlNodePtr node);
+XMLPUBFUN int XMLCALL	
+	xmlLsCountNode		(xmlNodePtr node);
+
+XMLPUBFUN const char * XMLCALL 
+	xmlBoolToText		(int boolval);
+
+/****************************************************************
+ *								*
+ *	 The XML shell related structures and functions		*
+ *								*
+ ****************************************************************/
+
+#ifdef LIBXML_XPATH_ENABLED
+/**
+ * xmlShellReadlineFunc:
+ * @prompt:  a string prompt
+ *
+ * This is a generic signature for the XML shell input function.
+ *
+ * Returns a string which will be freed by the Shell.
+ */
+typedef char * (* xmlShellReadlineFunc)(char *prompt);
+
+/**
+ * xmlShellCtxt:
+ *
+ * A debugging shell context.
+ * TODO: add the defined function tables.
+ */
+typedef struct _xmlShellCtxt xmlShellCtxt;
+typedef xmlShellCtxt *xmlShellCtxtPtr;
+struct _xmlShellCtxt {
+    char *filename;
+    xmlDocPtr doc;
+    xmlNodePtr node;
+    xmlXPathContextPtr pctxt;
+    int loaded;
+    FILE *output;
+    xmlShellReadlineFunc input;
+};
+
+/**
+ * xmlShellCmd:
+ * @ctxt:  a shell context
+ * @arg:  a string argument
+ * @node:  a first node
+ * @node2:  a second node
+ *
+ * This is a generic signature for the XML shell functions.
+ *
+ * Returns an int, negative returns indicating errors.
+ */
+typedef int (* xmlShellCmd) (xmlShellCtxtPtr ctxt,
+                             char *arg,
+			     xmlNodePtr node,
+			     xmlNodePtr node2);
+
+XMLPUBFUN void XMLCALL	
+	xmlShellPrintXPathError	(int errorType,
+				 const char *arg);
+XMLPUBFUN void XMLCALL	
+	xmlShellPrintXPathResult(xmlXPathObjectPtr list);
+XMLPUBFUN int XMLCALL	
+	xmlShellList		(xmlShellCtxtPtr ctxt,
+				 char *arg,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+XMLPUBFUN int XMLCALL	
+	xmlShellBase		(xmlShellCtxtPtr ctxt,
+				 char *arg,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+XMLPUBFUN int XMLCALL	
+	xmlShellDir		(xmlShellCtxtPtr ctxt,
+				 char *arg,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+XMLPUBFUN int XMLCALL	
+	xmlShellLoad		(xmlShellCtxtPtr ctxt,
+				 char *filename,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL	
+	xmlShellPrintNode	(xmlNodePtr node);
+XMLPUBFUN int XMLCALL	
+	xmlShellCat		(xmlShellCtxtPtr ctxt,
+				 char *arg,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+XMLPUBFUN int XMLCALL	
+	xmlShellWrite		(xmlShellCtxtPtr ctxt,
+				 char *filename,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+XMLPUBFUN int XMLCALL	
+	xmlShellSave		(xmlShellCtxtPtr ctxt,
+				 char *filename,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+#endif /* LIBXML_OUTPUT_ENABLED */
+#ifdef LIBXML_VALID_ENABLED
+XMLPUBFUN int XMLCALL	
+	xmlShellValidate	(xmlShellCtxtPtr ctxt,
+				 char *dtd,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+#endif /* LIBXML_VALID_ENABLED */
+XMLPUBFUN int XMLCALL	
+	xmlShellDu		(xmlShellCtxtPtr ctxt,
+				 char *arg,
+				 xmlNodePtr tree,
+				 xmlNodePtr node2);
+XMLPUBFUN int XMLCALL	
+	xmlShellPwd		(xmlShellCtxtPtr ctxt,
+				 char *buffer,
+				 xmlNodePtr node,
+				 xmlNodePtr node2);
+
+/*
+ * The Shell interface.
+ */
+XMLPUBFUN void XMLCALL	
+	xmlShell		(xmlDocPtr doc,
+				 char *filename,
+				 xmlShellReadlineFunc input,
+				 FILE *output);
+			 
+#endif /* LIBXML_XPATH_ENABLED */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_DEBUG_ENABLED */
+#endif /* __DEBUG_XML__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/dict.h ./aperios/include/libxml2/libxml/dict.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/dict.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/dict.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,69 @@
+/*
+ * Summary: string dictionnary
+ * Description: dictionary of reusable strings, just used to avoid allocation
+ *         and freeing operations.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_DICT_H__
+#define __XML_DICT_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The dictionnary.
+ */
+typedef struct _xmlDict xmlDict;
+typedef xmlDict *xmlDictPtr;
+
+/*
+ * Constructor and destructor.
+ */
+XMLPUBFUN xmlDictPtr XMLCALL
+			xmlDictCreate	(void);
+XMLPUBFUN xmlDictPtr XMLCALL
+			xmlDictCreateSub(xmlDictPtr sub);
+XMLPUBFUN int XMLCALL
+			xmlDictReference(xmlDictPtr dict);
+XMLPUBFUN void XMLCALL			
+			xmlDictFree	(xmlDictPtr dict);
+
+/*
+ * Lookup of entry in the dictionnary.
+ */
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlDictLookup	(xmlDictPtr dict,
+		                         const xmlChar *name,
+		                         int len);
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlDictExists	(xmlDictPtr dict,
+		                         const xmlChar *name,
+		                         int len);
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlDictQLookup	(xmlDictPtr dict,
+		                         const xmlChar *prefix,
+		                         const xmlChar *name);
+XMLPUBFUN int XMLCALL
+			xmlDictOwns	(xmlDictPtr dict,
+					 const xmlChar *str);
+XMLPUBFUN int XMLCALL			
+			xmlDictSize	(xmlDictPtr dict);
+
+/*
+ * Cleanup function
+ */
+XMLPUBFUN void XMLCALL
+                        xmlDictCleanup  (void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* ! __XML_DICT_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/encoding.h ./aperios/include/libxml2/libxml/encoding.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/encoding.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/encoding.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,226 @@
+/*
+ * Summary: interface for the encoding conversion functions
+ * Description: interface for the encoding conversion functions needed for
+ *              XML basic encoding and iconv() support.
+ *
+ * Related specs are
+ * rfc2044        (UTF-8 and UTF-16) F. Yergeau Alis Technologies
+ * [ISO-10646]    UTF-8 and UTF-16 in Annexes
+ * [ISO-8859-1]   ISO Latin-1 characters codes.
+ * [UNICODE]      The Unicode Consortium, "The Unicode Standard --
+ *                Worldwide Character Encoding -- Version 1.0", Addison-
+ *                Wesley, Volume 1, 1991, Volume 2, 1992.  UTF-8 is
+ *                described in Unicode Technical Report #4.
+ * [US-ASCII]     Coded Character Set--7-bit American Standard Code for
+ *                Information Interchange, ANSI X3.4-1986.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_CHAR_ENCODING_H__
+#define __XML_CHAR_ENCODING_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_ICONV_ENABLED
+#include <iconv.h>
+#endif
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * xmlCharEncoding:
+ *
+ * Predefined values for some standard encodings.
+ * Libxml does not do beforehand translation on UTF8 and ISOLatinX.
+ * It also supports ASCII, ISO-8859-1, and UTF16 (LE and BE) by default.
+ *
+ * Anything else would have to be translated to UTF8 before being
+ * given to the parser itself. The BOM for UTF16 and the encoding
+ * declaration are looked at and a converter is looked for at that
+ * point. If not found the parser stops here as asked by the XML REC. A
+ * converter can be registered by the user using xmlRegisterCharEncodingHandler
+ * but the current form doesn't allow stateful transcoding (a serious
+ * problem agreed !). If iconv has been found it will be used
+ * automatically and allow stateful transcoding, the simplest is then
+ * to be sure to enable iconv and to provide iconv libs for the encoding
+ * support needed.
+ *
+ * Note that the generic "UTF-16" is not a predefined value.  Instead, only
+ * the specific UTF-16LE and UTF-16BE are present.
+ */
+typedef enum {
+    XML_CHAR_ENCODING_ERROR=   -1, /* No char encoding detected */
+    XML_CHAR_ENCODING_NONE=	0, /* No char encoding detected */
+    XML_CHAR_ENCODING_UTF8=	1, /* UTF-8 */
+    XML_CHAR_ENCODING_UTF16LE=	2, /* UTF-16 little endian */
+    XML_CHAR_ENCODING_UTF16BE=	3, /* UTF-16 big endian */
+    XML_CHAR_ENCODING_UCS4LE=	4, /* UCS-4 little endian */
+    XML_CHAR_ENCODING_UCS4BE=	5, /* UCS-4 big endian */
+    XML_CHAR_ENCODING_EBCDIC=	6, /* EBCDIC uh! */
+    XML_CHAR_ENCODING_UCS4_2143=7, /* UCS-4 unusual ordering */
+    XML_CHAR_ENCODING_UCS4_3412=8, /* UCS-4 unusual ordering */
+    XML_CHAR_ENCODING_UCS2=	9, /* UCS-2 */
+    XML_CHAR_ENCODING_8859_1=	10,/* ISO-8859-1 ISO Latin 1 */
+    XML_CHAR_ENCODING_8859_2=	11,/* ISO-8859-2 ISO Latin 2 */
+    XML_CHAR_ENCODING_8859_3=	12,/* ISO-8859-3 */
+    XML_CHAR_ENCODING_8859_4=	13,/* ISO-8859-4 */
+    XML_CHAR_ENCODING_8859_5=	14,/* ISO-8859-5 */
+    XML_CHAR_ENCODING_8859_6=	15,/* ISO-8859-6 */
+    XML_CHAR_ENCODING_8859_7=	16,/* ISO-8859-7 */
+    XML_CHAR_ENCODING_8859_8=	17,/* ISO-8859-8 */
+    XML_CHAR_ENCODING_8859_9=	18,/* ISO-8859-9 */
+    XML_CHAR_ENCODING_2022_JP=  19,/* ISO-2022-JP */
+    XML_CHAR_ENCODING_SHIFT_JIS=20,/* Shift_JIS */
+    XML_CHAR_ENCODING_EUC_JP=   21,/* EUC-JP */
+    XML_CHAR_ENCODING_ASCII=    22 /* pure ASCII */
+} xmlCharEncoding;
+
+/**
+ * xmlCharEncodingInputFunc:
+ * @out:  a pointer to an array of bytes to store the UTF-8 result
+ * @outlen:  the length of @out
+ * @in:  a pointer to an array of chars in the original encoding
+ * @inlen:  the length of @in
+ *
+ * Take a block of chars in the original encoding and try to convert
+ * it to an UTF-8 block of chars out.
+ *
+ * Returns the number of bytes written, -1 if lack of space, or -2
+ *     if the transcoding failed.
+ * The value of @inlen after return is the number of octets consumed
+ *     if the return value is positive, else unpredictiable.
+ * The value of @outlen after return is the number of octets consumed.
+ */
+typedef int (* xmlCharEncodingInputFunc)(unsigned char *out, int *outlen,
+                                         const unsigned char *in, int *inlen);
+
+
+/**
+ * xmlCharEncodingOutputFunc:
+ * @out:  a pointer to an array of bytes to store the result
+ * @outlen:  the length of @out
+ * @in:  a pointer to an array of UTF-8 chars
+ * @inlen:  the length of @in
+ *
+ * Take a block of UTF-8 chars in and try to convert it to another
+ * encoding.
+ * Note: a first call designed to produce heading info is called with
+ * in = NULL. If stateful this should also initialize the encoder state.
+ *
+ * Returns the number of bytes written, -1 if lack of space, or -2
+ *     if the transcoding failed.
+ * The value of @inlen after return is the number of octets consumed
+ *     if the return value is positive, else unpredictiable.
+ * The value of @outlen after return is the number of octets produced.
+ */
+typedef int (* xmlCharEncodingOutputFunc)(unsigned char *out, int *outlen,
+                                          const unsigned char *in, int *inlen);
+
+
+/*
+ * Block defining the handlers for non UTF-8 encodings.
+ * If iconv is supported, there are two extra fields.
+ */
+
+typedef struct _xmlCharEncodingHandler xmlCharEncodingHandler;
+typedef xmlCharEncodingHandler *xmlCharEncodingHandlerPtr;
+struct _xmlCharEncodingHandler {
+    char                       *name;
+    xmlCharEncodingInputFunc   input;
+    xmlCharEncodingOutputFunc  output;
+#ifdef LIBXML_ICONV_ENABLED
+    iconv_t                    iconv_in;
+    iconv_t                    iconv_out;
+#endif /* LIBXML_ICONV_ENABLED */
+};
+
+#ifdef __cplusplus
+}
+#endif
+#include <libxml/tree.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Interfaces for encoding handlers.
+ */
+XMLPUBFUN void XMLCALL	
+	xmlInitCharEncodingHandlers	(void);
+XMLPUBFUN void XMLCALL	
+	xmlCleanupCharEncodingHandlers	(void);
+XMLPUBFUN void XMLCALL	
+	xmlRegisterCharEncodingHandler	(xmlCharEncodingHandlerPtr handler);
+XMLPUBFUN xmlCharEncodingHandlerPtr XMLCALL
+	xmlGetCharEncodingHandler	(xmlCharEncoding enc);
+XMLPUBFUN xmlCharEncodingHandlerPtr XMLCALL
+	xmlFindCharEncodingHandler	(const char *name);
+XMLPUBFUN xmlCharEncodingHandlerPtr XMLCALL
+	xmlNewCharEncodingHandler	(const char *name, 
+                          		 xmlCharEncodingInputFunc input,
+                          		 xmlCharEncodingOutputFunc output);
+
+/*
+ * Interfaces for encoding names and aliases.
+ */
+XMLPUBFUN int XMLCALL	
+	xmlAddEncodingAlias		(const char *name,
+					 const char *alias);
+XMLPUBFUN int XMLCALL	
+	xmlDelEncodingAlias		(const char *alias);
+XMLPUBFUN const char * XMLCALL
+	xmlGetEncodingAlias		(const char *alias);
+XMLPUBFUN void XMLCALL	
+	xmlCleanupEncodingAliases	(void);
+XMLPUBFUN xmlCharEncoding XMLCALL
+	xmlParseCharEncoding		(const char *name);
+XMLPUBFUN const char * XMLCALL
+	xmlGetCharEncodingName		(xmlCharEncoding enc);
+
+/*
+ * Interfaces directly used by the parsers.
+ */
+XMLPUBFUN xmlCharEncoding XMLCALL
+	xmlDetectCharEncoding		(const unsigned char *in,
+					 int len);
+
+XMLPUBFUN int XMLCALL	
+	xmlCharEncOutFunc		(xmlCharEncodingHandler *handler,
+					 xmlBufferPtr out,
+					 xmlBufferPtr in);
+
+XMLPUBFUN int XMLCALL	
+	xmlCharEncInFunc		(xmlCharEncodingHandler *handler,
+					 xmlBufferPtr out,
+					 xmlBufferPtr in);
+XMLPUBFUN int XMLCALL
+	xmlCharEncFirstLine		(xmlCharEncodingHandler *handler,
+					 xmlBufferPtr out,
+					 xmlBufferPtr in);
+XMLPUBFUN int XMLCALL	
+	xmlCharEncCloseFunc		(xmlCharEncodingHandler *handler);
+
+/*
+ * Export a few useful functions
+ */
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN int XMLCALL	
+	UTF8Toisolat1			(unsigned char *out,
+					 int *outlen,
+					 const unsigned char *in,
+					 int *inlen);
+#endif /* LIBXML_OUTPUT_ENABLED */
+XMLPUBFUN int XMLCALL	
+	isolat1ToUTF8			(unsigned char *out,
+					 int *outlen,
+					 const unsigned char *in,
+					 int *inlen);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __XML_CHAR_ENCODING_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/entities.h ./aperios/include/libxml2/libxml/entities.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/entities.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/entities.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,139 @@
+/*
+ * Summary: interface for the XML entities handling
+ * Description: this module provides some of the entity API needed
+ *              for the parser and applications.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_ENTITIES_H__
+#define __XML_ENTITIES_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The different valid entity types.
+ */
+typedef enum {
+    XML_INTERNAL_GENERAL_ENTITY = 1,
+    XML_EXTERNAL_GENERAL_PARSED_ENTITY = 2,
+    XML_EXTERNAL_GENERAL_UNPARSED_ENTITY = 3,
+    XML_INTERNAL_PARAMETER_ENTITY = 4,
+    XML_EXTERNAL_PARAMETER_ENTITY = 5,
+    XML_INTERNAL_PREDEFINED_ENTITY = 6
+} xmlEntityType;
+
+/*
+ * An unit of storage for an entity, contains the string, the value
+ * and the linkind data needed for the linking in the hash table.
+ */
+
+struct _xmlEntity {
+    void           *_private;	        /* application data */
+    xmlElementType          type;       /* XML_ENTITY_DECL, must be second ! */
+    const xmlChar          *name;	/* Entity name */
+    struct _xmlNode    *children;	/* First child link */
+    struct _xmlNode        *last;	/* Last child link */
+    struct _xmlDtd       *parent;	/* -> DTD */
+    struct _xmlNode        *next;	/* next sibling link  */
+    struct _xmlNode        *prev;	/* previous sibling link  */
+    struct _xmlDoc          *doc;       /* the containing document */
+
+    xmlChar                *orig;	/* content without ref substitution */
+    xmlChar             *content;	/* content or ndata if unparsed */
+    int                   length;	/* the content length */
+    xmlEntityType          etype;	/* The entity type */
+    const xmlChar    *ExternalID;	/* External identifier for PUBLIC */
+    const xmlChar      *SystemID;	/* URI for a SYSTEM or PUBLIC Entity */
+
+    struct _xmlEntity     *nexte;	/* unused */
+    const xmlChar           *URI;	/* the full URI as computed */
+    int                    owner;	/* does the entity own the childrens */
+};
+
+/*
+ * All entities are stored in an hash table.
+ * There is 2 separate hash tables for global and parameter entities.
+ */
+
+typedef struct _xmlHashTable xmlEntitiesTable;
+typedef xmlEntitiesTable *xmlEntitiesTablePtr;
+
+/*
+ * External functions:
+ */
+
+#ifdef LIBXML_LEGACY_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlInitializePredefinedEntities	(void);
+#endif /* LIBXML_LEGACY_ENABLED */
+XMLPUBFUN xmlEntityPtr XMLCALL
+			xmlAddDocEntity		(xmlDocPtr doc,
+						 const xmlChar *name,
+						 int type,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID,
+						 const xmlChar *content);
+XMLPUBFUN xmlEntityPtr XMLCALL		
+			xmlAddDtdEntity		(xmlDocPtr doc,
+						 const xmlChar *name,
+						 int type,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID,
+						 const xmlChar *content);
+XMLPUBFUN xmlEntityPtr XMLCALL		
+			xmlGetPredefinedEntity	(const xmlChar *name);
+XMLPUBFUN xmlEntityPtr XMLCALL		
+			xmlGetDocEntity		(xmlDocPtr doc,
+						 const xmlChar *name);
+XMLPUBFUN xmlEntityPtr XMLCALL		
+			xmlGetDtdEntity		(xmlDocPtr doc,
+						 const xmlChar *name);
+XMLPUBFUN xmlEntityPtr XMLCALL		
+			xmlGetParameterEntity	(xmlDocPtr doc,
+						 const xmlChar *name);
+#ifdef LIBXML_LEGACY_ENABLED
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlEncodeEntities	(xmlDocPtr doc,
+						 const xmlChar *input);
+#endif /* LIBXML_LEGACY_ENABLED */
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlEncodeEntitiesReentrant(xmlDocPtr doc,
+						 const xmlChar *input);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlEncodeSpecialChars	(xmlDocPtr doc,
+						 const xmlChar *input);
+XMLPUBFUN xmlEntitiesTablePtr XMLCALL	
+			xmlCreateEntitiesTable	(void);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlEntitiesTablePtr XMLCALL	
+			xmlCopyEntitiesTable	(xmlEntitiesTablePtr table);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN void XMLCALL			
+			xmlFreeEntitiesTable	(xmlEntitiesTablePtr table);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL			
+			xmlDumpEntitiesTable	(xmlBufferPtr buf,
+						 xmlEntitiesTablePtr table);
+XMLPUBFUN void XMLCALL			
+			xmlDumpEntityDecl	(xmlBufferPtr buf,
+						 xmlEntityPtr ent);
+#endif /* LIBXML_OUTPUT_ENABLED */
+#ifdef LIBXML_LEGACY_ENABLED
+XMLPUBFUN void XMLCALL			
+			xmlCleanupPredefinedEntities(void);
+#endif /* LIBXML_LEGACY_ENABLED */
+
+
+#ifdef __cplusplus
+}
+#endif
+
+# endif /* __XML_ENTITIES_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/globals.h ./aperios/include/libxml2/libxml/globals.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/globals.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/globals.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,455 @@
+/*
+ * Summary: interface for all global variables of the library
+ * Description: all the global variables and thread handling for
+ *              those variables is handled by this module.
+ *
+ * The bottom of this file is automatically generated by build_glob.py
+ * based on the description file global.data
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Gary Pennington <Gary.Pennington@uk.sun.com>, Daniel Veillard
+ */
+
+#ifndef __XML_GLOBALS_H
+#define __XML_GLOBALS_H
+
+#include <libxml/xmlversion.h>
+#include <libxml/parser.h>
+#include <libxml/xmlerror.h>
+#include <libxml/SAX.h>
+#include <libxml/SAX2.h>
+#include <libxml/xmlmemory.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+XMLPUBFUN void XMLCALL xmlInitGlobals(void);
+XMLPUBFUN void XMLCALL xmlCleanupGlobals(void);
+
+typedef xmlParserInputBufferPtr (*xmlParserInputBufferCreateFilenameFunc) (const char *URI, xmlCharEncoding enc);
+typedef xmlOutputBufferPtr (*xmlOutputBufferCreateFilenameFunc) (const char *URI, xmlCharEncodingHandlerPtr encoder, int compression);
+XMLPUBFUN xmlParserInputBufferCreateFilenameFunc
+XMLCALL xmlParserInputBufferCreateFilenameDefault (xmlParserInputBufferCreateFilenameFunc func);
+XMLPUBFUN xmlOutputBufferCreateFilenameFunc
+XMLCALL xmlOutputBufferCreateFilenameDefault (xmlOutputBufferCreateFilenameFunc func);
+
+/*
+ * Externally global symbols which need to be protected for backwards
+ * compatibility support.
+ */
+
+#undef	docbDefaultSAXHandler
+#undef	htmlDefaultSAXHandler
+#undef	oldXMLWDcompatibility
+#undef	xmlBufferAllocScheme
+#undef	xmlDefaultBufferSize
+#undef	xmlDefaultSAXHandler
+#undef	xmlDefaultSAXLocator
+#undef	xmlDoValidityCheckingDefaultValue
+#undef	xmlFree
+#undef	xmlGenericError
+#undef	xmlStructuredError
+#undef	xmlGenericErrorContext
+#undef	xmlGetWarningsDefaultValue
+#undef	xmlIndentTreeOutput
+#undef  xmlTreeIndentString
+#undef	xmlKeepBlanksDefaultValue
+#undef	xmlLineNumbersDefaultValue
+#undef	xmlLoadExtDtdDefaultValue
+#undef	xmlMalloc
+#undef	xmlMallocAtomic
+#undef	xmlMemStrdup
+#undef	xmlParserDebugEntities
+#undef	xmlParserVersion
+#undef	xmlPedanticParserDefaultValue
+#undef	xmlRealloc
+#undef	xmlSaveNoEmptyTags
+#undef	xmlSubstituteEntitiesDefaultValue
+#undef  xmlRegisterNodeDefaultValue
+#undef  xmlDeregisterNodeDefaultValue
+#undef  xmlLastError
+#undef  xmlParserInputBufferCreateFilenameValue
+#undef  xmlOutputBufferCreateFilenameValue
+
+typedef void (*xmlRegisterNodeFunc) (xmlNodePtr node);
+typedef void (*xmlDeregisterNodeFunc) (xmlNodePtr node);
+
+typedef struct _xmlGlobalState xmlGlobalState;
+typedef xmlGlobalState *xmlGlobalStatePtr;
+struct _xmlGlobalState 
+{
+	const char *xmlParserVersion;
+
+	xmlSAXLocator xmlDefaultSAXLocator;
+	xmlSAXHandlerV1 xmlDefaultSAXHandler;
+	xmlSAXHandlerV1 docbDefaultSAXHandler;
+	xmlSAXHandlerV1 htmlDefaultSAXHandler;
+
+	xmlFreeFunc xmlFree;
+	xmlMallocFunc xmlMalloc;
+	xmlStrdupFunc xmlMemStrdup;
+	xmlReallocFunc xmlRealloc;
+
+	xmlGenericErrorFunc xmlGenericError;
+	xmlStructuredErrorFunc xmlStructuredError;
+	void *xmlGenericErrorContext;
+
+	int oldXMLWDcompatibility;
+
+	xmlBufferAllocationScheme xmlBufferAllocScheme;
+	int xmlDefaultBufferSize;
+
+	int xmlSubstituteEntitiesDefaultValue;
+	int xmlDoValidityCheckingDefaultValue;
+	int xmlGetWarningsDefaultValue;
+	int xmlKeepBlanksDefaultValue;
+	int xmlLineNumbersDefaultValue;
+	int xmlLoadExtDtdDefaultValue;
+	int xmlParserDebugEntities;
+	int xmlPedanticParserDefaultValue;
+
+	int xmlSaveNoEmptyTags;
+	int xmlIndentTreeOutput;
+	const char *xmlTreeIndentString;
+
+  	xmlRegisterNodeFunc xmlRegisterNodeDefaultValue;
+  	xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue;
+
+	xmlMallocFunc xmlMallocAtomic;
+	xmlError xmlLastError;
+
+	xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValue;
+	xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue;
+};
+
+#ifdef __cplusplus
+}
+#endif
+#include <libxml/threads.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+XMLPUBFUN void XMLCALL	xmlInitializeGlobalState(xmlGlobalStatePtr gs);
+
+XMLPUBFUN void XMLCALL xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler);
+
+XMLPUBFUN void XMLCALL xmlThrDefSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler);
+
+XMLPUBFUN xmlRegisterNodeFunc XMLCALL xmlRegisterNodeDefault(xmlRegisterNodeFunc func);
+XMLPUBFUN xmlRegisterNodeFunc XMLCALL xmlThrDefRegisterNodeDefault(xmlRegisterNodeFunc func);
+XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlDeregisterNodeDefault(xmlDeregisterNodeFunc func);
+XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlThrDefDeregisterNodeDefault(xmlDeregisterNodeFunc func);
+
+XMLPUBFUN xmlOutputBufferCreateFilenameFunc XMLCALL 
+	xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func);
+XMLPUBFUN xmlParserInputBufferCreateFilenameFunc XMLCALL 
+	xmlThrDefParserInputBufferCreateFilenameDefault(xmlParserInputBufferCreateFilenameFunc func);
+
+/** DOC_DISABLE */
+/*
+ * In general the memory allocation entry points are not kept
+ * thread specific but this can be overridden by LIBXML_THREAD_ALLOC_ENABLED
+ *    - xmlMalloc
+ *    - xmlMallocAtomic
+ *    - xmlRealloc
+ *    - xmlMemStrdup
+ *    - xmlFree
+ */
+
+#ifdef LIBXML_THREAD_ALLOC_ENABLED
+#ifdef LIBXML_THREAD_ENABLED
+XMLPUBFUN  xmlMallocFunc * XMLCALL __xmlMalloc(void);
+#define xmlMalloc \
+(*(__xmlMalloc()))
+#else
+XMLPUBVAR xmlMallocFunc xmlMalloc;
+#endif
+
+#ifdef LIBXML_THREAD_ENABLED
+XMLPUBFUN  xmlMallocFunc * XMLCALL __xmlMallocAtomic(void);
+#define xmlMallocAtomic \
+(*(__xmlMallocAtomic()))
+#else
+XMLPUBVAR xmlMallocFunc xmlMallocAtomic;
+#endif
+
+#ifdef LIBXML_THREAD_ENABLED
+XMLPUBFUN  xmlReallocFunc * XMLCALL __xmlRealloc(void);
+#define xmlRealloc \
+(*(__xmlRealloc()))
+#else
+XMLPUBVAR xmlReallocFunc xmlRealloc;
+#endif
+
+#ifdef LIBXML_THREAD_ENABLED
+XMLPUBFUN  xmlFreeFunc * XMLCALL __xmlFree(void);
+#define xmlFree \
+(*(__xmlFree()))
+#else
+XMLPUBVAR xmlFreeFunc xmlFree;
+#endif
+
+#ifdef LIBXML_THREAD_ENABLED
+XMLPUBFUN  xmlStrdupFunc * XMLCALL __xmlMemStrdup(void);
+#define xmlMemStrdup \
+(*(__xmlMemStrdup()))
+#else
+XMLPUBVAR xmlStrdupFunc xmlMemStrdup;
+#endif
+
+#else /* !LIBXML_THREAD_ALLOC_ENABLED */
+XMLPUBVAR xmlMallocFunc xmlMalloc;
+XMLPUBVAR xmlMallocFunc xmlMallocAtomic;
+XMLPUBVAR xmlReallocFunc xmlRealloc;
+XMLPUBVAR xmlFreeFunc xmlFree;
+XMLPUBVAR xmlStrdupFunc xmlMemStrdup;
+#endif /* LIBXML_THREAD_ALLOC_ENABLED */
+
+#ifdef LIBXML_DOCB_ENABLED
+XMLPUBFUN  xmlSAXHandlerV1 * XMLCALL __docbDefaultSAXHandler(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define docbDefaultSAXHandler \
+(*(__docbDefaultSAXHandler()))
+#else
+XMLPUBVAR xmlSAXHandlerV1 docbDefaultSAXHandler;
+#endif
+#endif
+
+#ifdef LIBXML_HTML_ENABLED
+XMLPUBFUN xmlSAXHandlerV1 * XMLCALL __htmlDefaultSAXHandler(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define htmlDefaultSAXHandler \
+(*(__htmlDefaultSAXHandler()))
+#else
+XMLPUBVAR xmlSAXHandlerV1 htmlDefaultSAXHandler;
+#endif
+#endif
+
+XMLPUBFUN xmlError * XMLCALL __xmlLastError(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlLastError \
+(*(__xmlLastError()))
+#else
+XMLPUBVAR xmlError xmlLastError;
+#endif
+
+/*
+ * Everything starting from the line below is
+ * Automatically generated by build_glob.py.
+ * Do not modify the previous line.
+ */
+
+
+XMLPUBFUN int * XMLCALL __oldXMLWDcompatibility(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define oldXMLWDcompatibility \
+(*(__oldXMLWDcompatibility()))
+#else
+XMLPUBVAR int oldXMLWDcompatibility;
+#endif
+
+XMLPUBFUN xmlBufferAllocationScheme * XMLCALL __xmlBufferAllocScheme(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlBufferAllocScheme \
+(*(__xmlBufferAllocScheme()))
+#else
+XMLPUBVAR xmlBufferAllocationScheme xmlBufferAllocScheme;
+#endif
+XMLPUBFUN xmlBufferAllocationScheme XMLCALL xmlThrDefBufferAllocScheme(xmlBufferAllocationScheme v);
+
+XMLPUBFUN int * XMLCALL __xmlDefaultBufferSize(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlDefaultBufferSize \
+(*(__xmlDefaultBufferSize()))
+#else
+XMLPUBVAR int xmlDefaultBufferSize;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefDefaultBufferSize(int v);
+
+XMLPUBFUN xmlSAXHandlerV1 * XMLCALL __xmlDefaultSAXHandler(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlDefaultSAXHandler \
+(*(__xmlDefaultSAXHandler()))
+#else
+XMLPUBVAR xmlSAXHandlerV1 xmlDefaultSAXHandler;
+#endif
+
+XMLPUBFUN xmlSAXLocator * XMLCALL __xmlDefaultSAXLocator(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlDefaultSAXLocator \
+(*(__xmlDefaultSAXLocator()))
+#else
+XMLPUBVAR xmlSAXLocator xmlDefaultSAXLocator;
+#endif
+
+XMLPUBFUN int * XMLCALL __xmlDoValidityCheckingDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlDoValidityCheckingDefaultValue \
+(*(__xmlDoValidityCheckingDefaultValue()))
+#else
+XMLPUBVAR int xmlDoValidityCheckingDefaultValue;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefDoValidityCheckingDefaultValue(int v);
+
+XMLPUBFUN xmlGenericErrorFunc * XMLCALL __xmlGenericError(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlGenericError \
+(*(__xmlGenericError()))
+#else
+XMLPUBVAR xmlGenericErrorFunc xmlGenericError;
+#endif
+
+XMLPUBFUN xmlStructuredErrorFunc * XMLCALL __xmlStructuredError(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlStructuredError \
+(*(__xmlStructuredError()))
+#else
+XMLPUBVAR xmlStructuredErrorFunc xmlStructuredError;
+#endif
+
+XMLPUBFUN void * * XMLCALL __xmlGenericErrorContext(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlGenericErrorContext \
+(*(__xmlGenericErrorContext()))
+#else
+XMLPUBVAR void * xmlGenericErrorContext;
+#endif
+
+XMLPUBFUN int * XMLCALL __xmlGetWarningsDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlGetWarningsDefaultValue \
+(*(__xmlGetWarningsDefaultValue()))
+#else
+XMLPUBVAR int xmlGetWarningsDefaultValue;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefGetWarningsDefaultValue(int v);
+
+XMLPUBFUN int * XMLCALL __xmlIndentTreeOutput(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlIndentTreeOutput \
+(*(__xmlIndentTreeOutput()))
+#else
+XMLPUBVAR int xmlIndentTreeOutput;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefIndentTreeOutput(int v);
+
+XMLPUBFUN const char * * XMLCALL __xmlTreeIndentString(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlTreeIndentString \
+(*(__xmlTreeIndentString()))
+#else
+XMLPUBVAR const char * xmlTreeIndentString;
+#endif
+XMLPUBFUN const char * XMLCALL xmlThrDefTreeIndentString(const char * v);
+
+XMLPUBFUN int * XMLCALL __xmlKeepBlanksDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlKeepBlanksDefaultValue \
+(*(__xmlKeepBlanksDefaultValue()))
+#else
+XMLPUBVAR int xmlKeepBlanksDefaultValue;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefKeepBlanksDefaultValue(int v);
+
+XMLPUBFUN int * XMLCALL __xmlLineNumbersDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlLineNumbersDefaultValue \
+(*(__xmlLineNumbersDefaultValue()))
+#else
+XMLPUBVAR int xmlLineNumbersDefaultValue;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefLineNumbersDefaultValue(int v);
+
+XMLPUBFUN int * XMLCALL __xmlLoadExtDtdDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlLoadExtDtdDefaultValue \
+(*(__xmlLoadExtDtdDefaultValue()))
+#else
+XMLPUBVAR int xmlLoadExtDtdDefaultValue;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefLoadExtDtdDefaultValue(int v);
+
+XMLPUBFUN int * XMLCALL __xmlParserDebugEntities(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlParserDebugEntities \
+(*(__xmlParserDebugEntities()))
+#else
+XMLPUBVAR int xmlParserDebugEntities;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefParserDebugEntities(int v);
+
+XMLPUBFUN const char * * XMLCALL __xmlParserVersion(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlParserVersion \
+(*(__xmlParserVersion()))
+#else
+XMLPUBVAR const char * xmlParserVersion;
+#endif
+
+XMLPUBFUN int * XMLCALL __xmlPedanticParserDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlPedanticParserDefaultValue \
+(*(__xmlPedanticParserDefaultValue()))
+#else
+XMLPUBVAR int xmlPedanticParserDefaultValue;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefPedanticParserDefaultValue(int v);
+
+XMLPUBFUN int * XMLCALL __xmlSaveNoEmptyTags(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlSaveNoEmptyTags \
+(*(__xmlSaveNoEmptyTags()))
+#else
+XMLPUBVAR int xmlSaveNoEmptyTags;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefSaveNoEmptyTags(int v);
+
+XMLPUBFUN int * XMLCALL __xmlSubstituteEntitiesDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlSubstituteEntitiesDefaultValue \
+(*(__xmlSubstituteEntitiesDefaultValue()))
+#else
+XMLPUBVAR int xmlSubstituteEntitiesDefaultValue;
+#endif
+XMLPUBFUN int XMLCALL xmlThrDefSubstituteEntitiesDefaultValue(int v);
+
+XMLPUBFUN xmlRegisterNodeFunc * XMLCALL __xmlRegisterNodeDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlRegisterNodeDefaultValue \
+(*(__xmlRegisterNodeDefaultValue()))
+#else
+XMLPUBVAR xmlRegisterNodeFunc xmlRegisterNodeDefaultValue;
+#endif
+
+XMLPUBFUN xmlDeregisterNodeFunc * XMLCALL __xmlDeregisterNodeDefaultValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlDeregisterNodeDefaultValue \
+(*(__xmlDeregisterNodeDefaultValue()))
+#else
+XMLPUBVAR xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue;
+#endif
+
+XMLPUBFUN xmlParserInputBufferCreateFilenameFunc * XMLCALL __xmlParserInputBufferCreateFilenameValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlParserInputBufferCreateFilenameValue \
+(*(__xmlParserInputBufferCreateFilenameValue()))
+#else
+XMLPUBVAR xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValue;
+#endif
+
+XMLPUBFUN xmlOutputBufferCreateFilenameFunc * XMLCALL __xmlOutputBufferCreateFilenameValue(void);
+#ifdef LIBXML_THREAD_ENABLED
+#define xmlOutputBufferCreateFilenameValue \
+(*(__xmlOutputBufferCreateFilenameValue()))
+#else
+XMLPUBVAR xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue;
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __XML_GLOBALS_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/hash.h ./aperios/include/libxml2/libxml/hash.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/hash.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/hash.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,233 @@
+/*
+ * Summary: Chained hash tables
+ * Description: This module implements the hash table support used in 
+ * 		various places in the library.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Bjorn Reese <bjorn.reese@systematic.dk>
+ */
+
+#ifndef __XML_HASH_H__
+#define __XML_HASH_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The hash table.
+ */
+typedef struct _xmlHashTable xmlHashTable;
+typedef xmlHashTable *xmlHashTablePtr;
+
+#ifdef __cplusplus
+}
+#endif
+
+#include <libxml/xmlversion.h>
+#include <libxml/parser.h>
+#include <libxml/dict.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Recent version of gcc produce a warning when a function pointer is assigned
+ * to an object pointer, or vice versa.  The following macro is a dirty hack
+ * to allow suppression of the warning.  If your architecture has function
+ * pointers which are a different size than a void pointer, there may be some
+ * serious trouble within the library.
+ */
+/**
+ * XML_CAST_FPTR:
+ * @fptr:  pointer to a function
+ *
+ * Macro to do a casting from an object pointer to a
+ * function pointer without encountering a warning from
+ * gcc
+ *
+ * #define XML_CAST_FPTR(fptr) (*(void **)(&fptr))
+ * This macro violated ISO C aliasing rules (gcc4 on s390 broke)
+ * so it is disabled now
+ */
+
+#define XML_CAST_FPTR(fptr) fptr
+
+
+/*
+ * function types:
+ */
+/**
+ * xmlHashDeallocator:
+ * @payload:  the data in the hash
+ * @name:  the name associated
+ *
+ * Callback to free data from a hash.
+ */
+typedef void (*xmlHashDeallocator)(void *payload, xmlChar *name);
+/**
+ * xmlHashCopier:
+ * @payload:  the data in the hash
+ * @name:  the name associated
+ *
+ * Callback to copy data from a hash.
+ *
+ * Returns a copy of the data or NULL in case of error.
+ */
+typedef void *(*xmlHashCopier)(void *payload, xmlChar *name);
+/**
+ * xmlHashScanner:
+ * @payload:  the data in the hash
+ * @data:  extra scannner data
+ * @name:  the name associated
+ *
+ * Callback when scanning data in a hash with the simple scanner.
+ */
+typedef void (*xmlHashScanner)(void *payload, void *data, xmlChar *name);
+/**
+ * xmlHashScannerFull:
+ * @payload:  the data in the hash
+ * @data:  extra scannner data
+ * @name:  the name associated
+ * @name2:  the second name associated
+ * @name3:  the third name associated
+ *
+ * Callback when scanning data in a hash with the full scanner.
+ */
+typedef void (*xmlHashScannerFull)(void *payload, void *data,
+				   const xmlChar *name, const xmlChar *name2,
+				   const xmlChar *name3);
+
+/*
+ * Constructor and destructor.
+ */
+XMLPUBFUN xmlHashTablePtr XMLCALL
+			xmlHashCreate	(int size);
+XMLPUBFUN xmlHashTablePtr XMLCALL
+			xmlHashCreateDict(int size,
+					 xmlDictPtr dict);
+XMLPUBFUN void XMLCALL			
+			xmlHashFree	(xmlHashTablePtr table,
+					 xmlHashDeallocator f);
+
+/*
+ * Add a new entry to the hash table.
+ */
+XMLPUBFUN int XMLCALL			
+			xmlHashAddEntry	(xmlHashTablePtr table,
+		                         const xmlChar *name,
+		                         void *userdata);
+XMLPUBFUN int XMLCALL			
+			xmlHashUpdateEntry(xmlHashTablePtr table,
+		                         const xmlChar *name,
+		                         void *userdata,
+					 xmlHashDeallocator f);
+XMLPUBFUN int XMLCALL		    
+			xmlHashAddEntry2(xmlHashTablePtr table,
+		                         const xmlChar *name,
+		                         const xmlChar *name2,
+		                         void *userdata);
+XMLPUBFUN int XMLCALL			
+			xmlHashUpdateEntry2(xmlHashTablePtr table,
+		                         const xmlChar *name,
+		                         const xmlChar *name2,
+		                         void *userdata,
+					 xmlHashDeallocator f);
+XMLPUBFUN int XMLCALL			
+			xmlHashAddEntry3(xmlHashTablePtr table,
+		                         const xmlChar *name,
+		                         const xmlChar *name2,
+		                         const xmlChar *name3,
+		                         void *userdata);
+XMLPUBFUN int XMLCALL			
+			xmlHashUpdateEntry3(xmlHashTablePtr table,
+		                         const xmlChar *name,
+		                         const xmlChar *name2,
+		                         const xmlChar *name3,
+		                         void *userdata,
+					 xmlHashDeallocator f);
+
+/*
+ * Remove an entry from the hash table.
+ */
+XMLPUBFUN int XMLCALL     
+			xmlHashRemoveEntry(xmlHashTablePtr table, const xmlChar *name,
+                           xmlHashDeallocator f);
+XMLPUBFUN int XMLCALL     
+			xmlHashRemoveEntry2(xmlHashTablePtr table, const xmlChar *name,
+                            const xmlChar *name2, xmlHashDeallocator f);
+XMLPUBFUN int  XMLCALL    
+			xmlHashRemoveEntry3(xmlHashTablePtr table, const xmlChar *name,
+                            const xmlChar *name2, const xmlChar *name3,
+                            xmlHashDeallocator f);
+
+/*
+ * Retrieve the userdata.
+ */
+XMLPUBFUN void * XMLCALL			
+			xmlHashLookup	(xmlHashTablePtr table,
+					 const xmlChar *name);
+XMLPUBFUN void * XMLCALL			
+			xmlHashLookup2	(xmlHashTablePtr table,
+					 const xmlChar *name,
+					 const xmlChar *name2);
+XMLPUBFUN void * XMLCALL			
+			xmlHashLookup3	(xmlHashTablePtr table,
+					 const xmlChar *name,
+					 const xmlChar *name2,
+					 const xmlChar *name3);
+XMLPUBFUN void * XMLCALL			
+			xmlHashQLookup	(xmlHashTablePtr table,
+					 const xmlChar *name,
+					 const xmlChar *prefix);
+XMLPUBFUN void * XMLCALL			
+			xmlHashQLookup2	(xmlHashTablePtr table,
+					 const xmlChar *name,
+					 const xmlChar *prefix,
+					 const xmlChar *name2,
+					 const xmlChar *prefix2);
+XMLPUBFUN void * XMLCALL			
+			xmlHashQLookup3	(xmlHashTablePtr table,
+					 const xmlChar *name,
+					 const xmlChar *prefix,
+					 const xmlChar *name2,
+					 const xmlChar *prefix2,
+					 const xmlChar *name3,
+					 const xmlChar *prefix3);
+
+/*
+ * Helpers.
+ */
+XMLPUBFUN xmlHashTablePtr XMLCALL		
+			xmlHashCopy	(xmlHashTablePtr table,
+					 xmlHashCopier f);
+XMLPUBFUN int XMLCALL			
+			xmlHashSize	(xmlHashTablePtr table);
+XMLPUBFUN void XMLCALL			
+			xmlHashScan	(xmlHashTablePtr table,
+					 xmlHashScanner f,
+					 void *data);
+XMLPUBFUN void XMLCALL			
+			xmlHashScan3	(xmlHashTablePtr table,
+					 const xmlChar *name,
+					 const xmlChar *name2,
+					 const xmlChar *name3,
+					 xmlHashScanner f,
+					 void *data);
+XMLPUBFUN void XMLCALL			
+			xmlHashScanFull	(xmlHashTablePtr table,
+					 xmlHashScannerFull f,
+					 void *data);
+XMLPUBFUN void XMLCALL			
+			xmlHashScanFull3(xmlHashTablePtr table,
+					 const xmlChar *name,
+					 const xmlChar *name2,
+					 const xmlChar *name3,
+					 xmlHashScannerFull f,
+					 void *data);
+#ifdef __cplusplus
+}
+#endif
+#endif /* ! __XML_HASH_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/list.h ./aperios/include/libxml2/libxml/list.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/list.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/list.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,137 @@
+/*
+ * Summary: lists interfaces
+ * Description: this module implement the list support used in 
+ * various place in the library.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Gary Pennington <Gary.Pennington@uk.sun.com>
+ */
+
+#ifndef __XML_LINK_INCLUDE__
+#define __XML_LINK_INCLUDE__
+
+#include <libxml/xmlversion.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct _xmlLink xmlLink;
+typedef xmlLink *xmlLinkPtr;
+
+typedef struct _xmlList xmlList;
+typedef xmlList *xmlListPtr;
+
+/**
+ * xmlListDeallocator:
+ * @lk:  the data to deallocate
+ *
+ * Callback function used to free data from a list.
+ */
+typedef void (*xmlListDeallocator) (xmlLinkPtr lk);
+/**
+ * xmlListDataCompare:
+ * @data0: the first data
+ * @data1: the second data
+ *
+ * Callback function used to compare 2 data.
+ *
+ * Returns 0 is equality, -1 or 1 otherwise depending on the ordering.
+ */
+typedef int  (*xmlListDataCompare) (const void *data0, const void *data1);
+/**
+ * xmlListWalker:
+ * @data: the data found in the list
+ * @user: extra user provided data to the walker
+ *
+ * Callback function used when walking a list with xmlListWalk().
+ *
+ * Returns 0 to stop walking the list, 1 otherwise.
+ */
+typedef int (*xmlListWalker) (const void *data, const void *user);
+
+/* Creation/Deletion */
+XMLPUBFUN xmlListPtr XMLCALL
+		xmlListCreate		(xmlListDeallocator deallocator,
+	                                 xmlListDataCompare compare);
+XMLPUBFUN void XMLCALL		
+		xmlListDelete		(xmlListPtr l);
+
+/* Basic Operators */
+XMLPUBFUN void * XMLCALL		
+		xmlListSearch		(xmlListPtr l,
+					 void *data);
+XMLPUBFUN void * XMLCALL		
+		xmlListReverseSearch	(xmlListPtr l,
+					 void *data);
+XMLPUBFUN int XMLCALL		
+		xmlListInsert		(xmlListPtr l,
+					 void *data) ;
+XMLPUBFUN int XMLCALL		
+		xmlListAppend		(xmlListPtr l,
+					 void *data) ;
+XMLPUBFUN int XMLCALL		
+		xmlListRemoveFirst	(xmlListPtr l,
+					 void *data);
+XMLPUBFUN int XMLCALL		
+		xmlListRemoveLast	(xmlListPtr l,
+					 void *data);
+XMLPUBFUN int XMLCALL		
+		xmlListRemoveAll	(xmlListPtr l,
+					 void *data);
+XMLPUBFUN void XMLCALL		
+		xmlListClear		(xmlListPtr l);
+XMLPUBFUN int XMLCALL		
+		xmlListEmpty		(xmlListPtr l);
+XMLPUBFUN xmlLinkPtr XMLCALL	
+		xmlListFront		(xmlListPtr l);
+XMLPUBFUN xmlLinkPtr XMLCALL	
+		xmlListEnd		(xmlListPtr l);
+XMLPUBFUN int XMLCALL		
+		xmlListSize		(xmlListPtr l);
+
+XMLPUBFUN void XMLCALL		
+		xmlListPopFront		(xmlListPtr l);
+XMLPUBFUN void XMLCALL		
+		xmlListPopBack		(xmlListPtr l);
+XMLPUBFUN int XMLCALL		
+		xmlListPushFront	(xmlListPtr l,
+					 void *data);
+XMLPUBFUN int XMLCALL		
+		xmlListPushBack		(xmlListPtr l,
+					 void *data);
+
+/* Advanced Operators */
+XMLPUBFUN void XMLCALL		
+		xmlListReverse		(xmlListPtr l);
+XMLPUBFUN void XMLCALL		
+		xmlListSort		(xmlListPtr l);
+XMLPUBFUN void XMLCALL		
+		xmlListWalk		(xmlListPtr l,
+					 xmlListWalker walker,
+					 const void *user);
+XMLPUBFUN void XMLCALL		
+		xmlListReverseWalk	(xmlListPtr l,
+					 xmlListWalker walker,
+					 const void *user);
+XMLPUBFUN void XMLCALL		
+		xmlListMerge		(xmlListPtr l1,
+					 xmlListPtr l2);
+XMLPUBFUN xmlListPtr XMLCALL	
+		xmlListDup		(const xmlListPtr old);
+XMLPUBFUN int XMLCALL		
+		xmlListCopy		(xmlListPtr cur,
+					 const xmlListPtr old);
+/* Link operators */
+XMLPUBFUN void * XMLCALL          
+		xmlLinkGetData          (xmlLinkPtr lk);
+
+/* xmlListUnique() */
+/* xmlListSwap */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __XML_LINK_INCLUDE__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/nanoftp.h ./aperios/include/libxml2/libxml/nanoftp.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/nanoftp.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/nanoftp.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,143 @@
+/*
+ * Summary: minimal FTP implementation
+ * Description: minimal FTP implementation allowing to fetch resources
+ *              like external subset.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+ 
+#ifndef __NANO_FTP_H__
+#define __NANO_FTP_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_FTP_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * ftpListCallback: 
+ * @userData:  user provided data for the callback
+ * @filename:  the file name (including "->" when links are shown)
+ * @attrib:  the attribute string
+ * @owner:  the owner string
+ * @group:  the group string
+ * @size:  the file size
+ * @links:  the link count
+ * @year:  the year
+ * @month:  the month
+ * @day:  the day
+ * @hour:  the hour
+ * @minute:  the minute
+ *
+ * A callback for the xmlNanoFTPList command.
+ * Note that only one of year and day:minute are specified.
+ */
+typedef void (*ftpListCallback) (void *userData,
+	                         const char *filename, const char *attrib,
+	                         const char *owner, const char *group,
+				 unsigned long size, int links, int year,
+				 const char *month, int day, int hour,
+				 int minute);
+/**
+ * ftpDataCallback: 
+ * @userData: the user provided context
+ * @data: the data received
+ * @len: its size in bytes
+ *
+ * A callback for the xmlNanoFTPGet command.
+ */
+typedef void (*ftpDataCallback) (void *userData,
+				 const char *data,
+				 int len);
+
+/*
+ * Init
+ */
+XMLPUBFUN void XMLCALL
+	xmlNanoFTPInit		(void);
+XMLPUBFUN void XMLCALL	
+	xmlNanoFTPCleanup	(void);
+
+/*
+ * Creating/freeing contexts.
+ */
+XMLPUBFUN void * XMLCALL	
+	xmlNanoFTPNewCtxt	(const char *URL);
+XMLPUBFUN void XMLCALL	
+	xmlNanoFTPFreeCtxt	(void * ctx);
+XMLPUBFUN void * XMLCALL 	
+	xmlNanoFTPConnectTo	(const char *server,
+				 int port);
+/*
+ * Opening/closing session connections.
+ */
+XMLPUBFUN void * XMLCALL 	
+	xmlNanoFTPOpen		(const char *URL);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPConnect	(void *ctx);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPClose		(void *ctx);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPQuit		(void *ctx);
+XMLPUBFUN void XMLCALL	
+	xmlNanoFTPScanProxy	(const char *URL);
+XMLPUBFUN void XMLCALL	
+	xmlNanoFTPProxy		(const char *host,
+				 int port,
+				 const char *user,
+				 const char *passwd,
+				 int type);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPUpdateURL	(void *ctx,
+				 const char *URL);
+
+/*
+ * Rather internal commands.
+ */
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPGetResponse	(void *ctx);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPCheckResponse	(void *ctx);
+
+/*
+ * CD/DIR/GET handlers.
+ */
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPCwd		(void *ctx,
+				 const char *directory);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPDele		(void *ctx,
+				 const char *file);
+
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPGetConnection	(void *ctx);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPCloseConnection(void *ctx);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPList		(void *ctx,
+				 ftpListCallback callback,
+				 void *userData,
+				 const char *filename);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPGetSocket	(void *ctx,
+				 const char *filename);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPGet		(void *ctx,
+				 ftpDataCallback callback,
+				 void *userData,
+				 const char *filename);
+XMLPUBFUN int XMLCALL	
+	xmlNanoFTPRead		(void *ctx,
+				 void *dest,
+				 int len);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* LIBXML_FTP_ENABLED */
+#endif /* __NANO_FTP_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/nanohttp.h ./aperios/include/libxml2/libxml/nanohttp.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/nanohttp.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/nanohttp.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,81 @@
+/*
+ * Summary: minimal HTTP implementation
+ * Description: minimal HTTP implementation allowing to fetch resources
+ *              like external subset.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+ 
+#ifndef __NANO_HTTP_H__
+#define __NANO_HTTP_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_HTTP_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+XMLPUBFUN void XMLCALL
+	xmlNanoHTTPInit		(void);
+XMLPUBFUN void XMLCALL	
+	xmlNanoHTTPCleanup	(void);
+XMLPUBFUN void XMLCALL	
+	xmlNanoHTTPScanProxy	(const char *URL);
+XMLPUBFUN int XMLCALL	
+	xmlNanoHTTPFetch	(const char *URL,
+				 const char *filename,
+				 char **contentType);
+XMLPUBFUN void * XMLCALL	
+	xmlNanoHTTPMethod	(const char *URL,
+				 const char *method,
+				 const char *input,
+				 char **contentType,
+				 const char *headers,
+				 int   ilen);
+XMLPUBFUN void * XMLCALL	
+	xmlNanoHTTPMethodRedir	(const char *URL,
+				 const char *method,
+				 const char *input,
+				 char **contentType,
+				 char **redir,
+				 const char *headers,
+				 int   ilen);
+XMLPUBFUN void * XMLCALL	
+	xmlNanoHTTPOpen		(const char *URL,
+				 char **contentType);
+XMLPUBFUN void * XMLCALL	
+	xmlNanoHTTPOpenRedir	(const char *URL,
+				 char **contentType,
+				 char **redir);
+XMLPUBFUN int XMLCALL	
+	xmlNanoHTTPReturnCode	(void *ctx);
+XMLPUBFUN const char * XMLCALL 
+	xmlNanoHTTPAuthHeader	(void *ctx);
+XMLPUBFUN const char * XMLCALL
+	xmlNanoHTTPRedir	(void *ctx);
+XMLPUBFUN int XMLCALL
+	xmlNanoHTTPContentLength( void * ctx );
+XMLPUBFUN const char * XMLCALL
+	xmlNanoHTTPEncoding	(void *ctx);
+XMLPUBFUN const char * XMLCALL
+	xmlNanoHTTPMimeType	(void *ctx);
+XMLPUBFUN int XMLCALL	
+	xmlNanoHTTPRead		(void *ctx,
+				 void *dest,
+				 int len);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN int XMLCALL	
+	xmlNanoHTTPSave		(void *ctxt,
+				 const char *filename);
+#endif /* LIBXML_OUTPUT_ENABLED */
+XMLPUBFUN void XMLCALL	
+	xmlNanoHTTPClose	(void *ctx);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_HTTP_ENABLED */
+#endif /* __NANO_HTTP_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/parser.h ./aperios/include/libxml2/libxml/parser.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/parser.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/parser.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,1171 @@
+/*
+ * Summary: the core parser module
+ * Description: Interfaces, constants and types related to the XML parser
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_PARSER_H__
+#define __XML_PARSER_H__
+
+#include <stdarg.h>
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+#include <libxml/dict.h>
+#include <libxml/hash.h>
+#include <libxml/valid.h>
+#include <libxml/entities.h>
+#include <libxml/xmlerror.h>
+#include <libxml/xmlstring.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * XML_DEFAULT_VERSION:
+ *
+ * The default version of XML used: 1.0
+ */
+#define XML_DEFAULT_VERSION	"1.0"
+
+/**
+ * xmlParserInput:
+ *
+ * An xmlParserInput is an input flow for the XML processor.
+ * Each entity parsed is associated an xmlParserInput (except the
+ * few predefined ones). This is the case both for internal entities
+ * - in which case the flow is already completely in memory - or
+ * external entities - in which case we use the buf structure for
+ * progressive reading and I18N conversions to the internal UTF-8 format.
+ */
+
+/**
+ * xmlParserInputDeallocate:
+ * @str:  the string to deallocate
+ *
+ * Callback for freeing some parser input allocations.
+ */
+typedef void (* xmlParserInputDeallocate)(xmlChar *str);
+
+struct _xmlParserInput {
+    /* Input buffer */
+    xmlParserInputBufferPtr buf;      /* UTF-8 encoded buffer */
+
+    const char *filename;             /* The file analyzed, if any */
+    const char *directory;            /* the directory/base of the file */
+    const xmlChar *base;              /* Base of the array to parse */
+    const xmlChar *cur;               /* Current char being parsed */
+    const xmlChar *end;               /* end of the array to parse */
+    int length;                       /* length if known */
+    int line;                         /* Current line */
+    int col;                          /* Current column */
+    /*
+     * NOTE: consumed is only tested for equality in the parser code,
+     *       so even if there is an overflow this should not give troubles
+     *       for parsing very large instances.
+     */
+    unsigned long consumed;           /* How many xmlChars already consumed */
+    xmlParserInputDeallocate free;    /* function to deallocate the base */
+    const xmlChar *encoding;          /* the encoding string for entity */
+    const xmlChar *version;           /* the version string for entity */
+    int standalone;                   /* Was that entity marked standalone */
+    int id;                           /* an unique identifier for the entity */
+};
+
+/**
+ * xmlParserNodeInfo:
+ *
+ * The parser can be asked to collect Node informations, i.e. at what
+ * place in the file they were detected. 
+ * NOTE: This is off by default and not very well tested.
+ */
+typedef struct _xmlParserNodeInfo xmlParserNodeInfo;
+typedef xmlParserNodeInfo *xmlParserNodeInfoPtr;
+
+struct _xmlParserNodeInfo {
+  const struct _xmlNode* node;
+  /* Position & line # that text that created the node begins & ends on */
+  unsigned long begin_pos;
+  unsigned long begin_line;
+  unsigned long end_pos;
+  unsigned long end_line;
+};
+
+typedef struct _xmlParserNodeInfoSeq xmlParserNodeInfoSeq;
+typedef xmlParserNodeInfoSeq *xmlParserNodeInfoSeqPtr;
+struct _xmlParserNodeInfoSeq {
+  unsigned long maximum;
+  unsigned long length;
+  xmlParserNodeInfo* buffer;
+};
+
+/**
+ * xmlParserInputState:
+ *
+ * The parser is now working also as a state based parser.
+ * The recursive one use the state info for entities processing.
+ */
+typedef enum {
+    XML_PARSER_EOF = -1,	/* nothing is to be parsed */
+    XML_PARSER_START = 0,	/* nothing has been parsed */
+    XML_PARSER_MISC,		/* Misc* before int subset */
+    XML_PARSER_PI,		/* Within a processing instruction */
+    XML_PARSER_DTD,		/* within some DTD content */
+    XML_PARSER_PROLOG,		/* Misc* after internal subset */
+    XML_PARSER_COMMENT,		/* within a comment */
+    XML_PARSER_START_TAG,	/* within a start tag */
+    XML_PARSER_CONTENT,		/* within the content */
+    XML_PARSER_CDATA_SECTION,	/* within a CDATA section */
+    XML_PARSER_END_TAG,		/* within a closing tag */
+    XML_PARSER_ENTITY_DECL,	/* within an entity declaration */
+    XML_PARSER_ENTITY_VALUE,	/* within an entity value in a decl */
+    XML_PARSER_ATTRIBUTE_VALUE,	/* within an attribute value */
+    XML_PARSER_SYSTEM_LITERAL,	/* within a SYSTEM value */
+    XML_PARSER_EPILOG, 		/* the Misc* after the last end tag */
+    XML_PARSER_IGNORE,		/* within an IGNORED section */
+    XML_PARSER_PUBLIC_LITERAL 	/* within a PUBLIC value */
+} xmlParserInputState;
+
+/**
+ * XML_DETECT_IDS:
+ *
+ * Bit in the loadsubset context field to tell to do ID/REFs lookups.
+ * Use it to initialize xmlLoadExtDtdDefaultValue.
+ */
+#define XML_DETECT_IDS		2
+
+/**
+ * XML_COMPLETE_ATTRS:
+ *
+ * Bit in the loadsubset context field to tell to do complete the
+ * elements attributes lists with the ones defaulted from the DTDs.
+ * Use it to initialize xmlLoadExtDtdDefaultValue.
+ */
+#define XML_COMPLETE_ATTRS	4
+
+/**
+ * XML_SKIP_IDS:
+ *
+ * Bit in the loadsubset context field to tell to not do ID/REFs registration.
+ * Used to initialize xmlLoadExtDtdDefaultValue in some special cases.
+ */
+#define XML_SKIP_IDS		8
+
+/**
+ * xmlParserMode:
+ *
+ * A parser can operate in various modes
+ */
+typedef enum {
+    XML_PARSE_UNKNOWN = 0,
+    XML_PARSE_DOM = 1,
+    XML_PARSE_SAX = 2,
+    XML_PARSE_PUSH_DOM = 3,
+    XML_PARSE_PUSH_SAX = 4,
+    XML_PARSE_READER = 5
+} xmlParserMode;
+
+/**
+ * xmlParserCtxt:
+ *
+ * The parser context.
+ * NOTE This doesn't completely define the parser state, the (current ?)
+ *      design of the parser uses recursive function calls since this allow
+ *      and easy mapping from the production rules of the specification
+ *      to the actual code. The drawback is that the actual function call
+ *      also reflect the parser state. However most of the parsing routines
+ *      takes as the only argument the parser context pointer, so migrating
+ *      to a state based parser for progressive parsing shouldn't be too hard.
+ */
+struct _xmlParserCtxt {
+    struct _xmlSAXHandler *sax;       /* The SAX handler */
+    void            *userData;        /* For SAX interface only, used by DOM build */
+    xmlDocPtr           myDoc;        /* the document being built */
+    int            wellFormed;        /* is the document well formed */
+    int       replaceEntities;        /* shall we replace entities ? */
+    const xmlChar    *version;        /* the XML version string */
+    const xmlChar   *encoding;        /* the declared encoding, if any */
+    int            standalone;        /* standalone document */
+    int                  html;        /* an HTML(1)/Docbook(2) document */
+
+    /* Input stream stack */
+    xmlParserInputPtr  input;         /* Current input stream */
+    int                inputNr;       /* Number of current input streams */
+    int                inputMax;      /* Max number of input streams */
+    xmlParserInputPtr *inputTab;      /* stack of inputs */
+
+    /* Node analysis stack only used for DOM building */
+    xmlNodePtr         node;          /* Current parsed Node */
+    int                nodeNr;        /* Depth of the parsing stack */
+    int                nodeMax;       /* Max depth of the parsing stack */
+    xmlNodePtr        *nodeTab;       /* array of nodes */
+
+    int record_info;                  /* Whether node info should be kept */
+    xmlParserNodeInfoSeq node_seq;    /* info about each node parsed */
+
+    int errNo;                        /* error code */
+
+    int     hasExternalSubset;        /* reference and external subset */
+    int             hasPErefs;        /* the internal subset has PE refs */
+    int              external;        /* are we parsing an external entity */
+
+    int                 valid;        /* is the document valid */
+    int              validate;        /* shall we try to validate ? */
+    xmlValidCtxt        vctxt;        /* The validity context */
+
+    xmlParserInputState instate;      /* current type of input */
+    int                 token;        /* next char look-ahead */    
+
+    char           *directory;        /* the data directory */
+
+    /* Node name stack */
+    const xmlChar     *name;          /* Current parsed Node */
+    int                nameNr;        /* Depth of the parsing stack */
+    int                nameMax;       /* Max depth of the parsing stack */
+    const xmlChar *   *nameTab;       /* array of nodes */
+
+    long               nbChars;       /* number of xmlChar processed */
+    long            checkIndex;       /* used by progressive parsing lookup */
+    int             keepBlanks;       /* ugly but ... */
+    int             disableSAX;       /* SAX callbacks are disabled */
+    int               inSubset;       /* Parsing is in int 1/ext 2 subset */
+    const xmlChar *    intSubName;    /* name of subset */
+    xmlChar *          extSubURI;     /* URI of external subset */
+    xmlChar *          extSubSystem;  /* SYSTEM ID of external subset */
+
+    /* xml:space values */
+    int *              space;         /* Should the parser preserve spaces */
+    int                spaceNr;       /* Depth of the parsing stack */
+    int                spaceMax;      /* Max depth of the parsing stack */
+    int *              spaceTab;      /* array of space infos */
+
+    int                depth;         /* to prevent entity substitution loops */
+    xmlParserInputPtr  entity;        /* used to check entities boundaries */
+    int                charset;       /* encoding of the in-memory content
+				         actually an xmlCharEncoding */
+    int                nodelen;       /* Those two fields are there to */
+    int                nodemem;       /* Speed up large node parsing */
+    int                pedantic;      /* signal pedantic warnings */
+    void              *_private;      /* For user data, libxml won't touch it */
+
+    int                loadsubset;    /* should the external subset be loaded */
+    int                linenumbers;   /* set line number in element content */
+    void              *catalogs;      /* document's own catalog */
+    int                recovery;      /* run in recovery mode */
+    int                progressive;   /* is this a progressive parsing */
+    xmlDictPtr         dict;          /* dictionnary for the parser */
+    const xmlChar *   *atts;          /* array for the attributes callbacks */
+    int                maxatts;       /* the size of the array */
+    int                docdict;       /* use strings from dict to build tree */
+
+    /*
+     * pre-interned strings
+     */
+    const xmlChar *str_xml;
+    const xmlChar *str_xmlns;
+    const xmlChar *str_xml_ns;
+
+    /*
+     * Everything below is used only by the new SAX mode
+     */
+    int                sax2;          /* operating in the new SAX mode */
+    int                nsNr;          /* the number of inherited namespaces */
+    int                nsMax;         /* the size of the arrays */
+    const xmlChar *   *nsTab;         /* the array of prefix/namespace name */
+    int               *attallocs;     /* which attribute were allocated */
+    void *            *pushTab;       /* array of data for push */
+    xmlHashTablePtr    attsDefault;   /* defaulted attributes if any */
+    xmlHashTablePtr    attsSpecial;   /* non-CDATA attributes if any */
+    int                nsWellFormed;  /* is the document XML Nanespace okay */
+    int                options;       /* Extra options */
+
+    /*
+     * Those fields are needed only for treaming parsing so far
+     */
+    int               dictNames;    /* Use dictionary names for the tree */
+    int               freeElemsNr;  /* number of freed element nodes */
+    xmlNodePtr        freeElems;    /* List of freed element nodes */
+    int               freeAttrsNr;  /* number of freed attributes nodes */
+    xmlAttrPtr        freeAttrs;    /* List of freed attributes nodes */
+
+    /*
+     * the complete error informations for the last error.
+     */
+    xmlError          lastError;
+    xmlParserMode     parseMode;    /* the parser mode */
+};
+
+/**
+ * xmlSAXLocator:
+ *
+ * A SAX Locator.
+ */
+struct _xmlSAXLocator {
+    const xmlChar *(*getPublicId)(void *ctx);
+    const xmlChar *(*getSystemId)(void *ctx);
+    int (*getLineNumber)(void *ctx);
+    int (*getColumnNumber)(void *ctx);
+};
+
+/**
+ * xmlSAXHandler:
+ *
+ * A SAX handler is bunch of callbacks called by the parser when processing
+ * of the input generate data or structure informations.
+ */
+
+/**
+ * resolveEntitySAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @publicId: The public ID of the entity
+ * @systemId: The system ID of the entity
+ *
+ * Callback:
+ * The entity loader, to control the loading of external entities,
+ * the application can either:
+ *    - override this resolveEntity() callback in the SAX block
+ *    - or better use the xmlSetExternalEntityLoader() function to
+ *      set up it's own entity resolution routine
+ *
+ * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour.
+ */
+typedef xmlParserInputPtr (*resolveEntitySAXFunc) (void *ctx,
+				const xmlChar *publicId,
+				const xmlChar *systemId);
+/**
+ * internalSubsetSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  the root element name
+ * @ExternalID:  the external ID
+ * @SystemID:  the SYSTEM ID (e.g. filename or URL)
+ *
+ * Callback on internal subset declaration.
+ */
+typedef void (*internalSubsetSAXFunc) (void *ctx,
+				const xmlChar *name,
+				const xmlChar *ExternalID,
+				const xmlChar *SystemID);
+/**
+ * externalSubsetSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  the root element name
+ * @ExternalID:  the external ID
+ * @SystemID:  the SYSTEM ID (e.g. filename or URL)
+ *
+ * Callback on external subset declaration.
+ */
+typedef void (*externalSubsetSAXFunc) (void *ctx,
+				const xmlChar *name,
+				const xmlChar *ExternalID,
+				const xmlChar *SystemID);
+/**
+ * getEntitySAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name: The entity name
+ *
+ * Get an entity by name.
+ *
+ * Returns the xmlEntityPtr if found.
+ */
+typedef xmlEntityPtr (*getEntitySAXFunc) (void *ctx,
+				const xmlChar *name);
+/**
+ * getParameterEntitySAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name: The entity name
+ *
+ * Get a parameter entity by name.
+ *
+ * Returns the xmlEntityPtr if found.
+ */
+typedef xmlEntityPtr (*getParameterEntitySAXFunc) (void *ctx,
+				const xmlChar *name);
+/**
+ * entityDeclSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  the entity name 
+ * @type:  the entity type 
+ * @publicId: The public ID of the entity
+ * @systemId: The system ID of the entity
+ * @content: the entity value (without processing).
+ *
+ * An entity definition has been parsed.
+ */
+typedef void (*entityDeclSAXFunc) (void *ctx,
+				const xmlChar *name,
+				int type,
+				const xmlChar *publicId,
+				const xmlChar *systemId,
+				xmlChar *content);
+/**
+ * notationDeclSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name: The name of the notation
+ * @publicId: The public ID of the entity
+ * @systemId: The system ID of the entity
+ *
+ * What to do when a notation declaration has been parsed.
+ */
+typedef void (*notationDeclSAXFunc)(void *ctx,
+				const xmlChar *name,
+				const xmlChar *publicId,
+				const xmlChar *systemId);
+/**
+ * attributeDeclSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @elem:  the name of the element
+ * @fullname:  the attribute name 
+ * @type:  the attribute type 
+ * @def:  the type of default value
+ * @defaultValue: the attribute default value
+ * @tree:  the tree of enumerated value set
+ *
+ * An attribute definition has been parsed.
+ */
+typedef void (*attributeDeclSAXFunc)(void *ctx,
+				const xmlChar *elem,
+				const xmlChar *fullname,
+				int type,
+				int def,
+				const xmlChar *defaultValue,
+				xmlEnumerationPtr tree);
+/**
+ * elementDeclSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  the element name 
+ * @type:  the element type 
+ * @content: the element value tree
+ *
+ * An element definition has been parsed.
+ */
+typedef void (*elementDeclSAXFunc)(void *ctx,
+				const xmlChar *name,
+				int type,
+				xmlElementContentPtr content);
+/**
+ * unparsedEntityDeclSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name: The name of the entity
+ * @publicId: The public ID of the entity
+ * @systemId: The system ID of the entity
+ * @notationName: the name of the notation
+ *
+ * What to do when an unparsed entity declaration is parsed.
+ */
+typedef void (*unparsedEntityDeclSAXFunc)(void *ctx,
+				const xmlChar *name,
+				const xmlChar *publicId,
+				const xmlChar *systemId,
+				const xmlChar *notationName);
+/**
+ * setDocumentLocatorSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @loc: A SAX Locator
+ *
+ * Receive the document locator at startup, actually xmlDefaultSAXLocator.
+ * Everything is available on the context, so this is useless in our case.
+ */
+typedef void (*setDocumentLocatorSAXFunc) (void *ctx,
+				xmlSAXLocatorPtr loc);
+/**
+ * startDocumentSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ *
+ * Called when the document start being processed.
+ */
+typedef void (*startDocumentSAXFunc) (void *ctx);
+/**
+ * endDocumentSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ *
+ * Called when the document end has been detected.
+ */
+typedef void (*endDocumentSAXFunc) (void *ctx);
+/**
+ * startElementSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  The element name, including namespace prefix
+ * @atts:  An array of name/value attributes pairs, NULL terminated
+ *
+ * Called when an opening tag has been processed.
+ */
+typedef void (*startElementSAXFunc) (void *ctx,
+				const xmlChar *name,
+				const xmlChar **atts);
+/**
+ * endElementSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  The element name
+ *
+ * Called when the end of an element has been detected.
+ */
+typedef void (*endElementSAXFunc) (void *ctx,
+				const xmlChar *name);
+/**
+ * attributeSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  The attribute name, including namespace prefix
+ * @value:  The attribute value
+ *
+ * Handle an attribute that has been read by the parser.
+ * The default handling is to convert the attribute into an
+ * DOM subtree and past it in a new xmlAttr element added to
+ * the element.
+ */
+typedef void (*attributeSAXFunc) (void *ctx,
+				const xmlChar *name,
+				const xmlChar *value);
+/**
+ * referenceSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @name:  The entity name
+ *
+ * Called when an entity reference is detected. 
+ */
+typedef void (*referenceSAXFunc) (void *ctx,
+				const xmlChar *name);
+/**
+ * charactersSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @ch:  a xmlChar string
+ * @len: the number of xmlChar
+ *
+ * Receiving some chars from the parser.
+ */
+typedef void (*charactersSAXFunc) (void *ctx,
+				const xmlChar *ch,
+				int len);
+/**
+ * ignorableWhitespaceSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @ch:  a xmlChar string
+ * @len: the number of xmlChar
+ *
+ * Receiving some ignorable whitespaces from the parser.
+ * UNUSED: by default the DOM building will use characters.
+ */
+typedef void (*ignorableWhitespaceSAXFunc) (void *ctx,
+				const xmlChar *ch,
+				int len);
+/**
+ * processingInstructionSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @target:  the target name
+ * @data: the PI data's
+ *
+ * A processing instruction has been parsed.
+ */
+typedef void (*processingInstructionSAXFunc) (void *ctx,
+				const xmlChar *target,
+				const xmlChar *data);
+/**
+ * commentSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @value:  the comment content
+ *
+ * A comment has been parsed.
+ */
+typedef void (*commentSAXFunc) (void *ctx,
+				const xmlChar *value);
+/**
+ * cdataBlockSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ * @value:  The pcdata content
+ * @len:  the block length
+ *
+ * Called when a pcdata block has been parsed.
+ */
+typedef void (*cdataBlockSAXFunc) (
+	                        void *ctx,
+				const xmlChar *value,
+				int len);
+/**
+ * warningSAXFunc:
+ * @ctx:  an XML parser context
+ * @msg:  the message to display/transmit
+ * @...:  extra parameters for the message display
+ * 
+ * Display and format a warning messages, callback.
+ */
+typedef void (*warningSAXFunc) (void *ctx,
+				const char *msg, ...);
+/**
+ * errorSAXFunc:
+ * @ctx:  an XML parser context
+ * @msg:  the message to display/transmit
+ * @...:  extra parameters for the message display
+ * 
+ * Display and format an error messages, callback.
+ */
+typedef void (*errorSAXFunc) (void *ctx,
+				const char *msg, ...);
+/**
+ * fatalErrorSAXFunc:
+ * @ctx:  an XML parser context
+ * @msg:  the message to display/transmit
+ * @...:  extra parameters for the message display
+ * 
+ * Display and format fatal error messages, callback.
+ * Note: so far fatalError() SAX callbacks are not used, error()
+ *       get all the callbacks for errors.
+ */
+typedef void (*fatalErrorSAXFunc) (void *ctx,
+				const char *msg, ...);
+/**
+ * isStandaloneSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ *
+ * Is this document tagged standalone?
+ *
+ * Returns 1 if true
+ */
+typedef int (*isStandaloneSAXFunc) (void *ctx);
+/**
+ * hasInternalSubsetSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ *
+ * Does this document has an internal subset.
+ *
+ * Returns 1 if true
+ */
+typedef int (*hasInternalSubsetSAXFunc) (void *ctx);
+
+/**
+ * hasExternalSubsetSAXFunc:
+ * @ctx:  the user data (XML parser context)
+ *
+ * Does this document has an external subset?
+ *
+ * Returns 1 if true
+ */
+typedef int (*hasExternalSubsetSAXFunc) (void *ctx);
+
+/************************************************************************
+ *									*
+ *			The SAX version 2 API extensions		*
+ *									*
+ ************************************************************************/
+/**
+ * XML_SAX2_MAGIC:
+ *
+ * Special constant found in SAX2 blocks initialized fields
+ */
+#define XML_SAX2_MAGIC 0xDEEDBEAF
+
+/**
+ * startElementNsSAX2Func:
+ * @ctx:  the user data (XML parser context)
+ * @localname:  the local name of the element
+ * @prefix:  the element namespace prefix if available
+ * @URI:  the element namespace name if available
+ * @nb_namespaces:  number of namespace definitions on that node
+ * @namespaces:  pointer to the array of prefix/URI pairs namespace definitions
+ * @nb_attributes:  the number of attributes on that node
+ * @nb_defaulted:  the number of defaulted attributes. The defaulted
+ *                  ones are at the end of the array
+ * @attributes:  pointer to the array of (localname/prefix/URI/value/end)
+ *               attribute values.
+ *
+ * SAX2 callback when an element start has been detected by the parser.
+ * It provides the namespace informations for the element, as well as
+ * the new namespace declarations on the element.
+ */
+
+typedef void (*startElementNsSAX2Func) (void *ctx,
+					const xmlChar *localname,
+					const xmlChar *prefix,
+					const xmlChar *URI,
+					int nb_namespaces,
+					const xmlChar **namespaces,
+					int nb_attributes,
+					int nb_defaulted,
+					const xmlChar **attributes);
+ 
+/**
+ * endElementNsSAX2Func:
+ * @ctx:  the user data (XML parser context)
+ * @localname:  the local name of the element
+ * @prefix:  the element namespace prefix if available
+ * @URI:  the element namespace name if available
+ *
+ * SAX2 callback when an element end has been detected by the parser.
+ * It provides the namespace informations for the element.
+ */
+
+typedef void (*endElementNsSAX2Func)   (void *ctx,
+					const xmlChar *localname,
+					const xmlChar *prefix,
+					const xmlChar *URI);
+
+
+struct _xmlSAXHandler {
+    internalSubsetSAXFunc internalSubset;
+    isStandaloneSAXFunc isStandalone;
+    hasInternalSubsetSAXFunc hasInternalSubset;
+    hasExternalSubsetSAXFunc hasExternalSubset;
+    resolveEntitySAXFunc resolveEntity;
+    getEntitySAXFunc getEntity;
+    entityDeclSAXFunc entityDecl;
+    notationDeclSAXFunc notationDecl;
+    attributeDeclSAXFunc attributeDecl;
+    elementDeclSAXFunc elementDecl;
+    unparsedEntityDeclSAXFunc unparsedEntityDecl;
+    setDocumentLocatorSAXFunc setDocumentLocator;
+    startDocumentSAXFunc startDocument;
+    endDocumentSAXFunc endDocument;
+    startElementSAXFunc startElement;
+    endElementSAXFunc endElement;
+    referenceSAXFunc reference;
+    charactersSAXFunc characters;
+    ignorableWhitespaceSAXFunc ignorableWhitespace;
+    processingInstructionSAXFunc processingInstruction;
+    commentSAXFunc comment;
+    warningSAXFunc warning;
+    errorSAXFunc error;
+    fatalErrorSAXFunc fatalError; /* unused error() get all the errors */
+    getParameterEntitySAXFunc getParameterEntity;
+    cdataBlockSAXFunc cdataBlock;
+    externalSubsetSAXFunc externalSubset;
+    unsigned int initialized;
+    /* The following fields are extensions available only on version 2 */
+    void *_private;
+    startElementNsSAX2Func startElementNs;
+    endElementNsSAX2Func endElementNs;
+    xmlStructuredErrorFunc serror;
+};
+
+/*
+ * SAX Version 1
+ */
+typedef struct _xmlSAXHandlerV1 xmlSAXHandlerV1;
+typedef xmlSAXHandlerV1 *xmlSAXHandlerV1Ptr;
+struct _xmlSAXHandlerV1 {
+    internalSubsetSAXFunc internalSubset;
+    isStandaloneSAXFunc isStandalone;
+    hasInternalSubsetSAXFunc hasInternalSubset;
+    hasExternalSubsetSAXFunc hasExternalSubset;
+    resolveEntitySAXFunc resolveEntity;
+    getEntitySAXFunc getEntity;
+    entityDeclSAXFunc entityDecl;
+    notationDeclSAXFunc notationDecl;
+    attributeDeclSAXFunc attributeDecl;
+    elementDeclSAXFunc elementDecl;
+    unparsedEntityDeclSAXFunc unparsedEntityDecl;
+    setDocumentLocatorSAXFunc setDocumentLocator;
+    startDocumentSAXFunc startDocument;
+    endDocumentSAXFunc endDocument;
+    startElementSAXFunc startElement;
+    endElementSAXFunc endElement;
+    referenceSAXFunc reference;
+    charactersSAXFunc characters;
+    ignorableWhitespaceSAXFunc ignorableWhitespace;
+    processingInstructionSAXFunc processingInstruction;
+    commentSAXFunc comment;
+    warningSAXFunc warning;
+    errorSAXFunc error;
+    fatalErrorSAXFunc fatalError; /* unused error() get all the errors */
+    getParameterEntitySAXFunc getParameterEntity;
+    cdataBlockSAXFunc cdataBlock;
+    externalSubsetSAXFunc externalSubset;
+    unsigned int initialized;
+};
+
+
+/**
+ * xmlExternalEntityLoader:
+ * @URL: The System ID of the resource requested
+ * @ID: The Public ID of the resource requested
+ * @context: the XML parser context 
+ *
+ * External entity loaders types.
+ *
+ * Returns the entity input parser.
+ */
+typedef xmlParserInputPtr (*xmlExternalEntityLoader) (const char *URL,
+					 const char *ID,
+					 xmlParserCtxtPtr context);
+
+#ifdef __cplusplus
+}
+#endif
+
+#include <libxml/encoding.h>
+#include <libxml/xmlIO.h>
+#include <libxml/globals.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*
+ * Init/Cleanup
+ */
+XMLPUBFUN void XMLCALL		
+		xmlInitParser		(void);
+XMLPUBFUN void XMLCALL		
+		xmlCleanupParser	(void);
+
+/*
+ * Input functions
+ */
+XMLPUBFUN int XMLCALL		
+		xmlParserInputRead	(xmlParserInputPtr in,
+					 int len);
+XMLPUBFUN int XMLCALL		
+		xmlParserInputGrow	(xmlParserInputPtr in,
+					 int len);
+
+/*
+ * Basic parsing Interfaces
+ */
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlParseDoc		(const xmlChar *cur);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlParseFile		(const char *filename);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlParseMemory		(const char *buffer,
+					 int size);
+#endif /* LIBXML_SAX1_ENABLED */
+XMLPUBFUN int XMLCALL		
+		xmlSubstituteEntitiesDefault(int val);
+XMLPUBFUN int XMLCALL		
+		xmlKeepBlanksDefault	(int val);
+#ifdef LIBXML_PUSH_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlStopParser		(xmlParserCtxtPtr ctxt);
+#endif /* LIBXML_PUSH_ENABLED */
+XMLPUBFUN int XMLCALL		
+		xmlPedanticParserDefault(int val);
+XMLPUBFUN int XMLCALL		
+		xmlLineNumbersDefault	(int val);
+
+#ifdef LIBXML_SAX1_ENABLED
+/*
+ * Recovery mode 
+ */
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlRecoverDoc		(xmlChar *cur);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlRecoverMemory	(const char *buffer,
+					 int size);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlRecoverFile		(const char *filename);
+#endif /* LIBXML_SAX1_ENABLED */
+
+/*
+ * Less common routines and SAX interfaces
+ */
+XMLPUBFUN int XMLCALL		
+		xmlParseDocument	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL		
+		xmlParseExtParsedEnt	(xmlParserCtxtPtr ctxt);
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN int XMLCALL		
+		xmlSAXUserParseFile	(xmlSAXHandlerPtr sax,
+					 void *user_data,
+					 const char *filename);
+XMLPUBFUN int XMLCALL		
+		xmlSAXUserParseMemory	(xmlSAXHandlerPtr sax,
+					 void *user_data,
+					 const char *buffer,
+					 int size);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlSAXParseDoc		(xmlSAXHandlerPtr sax,
+					 const xmlChar *cur,
+					 int recovery);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlSAXParseMemory	(xmlSAXHandlerPtr sax,
+					 const char *buffer,
+                                   	 int size,
+					 int recovery);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlSAXParseMemoryWithData (xmlSAXHandlerPtr sax,
+					 const char *buffer,
+                                   	 int size,
+					 int recovery,
+					 void *data);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlSAXParseFile		(xmlSAXHandlerPtr sax,
+					 const char *filename,
+					 int recovery);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlSAXParseFileWithData	(xmlSAXHandlerPtr sax,
+					 const char *filename,
+					 int recovery,
+					 void *data);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlSAXParseEntity	(xmlSAXHandlerPtr sax,
+					 const char *filename);
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlParseEntity		(const char *filename);
+#endif /* LIBXML_SAX1_ENABLED */
+
+#ifdef LIBXML_VALID_ENABLED
+XMLPUBFUN xmlDtdPtr XMLCALL	
+		xmlSAXParseDTD		(xmlSAXHandlerPtr sax,
+					 const xmlChar *ExternalID,
+					 const xmlChar *SystemID);
+XMLPUBFUN xmlDtdPtr XMLCALL	
+		xmlParseDTD		(const xmlChar *ExternalID,
+					 const xmlChar *SystemID);
+XMLPUBFUN xmlDtdPtr XMLCALL	
+		xmlIOParseDTD		(xmlSAXHandlerPtr sax,
+					 xmlParserInputBufferPtr input,
+					 xmlCharEncoding enc);
+#endif /* LIBXML_VALID_ENABLE */
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN int XMLCALL	
+		xmlParseBalancedChunkMemory(xmlDocPtr doc,
+					 xmlSAXHandlerPtr sax,
+					 void *user_data,
+					 int depth,
+					 const xmlChar *string,
+					 xmlNodePtr *lst);
+#endif /* LIBXML_SAX1_ENABLED */
+XMLPUBFUN xmlParserErrors XMLCALL
+		xmlParseInNodeContext	(xmlNodePtr node,
+					 const char *data,
+					 int datalen,
+					 int options,
+					 xmlNodePtr *lst);
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN int XMLCALL          
+		xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc,
+                     xmlSAXHandlerPtr sax,
+                     void *user_data,
+                     int depth,
+                     const xmlChar *string,
+                     xmlNodePtr *lst,
+                     int recover);
+XMLPUBFUN int XMLCALL		
+		xmlParseExternalEntity	(xmlDocPtr doc,
+					 xmlSAXHandlerPtr sax,
+					 void *user_data,
+					 int depth,
+					 const xmlChar *URL,
+					 const xmlChar *ID,
+					 xmlNodePtr *lst);
+#endif /* LIBXML_SAX1_ENABLED */
+XMLPUBFUN int XMLCALL		
+		xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx,
+					 const xmlChar *URL,
+					 const xmlChar *ID,
+					 xmlNodePtr *lst);
+
+/*
+ * Parser contexts handling.
+ */
+XMLPUBFUN xmlParserCtxtPtr XMLCALL	
+		xmlNewParserCtxt	(void);
+XMLPUBFUN int XMLCALL		
+		xmlInitParserCtxt	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL		
+		xmlClearParserCtxt	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL		
+		xmlFreeParserCtxt	(xmlParserCtxtPtr ctxt);
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlSetupParserForBuffer	(xmlParserCtxtPtr ctxt,
+					 const xmlChar* buffer,
+					 const char *filename);
+#endif /* LIBXML_SAX1_ENABLED */
+XMLPUBFUN xmlParserCtxtPtr XMLCALL 
+		xmlCreateDocParserCtxt	(const xmlChar *cur);
+
+#ifdef LIBXML_LEGACY_ENABLED
+/*
+ * Reading/setting optional parsing features.
+ */
+XMLPUBFUN int XMLCALL		
+		xmlGetFeaturesList	(int *len,
+					 const char **result);
+XMLPUBFUN int XMLCALL		
+		xmlGetFeature		(xmlParserCtxtPtr ctxt,
+					 const char *name,
+					 void *result);
+XMLPUBFUN int XMLCALL		
+		xmlSetFeature		(xmlParserCtxtPtr ctxt,
+					 const char *name,
+					 void *value);
+#endif /* LIBXML_LEGACY_ENABLED */
+
+#ifdef LIBXML_PUSH_ENABLED
+/*
+ * Interfaces for the Push mode.
+ */
+XMLPUBFUN xmlParserCtxtPtr XMLCALL 
+		xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax,
+					 void *user_data,
+					 const char *chunk,
+					 int size,
+					 const char *filename);
+XMLPUBFUN int XMLCALL		 
+		xmlParseChunk		(xmlParserCtxtPtr ctxt,
+					 const char *chunk,
+					 int size,
+					 int terminate);
+#endif /* LIBXML_PUSH_ENABLED */
+
+/*
+ * Special I/O mode.
+ */
+
+XMLPUBFUN xmlParserCtxtPtr XMLCALL 
+		xmlCreateIOParserCtxt	(xmlSAXHandlerPtr sax,
+					 void *user_data,
+					 xmlInputReadCallback   ioread,
+					 xmlInputCloseCallback  ioclose,
+					 void *ioctx,
+					 xmlCharEncoding enc);
+
+XMLPUBFUN xmlParserInputPtr XMLCALL 
+		xmlNewIOInputStream	(xmlParserCtxtPtr ctxt,
+					 xmlParserInputBufferPtr input,
+					 xmlCharEncoding enc);
+
+/*
+ * Node infos.
+ */
+XMLPUBFUN const xmlParserNodeInfo* XMLCALL
+		xmlParserFindNodeInfo	(const xmlParserCtxtPtr ctxt,
+				         const xmlNodePtr node);
+XMLPUBFUN void XMLCALL		
+		xmlInitNodeInfoSeq	(xmlParserNodeInfoSeqPtr seq);
+XMLPUBFUN void XMLCALL		
+		xmlClearNodeInfoSeq	(xmlParserNodeInfoSeqPtr seq);
+XMLPUBFUN unsigned long XMLCALL 
+		xmlParserFindNodeInfoIndex(const xmlParserNodeInfoSeqPtr seq,
+                                         const xmlNodePtr node);
+XMLPUBFUN void XMLCALL		
+		xmlParserAddNodeInfo	(xmlParserCtxtPtr ctxt,
+					 const xmlParserNodeInfoPtr info);
+
+/*
+ * External entities handling actually implemented in xmlIO.
+ */
+
+XMLPUBFUN void XMLCALL		
+		xmlSetExternalEntityLoader(xmlExternalEntityLoader f);
+XMLPUBFUN xmlExternalEntityLoader XMLCALL
+		xmlGetExternalEntityLoader(void);
+XMLPUBFUN xmlParserInputPtr XMLCALL
+		xmlLoadExternalEntity	(const char *URL,
+					 const char *ID,
+					 xmlParserCtxtPtr ctxt);
+
+/*
+ * Index lookup, actually implemented in the encoding module
+ */
+XMLPUBFUN long XMLCALL
+		xmlByteConsumed		(xmlParserCtxtPtr ctxt);
+
+/*
+ * New set of simpler/more flexible APIs
+ */
+/**
+ * xmlParserOption:
+ *
+ * This is the set of XML parser options that can be passed down
+ * to the xmlReadDoc() and similar calls.
+ */
+typedef enum {
+    XML_PARSE_RECOVER	= 1<<0,	/* recover on errors */
+    XML_PARSE_NOENT	= 1<<1,	/* substitute entities */
+    XML_PARSE_DTDLOAD	= 1<<2,	/* load the external subset */
+    XML_PARSE_DTDATTR	= 1<<3,	/* default DTD attributes */
+    XML_PARSE_DTDVALID	= 1<<4,	/* validate with the DTD */
+    XML_PARSE_NOERROR	= 1<<5,	/* suppress error reports */
+    XML_PARSE_NOWARNING	= 1<<6,	/* suppress warning reports */
+    XML_PARSE_PEDANTIC	= 1<<7,	/* pedantic error reporting */
+    XML_PARSE_NOBLANKS	= 1<<8,	/* remove blank nodes */
+    XML_PARSE_SAX1	= 1<<9,	/* use the SAX1 interface internally */
+    XML_PARSE_XINCLUDE	= 1<<10,/* Implement XInclude substitition  */
+    XML_PARSE_NONET	= 1<<11,/* Forbid network access */
+    XML_PARSE_NODICT	= 1<<12,/* Do not reuse the context dictionnary */
+    XML_PARSE_NSCLEAN	= 1<<13,/* remove redundant namespaces declarations */
+    XML_PARSE_NOCDATA	= 1<<14,/* merge CDATA as text nodes */
+    XML_PARSE_NOXINCNODE= 1<<15 /* do not generate XINCLUDE START/END nodes */
+} xmlParserOption;
+
+XMLPUBFUN void XMLCALL
+		xmlCtxtReset		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL
+		xmlCtxtResetPush	(xmlParserCtxtPtr ctxt,
+					 const char *chunk,
+					 int size,
+					 const char *filename,
+					 const char *encoding);
+XMLPUBFUN int XMLCALL
+		xmlCtxtUseOptions	(xmlParserCtxtPtr ctxt,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlReadDoc		(const xmlChar *cur,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlReadFile		(const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlReadMemory		(const char *buffer,
+					 int size,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlReadFd		(int fd,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlReadIO		(xmlInputReadCallback ioread,
+					 xmlInputCloseCallback ioclose,
+					 void *ioctx,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlCtxtReadDoc		(xmlParserCtxtPtr ctxt,
+					 const xmlChar *cur,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlCtxtReadFile		(xmlParserCtxtPtr ctxt,
+					 const char *filename,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlCtxtReadMemory		(xmlParserCtxtPtr ctxt,
+					 const char *buffer,
+					 int size,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlCtxtReadFd		(xmlParserCtxtPtr ctxt,
+					 int fd,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlDocPtr XMLCALL
+		xmlCtxtReadIO		(xmlParserCtxtPtr ctxt,
+					 xmlInputReadCallback ioread,
+					 xmlInputCloseCallback ioclose,
+					 void *ioctx,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_PARSER_H__ */
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/parserInternals.h ./aperios/include/libxml2/libxml/parserInternals.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/parserInternals.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/parserInternals.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,602 @@
+/*
+ * Summary: internals routines exported by the parser.
+ * Description: this module exports a number of internal parsing routines
+ *              they are not really all intended for applications but
+ *              can prove useful doing low level processing.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_PARSER_INTERNALS_H__
+#define __XML_PARSER_INTERNALS_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/parser.h>
+#include <libxml/HTMLparser.h>
+#include <libxml/chvalid.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlParserMaxDepth:
+ *
+ * arbitrary depth limit for the XML documents that we allow to 
+ * process. This is not a limitation of the parser but a safety 
+ * boundary feature.
+ */
+XMLPUBVAR unsigned int xmlParserMaxDepth;
+
+ /**
+  * XML_MAX_NAMELEN:
+  *
+  * Identifiers can be longer, but this will be more costly
+  * at runtime.
+  */
+#define XML_MAX_NAMELEN 100
+
+/**
+ * INPUT_CHUNK:
+ *
+ * The parser tries to always have that amount of input ready.
+ * One of the point is providing context when reporting errors.
+ */
+#define INPUT_CHUNK	250
+
+/************************************************************************
+ *									*
+ * UNICODE version of the macros.      					*
+ *									*
+ ************************************************************************/
+/**
+ * IS_BYTE_CHAR:
+ * @c:  an byte value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ * [2] Char ::= #x9 | #xA | #xD | [#x20...]
+ * any byte character in the accepted range
+ */
+#define IS_BYTE_CHAR(c)	 xmlIsChar_ch(c)
+
+/**
+ * IS_CHAR:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ * [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
+ *                  | [#x10000-#x10FFFF]
+ * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
+ */
+#define IS_CHAR(c)   xmlIsCharQ(c)
+
+/**
+ * IS_CHAR_CH:
+ * @c: an xmlChar (usually an unsigned char)
+ *
+ * Behaves like IS_CHAR on single-byte value
+ */
+#define IS_CHAR_CH(c)  xmlIsChar_ch(c)
+
+/**
+ * IS_BLANK:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ * [3] S ::= (#x20 | #x9 | #xD | #xA)+
+ */
+#define IS_BLANK(c)  xmlIsBlankQ(c)
+
+/**
+ * IS_BLANK_CH:
+ * @c:  an xmlChar value (normally unsigned char)
+ *
+ * Behaviour same as IS_BLANK
+ */
+#define IS_BLANK_CH(c)  xmlIsBlank_ch(c)
+
+/**
+ * IS_BASECHAR:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ * [85] BaseChar ::= ... long list see REC ...
+ */
+#define IS_BASECHAR(c) xmlIsBaseCharQ(c)
+
+/**
+ * IS_DIGIT:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ * [88] Digit ::= ... long list see REC ...
+ */
+#define IS_DIGIT(c) xmlIsDigitQ(c)
+
+/**
+ * IS_DIGIT_CH:
+ * @c:  an xmlChar value (usually an unsigned char)
+ *
+ * Behaves like IS_DIGIT but with a single byte argument
+ */
+#define IS_DIGIT_CH(c)  xmlIsDigit_ch(c)
+
+/**
+ * IS_COMBINING:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ * [87] CombiningChar ::= ... long list see REC ...
+ */
+#define IS_COMBINING(c) xmlIsCombiningQ(c)
+
+/**
+ * IS_COMBINING_CH:
+ * @c:  an xmlChar (usually an unsigned char)
+ *
+ * Always false (all combining chars > 0xff)
+ */
+#define IS_COMBINING_CH(c) 0 
+
+/**
+ * IS_EXTENDER:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ *
+ * [89] Extender ::= #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 |
+ *                   #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] |
+ *                   [#x309D-#x309E] | [#x30FC-#x30FE]
+ */
+#define IS_EXTENDER(c) xmlIsExtenderQ(c)
+
+/**
+ * IS_EXTENDER_CH:
+ * @c:  an xmlChar value (usually an unsigned char)
+ *
+ * Behaves like IS_EXTENDER but with a single-byte argument
+ */
+#define IS_EXTENDER_CH(c)  xmlIsExtender_ch(c)
+
+/**
+ * IS_IDEOGRAPHIC:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ *
+ * [86] Ideographic ::= [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029]
+ */
+#define IS_IDEOGRAPHIC(c) xmlIsIdeographicQ(c)
+
+/**
+ * IS_LETTER:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ *
+ * [84] Letter ::= BaseChar | Ideographic 
+ */
+#define IS_LETTER(c) (IS_BASECHAR(c) || IS_IDEOGRAPHIC(c))
+
+/**
+ * IS_LETTER_CH:
+ * @c:  an xmlChar value (normally unsigned char)
+ *
+ * Macro behaves like IS_LETTER, but only check base chars
+ *
+ */
+#define IS_LETTER_CH(c) xmlIsBaseChar_ch(c)
+
+/**
+ * IS_ASCII_LETTER:
+ * @c: an xmlChar value
+ *
+ * Macro to check [a-zA-Z]
+ *
+ */
+#define IS_ASCII_LETTER(c)	(((0x41 <= (c)) && ((c) <= 0x5a)) || \
+				 ((0x61 <= (c)) && ((c) <= 0x7a)))
+
+/**
+ * IS_ASCII_DIGIT:
+ * @c: an xmlChar value
+ *
+ * Macro to check [0-9]
+ *
+ */
+#define IS_ASCII_DIGIT(c)	((0x30 <= (c)) && ((c) <= 0x39))
+
+/**
+ * IS_PUBIDCHAR:
+ * @c:  an UNICODE value (int)
+ *
+ * Macro to check the following production in the XML spec:
+ *
+ *
+ * [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
+ */
+#define IS_PUBIDCHAR(c)	xmlIsPubidCharQ(c)
+
+/**
+ * IS_PUBIDCHAR_CH:
+ * @c:  an xmlChar value (normally unsigned char)
+ *
+ * Same as IS_PUBIDCHAR but for single-byte value
+ */
+#define IS_PUBIDCHAR_CH(c) xmlIsPubidChar_ch(c)
+
+/**
+ * SKIP_EOL:
+ * @p:  and UTF8 string pointer
+ *
+ * Skips the end of line chars.
+ */
+#define SKIP_EOL(p) 							\
+    if (*(p) == 0x13) { p++ ; if (*(p) == 0x10) p++; }			\
+    if (*(p) == 0x10) { p++ ; if (*(p) == 0x13) p++; }
+
+/**
+ * MOVETO_ENDTAG:
+ * @p:  and UTF8 string pointer
+ *
+ * Skips to the next '>' char.
+ */
+#define MOVETO_ENDTAG(p)						\
+    while ((*p) && (*(p) != '>')) (p)++
+
+/**
+ * MOVETO_STARTTAG:
+ * @p:  and UTF8 string pointer
+ *
+ * Skips to the next '<' char.
+ */
+#define MOVETO_STARTTAG(p)						\
+    while ((*p) && (*(p) != '<')) (p)++
+
+/**
+ * Global variables used for predefined strings.
+ */
+XMLPUBVAR const xmlChar xmlStringText[];
+XMLPUBVAR const xmlChar xmlStringTextNoenc[];
+XMLPUBVAR const xmlChar xmlStringComment[];
+
+/*
+ * Function to finish the work of the macros where needed.
+ */
+XMLPUBFUN int XMLCALL                   xmlIsLetter     (int c);
+
+/**
+ * Parser context.
+ */
+XMLPUBFUN xmlParserCtxtPtr XMLCALL	
+			xmlCreateFileParserCtxt	(const char *filename);
+XMLPUBFUN xmlParserCtxtPtr XMLCALL	
+			xmlCreateURLParserCtxt	(const char *filename,
+						 int options);
+XMLPUBFUN xmlParserCtxtPtr XMLCALL	
+			xmlCreateMemoryParserCtxt(const char *buffer,
+						 int size);
+XMLPUBFUN xmlParserCtxtPtr XMLCALL	
+			xmlCreateEntityParserCtxt(const xmlChar *URL,
+						 const xmlChar *ID,
+						 const xmlChar *base);
+XMLPUBFUN int XMLCALL			
+			xmlSwitchEncoding	(xmlParserCtxtPtr ctxt,
+						 xmlCharEncoding enc);
+XMLPUBFUN int XMLCALL			
+			xmlSwitchToEncoding	(xmlParserCtxtPtr ctxt,
+					 xmlCharEncodingHandlerPtr handler);
+XMLPUBFUN int XMLCALL			
+			xmlSwitchInputEncoding	(xmlParserCtxtPtr ctxt,
+						 xmlParserInputPtr input,
+					 xmlCharEncodingHandlerPtr handler);
+
+#ifdef IN_LIBXML
+/* internal error reporting */
+XMLPUBFUN void XMLCALL
+			__xmlErrEncoding	(xmlParserCtxtPtr ctxt,
+						 xmlParserErrors xmlerr,
+						 const char *msg,
+						 const xmlChar * str1,
+						 const xmlChar * str2);
+#endif
+
+/**
+ * Input Streams.
+ */
+XMLPUBFUN xmlParserInputPtr XMLCALL	
+			xmlNewStringInputStream	(xmlParserCtxtPtr ctxt,
+						 const xmlChar *buffer);
+XMLPUBFUN xmlParserInputPtr XMLCALL	
+			xmlNewEntityInputStream	(xmlParserCtxtPtr ctxt,
+						 xmlEntityPtr entity);
+XMLPUBFUN void XMLCALL			
+			xmlPushInput		(xmlParserCtxtPtr ctxt,
+						 xmlParserInputPtr input);
+XMLPUBFUN xmlChar XMLCALL			
+			xmlPopInput		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlFreeInputStream	(xmlParserInputPtr input);
+XMLPUBFUN xmlParserInputPtr XMLCALL	
+			xmlNewInputFromFile	(xmlParserCtxtPtr ctxt,
+						 const char *filename);
+XMLPUBFUN xmlParserInputPtr XMLCALL	
+			xmlNewInputStream	(xmlParserCtxtPtr ctxt);
+
+/**
+ * Namespaces.
+ */
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlSplitQName		(xmlParserCtxtPtr ctxt,
+						 const xmlChar *name,
+						 xmlChar **prefix);
+
+/**
+ * Generic production rules.
+ */
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlParseName		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseNmtoken		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseEntityValue	(xmlParserCtxtPtr ctxt,
+						 xmlChar **orig);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseAttValue	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseSystemLiteral	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParsePubidLiteral	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseCharData	(xmlParserCtxtPtr ctxt,
+						 int cdata);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseExternalID	(xmlParserCtxtPtr ctxt,
+						 xmlChar **publicID,
+						 int strict);
+XMLPUBFUN void XMLCALL			
+			xmlParseComment		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlParsePITarget	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParsePI		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseNotationDecl	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseEntityDecl	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			
+			xmlParseDefaultDecl	(xmlParserCtxtPtr ctxt,
+						 xmlChar **value);
+XMLPUBFUN xmlEnumerationPtr XMLCALL	
+			xmlParseNotationType	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlEnumerationPtr XMLCALL	
+			xmlParseEnumerationType	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			
+			xmlParseEnumeratedType	(xmlParserCtxtPtr ctxt,
+						 xmlEnumerationPtr *tree);
+XMLPUBFUN int XMLCALL			
+			xmlParseAttributeType	(xmlParserCtxtPtr ctxt,
+						 xmlEnumerationPtr *tree);
+XMLPUBFUN void XMLCALL			
+			xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlElementContentPtr XMLCALL	
+			xmlParseElementMixedContentDecl
+						(xmlParserCtxtPtr ctxt,
+						 int inputchk);
+XMLPUBFUN xmlElementContentPtr XMLCALL	
+			xmlParseElementChildrenContentDecl
+						(xmlParserCtxtPtr ctxt,
+						 int inputchk);
+XMLPUBFUN int XMLCALL			
+			xmlParseElementContentDecl(xmlParserCtxtPtr ctxt,
+						 const xmlChar *name,
+						 xmlElementContentPtr *result);
+XMLPUBFUN int XMLCALL			
+			xmlParseElementDecl	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseMarkupDecl	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			
+			xmlParseCharRef		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlEntityPtr XMLCALL		
+			xmlParseEntityRef	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseReference	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParsePEReference	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseDocTypeDecl	(xmlParserCtxtPtr ctxt);
+#ifdef LIBXML_SAX1_ENABLED
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlParseAttribute	(xmlParserCtxtPtr ctxt,
+						 xmlChar **value);
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlParseStartTag	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseEndTag		(xmlParserCtxtPtr ctxt);
+#endif /* LIBXML_SAX1_ENABLED */
+XMLPUBFUN void XMLCALL			
+			xmlParseCDSect		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseContent		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseElement		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseVersionNum	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseVersionInfo	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseEncName		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN const xmlChar * XMLCALL		
+			xmlParseEncodingDecl	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			
+			xmlParseSDDecl		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseXMLDecl		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseTextDecl	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseMisc		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+			xmlParseExternalSubset	(xmlParserCtxtPtr ctxt,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID); 
+/**
+ * XML_SUBSTITUTE_NONE:
+ *
+ * If no entities need to be substituted.
+ */
+#define XML_SUBSTITUTE_NONE	0
+/**
+ * XML_SUBSTITUTE_REF:
+ *
+ * Whether general entities need to be substituted.
+ */
+#define XML_SUBSTITUTE_REF	1
+/**
+ * XML_SUBSTITUTE_PEREF:
+ *
+ * Whether parameter entities need to be substituted.
+ */
+#define XML_SUBSTITUTE_PEREF	2
+/**
+ * XML_SUBSTITUTE_BOTH:
+ *
+ * Both general and parameter entities need to be substituted.
+ */
+#define XML_SUBSTITUTE_BOTH 	3
+
+XMLPUBFUN xmlChar * XMLCALL
+		xmlStringDecodeEntities		(xmlParserCtxtPtr ctxt,
+						 const xmlChar *str,
+						 int what,
+						 xmlChar end,
+						 xmlChar  end2,
+						 xmlChar end3);
+XMLPUBFUN xmlChar * XMLCALL
+		xmlStringLenDecodeEntities	(xmlParserCtxtPtr ctxt,
+						 const xmlChar *str,
+						 int len,
+						 int what,
+						 xmlChar end,
+						 xmlChar  end2,
+						 xmlChar end3);
+
+/*
+ * Generated by MACROS on top of parser.c c.f. PUSH_AND_POP.
+ */
+XMLPUBFUN int XMLCALL			nodePush		(xmlParserCtxtPtr ctxt,
+						 xmlNodePtr value);
+XMLPUBFUN xmlNodePtr XMLCALL		nodePop			(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			inputPush		(xmlParserCtxtPtr ctxt,
+						 xmlParserInputPtr value);
+XMLPUBFUN xmlParserInputPtr XMLCALL	inputPop		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN const xmlChar * XMLCALL	namePop			(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			namePush		(xmlParserCtxtPtr ctxt,
+						 const xmlChar *value);
+
+/*
+ * other commodities shared between parser.c and parserInternals.
+ */
+XMLPUBFUN int XMLCALL			xmlSkipBlankChars	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			xmlStringCurrentChar	(xmlParserCtxtPtr ctxt,
+						 const xmlChar *cur,
+						 int *len);
+XMLPUBFUN void XMLCALL			xmlParserHandlePEReference(xmlParserCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			xmlCheckLanguageID	(const xmlChar *lang);
+
+/*
+ * Really core function shared with HTML parser.
+ */
+XMLPUBFUN int XMLCALL			xmlCurrentChar		(xmlParserCtxtPtr ctxt,
+						 int *len);
+XMLPUBFUN int XMLCALL		xmlCopyCharMultiByte	(xmlChar *out,
+						 int val);
+XMLPUBFUN int XMLCALL			xmlCopyChar		(int len,
+						 xmlChar *out,
+						 int val);
+XMLPUBFUN void XMLCALL			xmlNextChar		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			xmlParserInputShrink	(xmlParserInputPtr in);
+
+#ifdef LIBXML_HTML_ENABLED
+/*
+ * Actually comes from the HTML parser but launched from the init stuff.
+ */
+XMLPUBFUN void XMLCALL			htmlInitAutoClose	(void);
+XMLPUBFUN htmlParserCtxtPtr XMLCALL	htmlCreateFileParserCtxt(const char *filename,
+	                                         const char *encoding);
+#endif
+
+/*
+ * Specific function to keep track of entities references
+ * and used by the XSLT debugger.
+ */
+#ifdef LIBXML_LEGACY_ENABLED
+/**
+ * xmlEntityReferenceFunc:
+ * @ent: the entity
+ * @firstNode:  the fist node in the chunk
+ * @lastNode:  the last nod in the chunk
+ *
+ * Callback function used when one needs to be able to track back the
+ * provenance of a chunk of nodes inherited from an entity replacement.
+ */
+typedef	void	(*xmlEntityReferenceFunc)	(xmlEntityPtr ent,
+						 xmlNodePtr firstNode,
+						 xmlNodePtr lastNode);
+  
+XMLPUBFUN void XMLCALL		xmlSetEntityReferenceFunc	(xmlEntityReferenceFunc func);
+
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlParseQuotedString	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL
+                        xmlParseNamespace       (xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlNamespaceParseNSDef	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlScanName		(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlNamespaceParseNCName	(xmlParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL	xmlParserHandleReference(xmlParserCtxtPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL		
+			xmlNamespaceParseQName	(xmlParserCtxtPtr ctxt,
+						 xmlChar **prefix);
+/**
+ * Entities
+ */
+XMLPUBFUN xmlChar * XMLCALL
+		xmlDecodeEntities		(xmlParserCtxtPtr ctxt,
+						 int len,
+						 int what,
+						 xmlChar end,
+						 xmlChar  end2,
+						 xmlChar end3);
+XMLPUBFUN void XMLCALL			
+			xmlHandleEntity		(xmlParserCtxtPtr ctxt,
+						 xmlEntityPtr entity);
+
+#endif /* LIBXML_LEGACY_ENABLED */
+
+#ifdef IN_LIBXML
+/*
+ * internal only
+ */
+XMLPUBFUN void XMLCALL
+	xmlErrMemory		(xmlParserCtxtPtr ctxt,
+				 const char *extra);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_PARSER_INTERNALS_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/pattern.h ./aperios/include/libxml2/libxml/pattern.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/pattern.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/pattern.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,77 @@
+/*
+ * Summary: pattern expression handling
+ * Description: allows to compile and test pattern expressions for nodes
+ *              either in a tree or based on a parser state.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_PATTERN_H__
+#define __XML_PATTERN_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+#include <libxml/dict.h>
+
+#ifdef LIBXML_PATTERN_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlPattern:
+ *
+ * A compiled (XPath based) pattern to select nodes
+ */
+typedef struct _xmlPattern xmlPattern;
+typedef xmlPattern *xmlPatternPtr;
+
+XMLPUBFUN void XMLCALL
+			xmlFreePattern		(xmlPatternPtr comp);
+
+XMLPUBFUN void XMLCALL
+			xmlFreePatternList	(xmlPatternPtr comp);
+
+XMLPUBFUN xmlPatternPtr XMLCALL
+			xmlPatterncompile	(const xmlChar *pattern,
+						 xmlDict *dict,
+						 int flags,
+						 const xmlChar **namespaces);
+XMLPUBFUN int XMLCALL
+			xmlPatternMatch		(xmlPatternPtr comp,
+						 xmlNodePtr node);
+
+/* streaming interfaces */
+typedef struct _xmlStreamCtxt xmlStreamCtxt;
+typedef xmlStreamCtxt *xmlStreamCtxtPtr;
+
+XMLPUBFUN int XMLCALL
+			xmlPatternStreamable	(xmlPatternPtr comp);
+XMLPUBFUN int XMLCALL
+			xmlPatternMaxDepth	(xmlPatternPtr comp);
+XMLPUBFUN int XMLCALL
+			xmlPatternFromRoot	(xmlPatternPtr comp);
+XMLPUBFUN xmlStreamCtxtPtr XMLCALL
+			xmlPatternGetStreamCtxt	(xmlPatternPtr comp);
+XMLPUBFUN void XMLCALL
+			xmlFreeStreamCtxt	(xmlStreamCtxtPtr stream);
+XMLPUBFUN int XMLCALL
+			xmlStreamPush		(xmlStreamCtxtPtr stream,
+						 const xmlChar *name,
+						 const xmlChar *ns);
+XMLPUBFUN int XMLCALL
+			xmlStreamPushAttr	(xmlStreamCtxtPtr stream,
+						 const xmlChar *name,
+						 const xmlChar *ns);
+XMLPUBFUN int XMLCALL
+			xmlStreamPop		(xmlStreamCtxtPtr stream);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_PATTERN_ENABLED */
+
+#endif /* __XML_PATTERN_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/relaxng.h ./aperios/include/libxml2/libxml/relaxng.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/relaxng.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/relaxng.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,188 @@
+/*
+ * Summary: implementation of the Relax-NG validation
+ * Description: implementation of the Relax-NG validation
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_RELAX_NG__
+#define __XML_RELAX_NG__
+
+#include <libxml/xmlversion.h>
+#include <libxml/hash.h>
+#include <libxml/xmlstring.h>
+
+#ifdef LIBXML_SCHEMAS_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct _xmlRelaxNG xmlRelaxNG;
+typedef xmlRelaxNG *xmlRelaxNGPtr;
+
+
+/**
+ * A schemas validation context
+ */
+typedef void (*xmlRelaxNGValidityErrorFunc) (void *ctx, const char *msg, ...);
+typedef void (*xmlRelaxNGValidityWarningFunc) (void *ctx, const char *msg, ...);
+
+typedef struct _xmlRelaxNGParserCtxt xmlRelaxNGParserCtxt;
+typedef xmlRelaxNGParserCtxt *xmlRelaxNGParserCtxtPtr;
+
+typedef struct _xmlRelaxNGValidCtxt xmlRelaxNGValidCtxt;
+typedef xmlRelaxNGValidCtxt *xmlRelaxNGValidCtxtPtr;
+
+/*
+ * xmlRelaxNGValidErr:
+ *
+ * List of possible Relax NG validation errors
+ */
+typedef enum {
+    XML_RELAXNG_OK = 0,
+    XML_RELAXNG_ERR_MEMORY,
+    XML_RELAXNG_ERR_TYPE,
+    XML_RELAXNG_ERR_TYPEVAL,
+    XML_RELAXNG_ERR_DUPID,
+    XML_RELAXNG_ERR_TYPECMP,
+    XML_RELAXNG_ERR_NOSTATE,
+    XML_RELAXNG_ERR_NODEFINE,
+    XML_RELAXNG_ERR_LISTEXTRA,
+    XML_RELAXNG_ERR_LISTEMPTY,
+    XML_RELAXNG_ERR_INTERNODATA,
+    XML_RELAXNG_ERR_INTERSEQ,
+    XML_RELAXNG_ERR_INTEREXTRA,
+    XML_RELAXNG_ERR_ELEMNAME,
+    XML_RELAXNG_ERR_ATTRNAME,
+    XML_RELAXNG_ERR_ELEMNONS,
+    XML_RELAXNG_ERR_ATTRNONS,
+    XML_RELAXNG_ERR_ELEMWRONGNS,
+    XML_RELAXNG_ERR_ATTRWRONGNS,
+    XML_RELAXNG_ERR_ELEMEXTRANS,
+    XML_RELAXNG_ERR_ATTREXTRANS,
+    XML_RELAXNG_ERR_ELEMNOTEMPTY,
+    XML_RELAXNG_ERR_NOELEM,
+    XML_RELAXNG_ERR_NOTELEM,
+    XML_RELAXNG_ERR_ATTRVALID,
+    XML_RELAXNG_ERR_CONTENTVALID,
+    XML_RELAXNG_ERR_EXTRACONTENT,
+    XML_RELAXNG_ERR_INVALIDATTR,
+    XML_RELAXNG_ERR_DATAELEM,
+    XML_RELAXNG_ERR_VALELEM,
+    XML_RELAXNG_ERR_LISTELEM,
+    XML_RELAXNG_ERR_DATATYPE,
+    XML_RELAXNG_ERR_VALUE,
+    XML_RELAXNG_ERR_LIST,
+    XML_RELAXNG_ERR_NOGRAMMAR,
+    XML_RELAXNG_ERR_EXTRADATA,
+    XML_RELAXNG_ERR_LACKDATA,
+    XML_RELAXNG_ERR_INTERNAL,
+    XML_RELAXNG_ERR_ELEMWRONG,
+    XML_RELAXNG_ERR_TEXTWRONG
+} xmlRelaxNGValidErr;
+
+/*
+ * xmlRelaxNGParserFlags:
+ *
+ * List of possible Relax NG Parser flags
+ */
+typedef enum {
+    XML_RELAXNGP_NONE = 0,
+    XML_RELAXNGP_FREE_DOC = 1,
+    XML_RELAXNGP_CRNG = 2
+} xmlRelaxNGParserFlag;
+
+XMLPUBFUN int XMLCALL
+		    xmlRelaxNGInitTypes		(void);
+XMLPUBFUN void XMLCALL			
+		    xmlRelaxNGCleanupTypes	(void);
+
+/*
+ * Interfaces for parsing.
+ */
+XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL 
+		    xmlRelaxNGNewParserCtxt	(const char *URL);
+XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL 
+		    xmlRelaxNGNewMemParserCtxt	(const char *buffer,
+						 int size);
+XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL   
+		    xmlRelaxNGNewDocParserCtxt	(xmlDocPtr doc);
+
+XMLPUBFUN int XMLCALL
+		    xmlRelaxParserSetFlag	(xmlRelaxNGParserCtxtPtr ctxt,
+		    				 int flag);
+
+XMLPUBFUN void XMLCALL		
+		    xmlRelaxNGFreeParserCtxt	(xmlRelaxNGParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL			
+		    xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,
+					 xmlRelaxNGValidityErrorFunc err,
+					 xmlRelaxNGValidityWarningFunc warn,
+					 void *ctx);
+XMLPUBFUN int XMLCALL
+		    xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,
+					 xmlRelaxNGValidityErrorFunc *err,
+					 xmlRelaxNGValidityWarningFunc *warn,
+					 void **ctx);
+XMLPUBFUN xmlRelaxNGPtr XMLCALL	
+		    xmlRelaxNGParse		(xmlRelaxNGParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL		
+		    xmlRelaxNGFree		(xmlRelaxNGPtr schema);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL		
+		    xmlRelaxNGDump		(FILE *output,
+					 xmlRelaxNGPtr schema);
+XMLPUBFUN void XMLCALL
+		    xmlRelaxNGDumpTree	(FILE * output,
+					 xmlRelaxNGPtr schema);
+#endif /* LIBXML_OUTPUT_ENABLED */
+/*
+ * Interfaces for validating
+ */
+XMLPUBFUN void XMLCALL		
+		    xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
+					 xmlRelaxNGValidityErrorFunc err,
+					 xmlRelaxNGValidityWarningFunc warn,
+					 void *ctx);
+XMLPUBFUN int XMLCALL	
+		    xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
+					 xmlRelaxNGValidityErrorFunc *err,
+					 xmlRelaxNGValidityWarningFunc *warn,
+					 void **ctx);
+XMLPUBFUN xmlRelaxNGValidCtxtPtr XMLCALL	
+		    xmlRelaxNGNewValidCtxt	(xmlRelaxNGPtr schema);
+XMLPUBFUN void XMLCALL			
+		    xmlRelaxNGFreeValidCtxt	(xmlRelaxNGValidCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			
+		    xmlRelaxNGValidateDoc	(xmlRelaxNGValidCtxtPtr ctxt,
+					 	 xmlDocPtr doc);
+/*
+ * Interfaces for progressive validation when possible
+ */
+XMLPUBFUN int XMLCALL	
+		    xmlRelaxNGValidatePushElement	(xmlRelaxNGValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem);
+XMLPUBFUN int XMLCALL	
+		    xmlRelaxNGValidatePushCData	(xmlRelaxNGValidCtxtPtr ctxt,
+					 const xmlChar *data,
+					 int len);
+XMLPUBFUN int XMLCALL	
+		    xmlRelaxNGValidatePopElement	(xmlRelaxNGValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem);
+XMLPUBFUN int XMLCALL	
+		    xmlRelaxNGValidateFullElement	(xmlRelaxNGValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_SCHEMAS_ENABLED */
+
+#endif /* __XML_RELAX_NG__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/schemasInternals.h ./aperios/include/libxml2/libxml/schemasInternals.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/schemasInternals.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/schemasInternals.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,864 @@
+/*
+ * Summary: internal interfaces for XML Schemas
+ * Description: internal interfaces for the XML Schemas handling
+ *              and schema validity checking
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+
+#ifndef __XML_SCHEMA_INTERNALS_H__
+#define __XML_SCHEMA_INTERNALS_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_SCHEMAS_ENABLED
+
+#include <libxml/xmlregexp.h>
+#include <libxml/hash.h>
+#include <libxml/dict.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    XML_SCHEMAS_UNKNOWN = 0,
+    XML_SCHEMAS_STRING,
+    XML_SCHEMAS_NORMSTRING,
+    XML_SCHEMAS_DECIMAL,
+    XML_SCHEMAS_TIME,
+    XML_SCHEMAS_GDAY,
+    XML_SCHEMAS_GMONTH,
+    XML_SCHEMAS_GMONTHDAY,
+    XML_SCHEMAS_GYEAR,
+    XML_SCHEMAS_GYEARMONTH,
+    XML_SCHEMAS_DATE,
+    XML_SCHEMAS_DATETIME,
+    XML_SCHEMAS_DURATION,
+    XML_SCHEMAS_FLOAT,
+    XML_SCHEMAS_DOUBLE,
+    XML_SCHEMAS_BOOLEAN,
+    XML_SCHEMAS_TOKEN,
+    XML_SCHEMAS_LANGUAGE,
+    XML_SCHEMAS_NMTOKEN,
+    XML_SCHEMAS_NMTOKENS,
+    XML_SCHEMAS_NAME,
+    XML_SCHEMAS_QNAME,
+    XML_SCHEMAS_NCNAME,
+    XML_SCHEMAS_ID,
+    XML_SCHEMAS_IDREF,
+    XML_SCHEMAS_IDREFS,
+    XML_SCHEMAS_ENTITY,
+    XML_SCHEMAS_ENTITIES,
+    XML_SCHEMAS_NOTATION,
+    XML_SCHEMAS_ANYURI,
+    XML_SCHEMAS_INTEGER,
+    XML_SCHEMAS_NPINTEGER,
+    XML_SCHEMAS_NINTEGER,
+    XML_SCHEMAS_NNINTEGER,
+    XML_SCHEMAS_PINTEGER,
+    XML_SCHEMAS_INT,
+    XML_SCHEMAS_UINT,
+    XML_SCHEMAS_LONG,
+    XML_SCHEMAS_ULONG,
+    XML_SCHEMAS_SHORT,
+    XML_SCHEMAS_USHORT,
+    XML_SCHEMAS_BYTE,
+    XML_SCHEMAS_UBYTE,
+    XML_SCHEMAS_HEXBINARY,
+    XML_SCHEMAS_BASE64BINARY,
+    XML_SCHEMAS_ANYTYPE,
+    XML_SCHEMAS_ANYSIMPLETYPE
+} xmlSchemaValType;
+
+/*
+ * XML Schemas defines multiple type of types.
+ */
+typedef enum {
+    XML_SCHEMA_TYPE_BASIC = 1, /* A built-in datatype */
+    XML_SCHEMA_TYPE_ANY,
+    XML_SCHEMA_TYPE_FACET,
+    XML_SCHEMA_TYPE_SIMPLE,
+    XML_SCHEMA_TYPE_COMPLEX,
+    XML_SCHEMA_TYPE_SEQUENCE,
+    XML_SCHEMA_TYPE_CHOICE,
+    XML_SCHEMA_TYPE_ALL,
+    XML_SCHEMA_TYPE_SIMPLE_CONTENT,
+    XML_SCHEMA_TYPE_COMPLEX_CONTENT,
+    XML_SCHEMA_TYPE_UR,
+    XML_SCHEMA_TYPE_RESTRICTION,
+    XML_SCHEMA_TYPE_EXTENSION,
+    XML_SCHEMA_TYPE_ELEMENT,
+    XML_SCHEMA_TYPE_ATTRIBUTE,
+    XML_SCHEMA_TYPE_ATTRIBUTEGROUP,
+    XML_SCHEMA_TYPE_GROUP,
+    XML_SCHEMA_TYPE_NOTATION,
+    XML_SCHEMA_TYPE_LIST,
+    XML_SCHEMA_TYPE_UNION,
+    XML_SCHEMA_TYPE_ANY_ATTRIBUTE,
+    XML_SCHEMA_TYPE_IDC_UNIQUE,
+    XML_SCHEMA_TYPE_IDC_KEY,
+    XML_SCHEMA_TYPE_IDC_KEYREF,
+    XML_SCHEMA_TYPE_PARTICLE,
+    XML_SCHEMA_FACET_MININCLUSIVE = 1000,
+    XML_SCHEMA_FACET_MINEXCLUSIVE,
+    XML_SCHEMA_FACET_MAXINCLUSIVE,
+    XML_SCHEMA_FACET_MAXEXCLUSIVE,
+    XML_SCHEMA_FACET_TOTALDIGITS,
+    XML_SCHEMA_FACET_FRACTIONDIGITS,
+    XML_SCHEMA_FACET_PATTERN,
+    XML_SCHEMA_FACET_ENUMERATION,
+    XML_SCHEMA_FACET_WHITESPACE,
+    XML_SCHEMA_FACET_LENGTH,
+    XML_SCHEMA_FACET_MAXLENGTH,
+    XML_SCHEMA_FACET_MINLENGTH,
+    XML_SCHEMA_EXTRA_QNAMEREF = 2000
+} xmlSchemaTypeType;
+
+typedef enum {
+    XML_SCHEMA_CONTENT_UNKNOWN = 0,
+    XML_SCHEMA_CONTENT_EMPTY = 1,
+    XML_SCHEMA_CONTENT_ELEMENTS,
+    XML_SCHEMA_CONTENT_MIXED,
+    XML_SCHEMA_CONTENT_SIMPLE,
+    XML_SCHEMA_CONTENT_MIXED_OR_ELEMENTS, /* obsolete, not used */
+    XML_SCHEMA_CONTENT_BASIC,
+    XML_SCHEMA_CONTENT_ANY
+} xmlSchemaContentType;
+
+typedef struct _xmlSchemaVal xmlSchemaVal;
+typedef xmlSchemaVal *xmlSchemaValPtr;
+
+typedef struct _xmlSchemaType xmlSchemaType;
+typedef xmlSchemaType *xmlSchemaTypePtr;
+
+typedef struct _xmlSchemaFacet xmlSchemaFacet;
+typedef xmlSchemaFacet *xmlSchemaFacetPtr;
+
+/**
+ * Annotation
+ */
+typedef struct _xmlSchemaAnnot xmlSchemaAnnot;
+typedef xmlSchemaAnnot *xmlSchemaAnnotPtr;
+struct _xmlSchemaAnnot {
+    struct _xmlSchemaAnnot *next;
+    xmlNodePtr content;         /* the annotation */
+};
+
+/**
+ * XML_SCHEMAS_ANYATTR_SKIP:
+ *
+ * Skip unknown attribute from validation
+ * Obsolete, not used anymore.
+ */
+#define XML_SCHEMAS_ANYATTR_SKIP        1
+/**
+ * XML_SCHEMAS_ANYATTR_LAX:
+ *
+ * Ignore validation non definition on attributes
+ * Obsolete, not used anymore.
+ */
+#define XML_SCHEMAS_ANYATTR_LAX                2
+/**
+ * XML_SCHEMAS_ANYATTR_STRICT:
+ *
+ * Apply strict validation rules on attributes
+ * Obsolete, not used anymore.
+ */
+#define XML_SCHEMAS_ANYATTR_STRICT        3
+/**
+ * XML_SCHEMAS_ANY_SKIP:
+ *
+ * Skip unknown attribute from validation
+ */
+#define XML_SCHEMAS_ANY_SKIP        1
+/**
+ * XML_SCHEMAS_ANY_LAX:
+ *
+ * Used by wildcards.
+ * Validate if type found, don't worry if not found
+ */
+#define XML_SCHEMAS_ANY_LAX                2
+/**
+ * XML_SCHEMAS_ANY_STRICT:
+ *
+ * Used by wildcards.
+ * Apply strict validation rules
+ */
+#define XML_SCHEMAS_ANY_STRICT        3
+/**
+ * XML_SCHEMAS_ATTR_USE_PROHIBITED:
+ *
+ * Used by wildcards.
+ * The attribute is prohibited.
+ */
+#define XML_SCHEMAS_ATTR_USE_PROHIBITED 0
+/**
+ * XML_SCHEMAS_ATTR_USE_REQUIRED:
+ *
+ * The attribute is required.
+ */
+#define XML_SCHEMAS_ATTR_USE_REQUIRED 1
+/**
+ * XML_SCHEMAS_ATTR_USE_OPTIONAL:
+ *
+ * The attribute is optional.
+ */
+#define XML_SCHEMAS_ATTR_USE_OPTIONAL 2
+/**
+ * XML_SCHEMAS_ATTR_GLOBAL:
+ *
+ * allow elements in no namespace
+ */
+#define XML_SCHEMAS_ATTR_GLOBAL        1 << 0
+/**
+ * XML_SCHEMAS_ATTR_NSDEFAULT:
+ *
+ * allow elements in no namespace
+ */
+#define XML_SCHEMAS_ATTR_NSDEFAULT        1 << 7
+/**
+ * XML_SCHEMAS_ATTR_INTERNAL_RESOLVED:
+ *
+ * this is set when the "type" and "ref" references
+ * have been resolved.
+ */
+#define XML_SCHEMAS_ATTR_INTERNAL_RESOLVED        1 << 8
+/**
+ * XML_SCHEMAS_ATTR_FIXED:
+ *
+ * the attribute has a fixed value
+ */
+#define XML_SCHEMAS_ATTR_FIXED        1 << 9
+
+/**
+ * xmlSchemaAttribute:
+ * An attribute definition.
+ */
+
+typedef struct _xmlSchemaAttribute xmlSchemaAttribute;
+typedef xmlSchemaAttribute *xmlSchemaAttributePtr;
+struct _xmlSchemaAttribute {
+    xmlSchemaTypeType type;        /* The kind of type */
+    struct _xmlSchemaAttribute *next;/* the next attribute if in a group ... */
+    const xmlChar *name; /* name of the declaration or empty if particle */
+    const xmlChar *id;
+    const xmlChar *ref; /* the local name of the attribute decl. if a particle */
+    const xmlChar *refNs; /* the ns URI of the attribute decl. if a particle */
+    const xmlChar *typeName; /* the local name of the type definition */
+    const xmlChar *typeNs; /* the ns URI of the type definition */
+    xmlSchemaAnnotPtr annot;
+
+    xmlSchemaTypePtr base; /* obsolete, not used */
+    int occurs;
+    const xmlChar *defValue;
+    xmlSchemaTypePtr subtypes; /* the type definition */
+    xmlNodePtr node;
+    const xmlChar *targetNamespace;
+    int flags;
+    const xmlChar *refPrefix;
+    xmlSchemaValPtr defVal;
+    xmlSchemaAttributePtr refDecl;
+};
+
+/**
+ * xmlSchemaAttributeLink:
+ * Used to build a list of attribute uses on complexType definitions.
+ */
+typedef struct _xmlSchemaAttributeLink xmlSchemaAttributeLink;
+typedef xmlSchemaAttributeLink *xmlSchemaAttributeLinkPtr;
+struct _xmlSchemaAttributeLink {
+    struct _xmlSchemaAttributeLink *next;/* the next attribute link ... */
+    struct _xmlSchemaAttribute *attr;/* the linked attribute */
+};
+
+/**
+ * XML_SCHEMAS_WILDCARD_COMPLETE:
+ *
+ * If the wildcard is complete.
+ */
+#define XML_SCHEMAS_WILDCARD_COMPLETE 1 << 0
+
+/**
+ * xmlSchemaCharValueLink:
+ * Used to build a list of namespaces on wildcards.
+ */
+typedef struct _xmlSchemaWildcardNs xmlSchemaWildcardNs;
+typedef xmlSchemaWildcardNs *xmlSchemaWildcardNsPtr;
+struct _xmlSchemaWildcardNs {
+    struct _xmlSchemaWildcardNs *next;/* the next constraint link ... */
+    const xmlChar *value;/* the value */
+};
+
+/**
+ * xmlSchemaWildcard.
+ * A wildcard.
+ */
+typedef struct _xmlSchemaWildcard xmlSchemaWildcard;
+typedef xmlSchemaWildcard *xmlSchemaWildcardPtr;
+struct _xmlSchemaWildcard {
+    xmlSchemaTypeType type;        /* The kind of type */
+    const xmlChar *id;
+    xmlSchemaAnnotPtr annot;
+    xmlNodePtr node;
+    int minOccurs;
+    int maxOccurs;
+    int processContents;
+    int any; /* Indicates if the ns constraint is of ##any */
+    xmlSchemaWildcardNsPtr nsSet; /* The list of allowed namespaces */
+    xmlSchemaWildcardNsPtr negNsSet; /* The negated namespace */
+    int flags;
+};
+
+/**
+ * XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED:
+ *
+ * The attribute wildcard has been already builded.
+ */
+#define XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED 1 << 0
+/**
+ * XML_SCHEMAS_ATTRGROUP_GLOBAL:
+ *
+ * The attribute wildcard has been already builded.
+ */
+#define XML_SCHEMAS_ATTRGROUP_GLOBAL 1 << 1
+/**
+ * XML_SCHEMAS_ATTRGROUP_MARKED:
+ *
+ * Marks the attr group as marked; used for circular checks.
+ */
+#define XML_SCHEMAS_ATTRGROUP_MARKED 1 << 2
+
+/**
+ * An attribute group definition.
+ *
+ * xmlSchemaAttribute and xmlSchemaAttributeGroup start of structures
+ * must be kept similar
+ */
+typedef struct _xmlSchemaAttributeGroup xmlSchemaAttributeGroup;
+typedef xmlSchemaAttributeGroup *xmlSchemaAttributeGroupPtr;
+struct _xmlSchemaAttributeGroup {
+    xmlSchemaTypeType type;        /* The kind of type */
+    struct _xmlSchemaAttribute *next;/* the next attribute if in a group ... */
+    const xmlChar *name;
+    const xmlChar *id;
+    const xmlChar *ref;
+    const xmlChar *refNs;
+    xmlSchemaAnnotPtr annot;
+
+    xmlSchemaAttributePtr attributes;
+    xmlNodePtr node;
+    int flags;
+    xmlSchemaWildcardPtr attributeWildcard;
+    const xmlChar *refPrefix;
+    xmlSchemaAttributeGroupPtr refItem; /* The referenced attribute group */
+    const xmlChar *targetNamespace;
+};
+
+/**
+ * xmlSchemaTypeLink:
+ * Used to build a list of types (e.g. member types of
+ * simpleType with variety "union").
+ */
+typedef struct _xmlSchemaTypeLink xmlSchemaTypeLink;
+typedef xmlSchemaTypeLink *xmlSchemaTypeLinkPtr;
+struct _xmlSchemaTypeLink {
+    struct _xmlSchemaTypeLink *next;/* the next type link ... */
+    xmlSchemaTypePtr type;/* the linked type*/
+};
+
+/**
+ * xmlSchemaFacetLink:
+ * Used to build a list of facets.
+ */
+typedef struct _xmlSchemaFacetLink xmlSchemaFacetLink;
+typedef xmlSchemaFacetLink *xmlSchemaFacetLinkPtr;
+struct _xmlSchemaFacetLink {
+    struct _xmlSchemaFacetLink *next;/* the next facet link ... */
+    xmlSchemaFacetPtr facet;/* the linked facet */
+};
+
+/**
+ * XML_SCHEMAS_TYPE_MIXED:
+ *
+ * the element content type is mixed
+ */
+#define XML_SCHEMAS_TYPE_MIXED                1 << 0
+/**
+ * XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION:
+ *
+ * the simple or complex type has a derivation method of "extension".
+ */
+#define XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION                1 << 1
+/**
+ * XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION:
+ *
+ * the simple or complex type has a derivation method of "restriction".
+ */
+#define XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION                1 << 2
+/**
+ * XML_SCHEMAS_TYPE_GLOBAL:
+ *
+ * the type is global
+ */
+#define XML_SCHEMAS_TYPE_GLOBAL                1 << 3
+/**
+ * XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD:
+ *
+ * the complexType owns an attribute wildcard, i.e.
+ * it can be freed by the complexType
+ */
+#define XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD    1 << 4 /* Obsolete. */
+/**
+ * XML_SCHEMAS_TYPE_VARIETY_ABSENT:
+ *
+ * the simpleType has a variety of "absent".
+ */
+#define XML_SCHEMAS_TYPE_VARIETY_ABSENT    1 << 5
+/**
+ * XML_SCHEMAS_TYPE_VARIETY_LIST:
+ *
+ * the simpleType has a variety of "list".
+ */
+#define XML_SCHEMAS_TYPE_VARIETY_LIST    1 << 6
+/**
+ * XML_SCHEMAS_TYPE_VARIETY_UNION:
+ *
+ * the simpleType has a variety of "union".
+ */
+#define XML_SCHEMAS_TYPE_VARIETY_UNION    1 << 7
+/**
+ * XML_SCHEMAS_TYPE_VARIETY_ATOMIC:
+ *
+ * the simpleType has a variety of "union".
+ */
+#define XML_SCHEMAS_TYPE_VARIETY_ATOMIC    1 << 8
+/**
+ * XML_SCHEMAS_TYPE_FINAL_EXTENSION:
+ *
+ * the complexType has a final of "extension".
+ */
+#define XML_SCHEMAS_TYPE_FINAL_EXTENSION    1 << 9
+/**
+ * XML_SCHEMAS_TYPE_FINAL_RESTRICTION:
+ *
+ * the simpleType/complexType has a final of "restriction".
+ */
+#define XML_SCHEMAS_TYPE_FINAL_RESTRICTION    1 << 10
+/**
+ * XML_SCHEMAS_TYPE_FINAL_LIST:
+ *
+ * the simpleType has a final of "list".
+ */
+#define XML_SCHEMAS_TYPE_FINAL_LIST    1 << 11
+/**
+ * XML_SCHEMAS_TYPE_FINAL_UNION:
+ *
+ * the simpleType has a final of "union".
+ */
+#define XML_SCHEMAS_TYPE_FINAL_UNION    1 << 12
+/**
+ * XML_SCHEMAS_TYPE_FINAL_DEFAULT:
+ *
+ * the simpleType has a final of "default".
+ */
+#define XML_SCHEMAS_TYPE_FINAL_DEFAULT    1 << 13
+/**
+ * XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE:
+ *
+ * Marks the item as a builtin primitive.
+ */
+#define XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE    1 << 14
+/**
+ * XML_SCHEMAS_TYPE_MARKED:
+ *
+ * Marks the item as marked; used for circular checks.
+ */
+#define XML_SCHEMAS_TYPE_MARKED        1 << 16
+/**
+ * XML_SCHEMAS_TYPE_BLOCK_DEFAULT:
+ *
+ * the complexType did not specify 'block' so use the default of the
+ * <schema> item.
+ */
+#define XML_SCHEMAS_TYPE_BLOCK_DEFAULT    1 << 17
+/**
+ * XML_SCHEMAS_TYPE_BLOCK_EXTENSION:
+ *
+ * the complexType has a 'block' of "extension".
+ */
+#define XML_SCHEMAS_TYPE_BLOCK_EXTENSION    1 << 18
+/**
+ * XML_SCHEMAS_TYPE_BLOCK_RESTRICTION:
+ *
+ * the complexType has a 'block' of "restriction".
+ */
+#define XML_SCHEMAS_TYPE_BLOCK_RESTRICTION    1 << 19
+/**
+ * XML_SCHEMAS_TYPE_ABSTRACT:
+ *
+ * the simple/complexType is abstract.
+ */
+#define XML_SCHEMAS_TYPE_ABSTRACT    1 << 20
+/**
+ * XML_SCHEMAS_TYPE_FACETSNEEDVALUE:
+ *
+ * indicates if the facets need a computed value
+ */
+#define XML_SCHEMAS_TYPE_FACETSNEEDVALUE    1 << 21
+/**
+ * XML_SCHEMAS_TYPE_INTERNAL_RESOLVED:
+ *
+ * indicates that the type was typefixed
+ */
+#define XML_SCHEMAS_TYPE_INTERNAL_RESOLVED    1 << 22
+/**
+ * XML_SCHEMAS_TYPE_INTERNAL_INVALID:
+ *
+ * indicates that the type is invalid
+ */
+#define XML_SCHEMAS_TYPE_INTERNAL_INVALID    1 << 23
+
+
+/**
+ * _xmlSchemaType:
+ *
+ * Schemas type definition.
+ */
+struct _xmlSchemaType {
+    xmlSchemaTypeType type;        /* The kind of type */
+    struct _xmlSchemaType *next;/* the next type if in a sequence ... */
+    const xmlChar *name;
+    const xmlChar *id;
+    const xmlChar *ref;
+    const xmlChar *refNs;
+    xmlSchemaAnnotPtr annot;
+    xmlSchemaTypePtr subtypes;
+    xmlSchemaAttributePtr attributes;
+    xmlNodePtr node;
+    int minOccurs;
+    int maxOccurs;
+
+    int flags;
+    xmlSchemaContentType contentType;
+    const xmlChar *base;
+    const xmlChar *baseNs;
+    xmlSchemaTypePtr baseType;
+    xmlSchemaFacetPtr facets;
+    struct _xmlSchemaType *redef;/* possible redefinitions for the type */
+    int recurse;
+    xmlSchemaAttributeLinkPtr attributeUses;
+    xmlSchemaWildcardPtr attributeWildcard;
+    int builtInType;
+    xmlSchemaTypeLinkPtr memberTypes;
+    xmlSchemaFacetLinkPtr facetSet;
+    const xmlChar *refPrefix;
+    xmlSchemaTypePtr contentTypeDef;
+    xmlRegexpPtr contModel;
+    const xmlChar *targetNamespace;
+};
+
+/*
+ * xmlSchemaElement:
+ * An element definition.
+ *
+ * xmlSchemaType, xmlSchemaFacet and xmlSchemaElement start of
+ * structures must be kept similar
+ */
+/**
+ * XML_SCHEMAS_ELEM_NILLABLE:
+ *
+ * the element is nillable
+ */
+#define XML_SCHEMAS_ELEM_NILLABLE        1 << 0
+/**
+ * XML_SCHEMAS_ELEM_GLOBAL:
+ *
+ * the element is global
+ */
+#define XML_SCHEMAS_ELEM_GLOBAL                1 << 1
+/**
+ * XML_SCHEMAS_ELEM_DEFAULT:
+ *
+ * the element has a default value
+ */
+#define XML_SCHEMAS_ELEM_DEFAULT        1 << 2
+/**
+ * XML_SCHEMAS_ELEM_FIXED:
+ *
+ * the element has a fixed value
+ */
+#define XML_SCHEMAS_ELEM_FIXED                1 << 3
+/**
+ * XML_SCHEMAS_ELEM_ABSTRACT:
+ *
+ * the element is abstract
+ */
+#define XML_SCHEMAS_ELEM_ABSTRACT        1 << 4
+/**
+ * XML_SCHEMAS_ELEM_TOPLEVEL:
+ *
+ * the element is top level
+ * obsolete: use XML_SCHEMAS_ELEM_GLOBAL instead
+ */
+#define XML_SCHEMAS_ELEM_TOPLEVEL        1 << 5
+/**
+ * XML_SCHEMAS_ELEM_REF:
+ *
+ * the element is a reference to a type
+ */
+#define XML_SCHEMAS_ELEM_REF                1 << 6
+/**
+ * XML_SCHEMAS_ELEM_NSDEFAULT:
+ *
+ * allow elements in no namespace
+ * Obsolete, not used anymore.
+ */
+#define XML_SCHEMAS_ELEM_NSDEFAULT        1 << 7
+/**
+ * XML_SCHEMAS_ELEM_INTERNAL_RESOLVED:
+ *
+ * this is set when "type", "ref", "substitutionGroup"
+ * references have been resolved.
+ */
+#define XML_SCHEMAS_ELEM_INTERNAL_RESOLVED        1 << 8
+ /**
+ * XML_SCHEMAS_ELEM_CIRCULAR:
+ *
+ * a helper flag for the search of circular references.
+ */
+#define XML_SCHEMAS_ELEM_CIRCULAR        1 << 9
+/**
+ * XML_SCHEMAS_ELEM_BLOCK_ABSENT:
+ *
+ * the "block" attribute is absent
+ */
+#define XML_SCHEMAS_ELEM_BLOCK_ABSENT        1 << 10
+/**
+ * XML_SCHEMAS_ELEM_BLOCK_EXTENSION:
+ *
+ * disallowed substitutions are absent
+ */
+#define XML_SCHEMAS_ELEM_BLOCK_EXTENSION        1 << 11
+/**
+ * XML_SCHEMAS_ELEM_BLOCK_RESTRICTION:
+ *
+ * disallowed substitutions: "restriction"
+ */
+#define XML_SCHEMAS_ELEM_BLOCK_RESTRICTION        1 << 12
+/**
+ * XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION:
+ *
+ * disallowed substitutions: "substituion"
+ */
+#define XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION        1 << 13
+/**
+ * XML_SCHEMAS_ELEM_FINAL_ABSENT:
+ *
+ * substitution group exclusions are absent
+ */
+#define XML_SCHEMAS_ELEM_FINAL_ABSENT        1 << 14
+/**
+ * XML_SCHEMAS_ELEM_FINAL_EXTENSION:
+ *
+ * substitution group exclusions: "extension"
+ */
+#define XML_SCHEMAS_ELEM_FINAL_EXTENSION        1 << 15
+/**
+ * XML_SCHEMAS_ELEM_FINAL_RESTRICTION:
+ *
+ * substitution group exclusions: "restriction"
+ */
+#define XML_SCHEMAS_ELEM_FINAL_RESTRICTION        1 << 16
+
+
+typedef struct _xmlSchemaElement xmlSchemaElement;
+typedef xmlSchemaElement *xmlSchemaElementPtr;
+struct _xmlSchemaElement {
+    xmlSchemaTypeType type;        /* The kind of type */
+    struct _xmlSchemaType *next;/* the next type if in a sequence ... */
+    const xmlChar *name;
+    const xmlChar *id;
+    const xmlChar *ref; /* the local name of the element declaration if a particle */
+    const xmlChar *refNs; /* the ns URI of the element declaration if a particle */
+    xmlSchemaAnnotPtr annot;
+    xmlSchemaTypePtr subtypes; /* the type definition */
+    xmlSchemaAttributePtr attributes;
+    xmlNodePtr node;
+    int minOccurs;
+    int maxOccurs;
+
+    int flags;
+    const xmlChar *targetNamespace;
+    const xmlChar *namedType;
+    const xmlChar *namedTypeNs;
+    const xmlChar *substGroup;
+    const xmlChar *substGroupNs;
+    const xmlChar *scope;
+    const xmlChar *value;
+    struct _xmlSchemaElement *refDecl; /* the element declaration if a particle */
+    xmlRegexpPtr contModel;
+    xmlSchemaContentType contentType;
+    const xmlChar *refPrefix;
+    xmlSchemaValPtr defVal;
+    void *idcs;
+};
+
+/*
+ * XML_SCHEMAS_FACET_UNKNOWN:
+ *
+ * unknown facet handling
+ */
+#define XML_SCHEMAS_FACET_UNKNOWN        0
+/*
+ * XML_SCHEMAS_FACET_PRESERVE:
+ *
+ * preserve the type of the facet
+ */
+#define XML_SCHEMAS_FACET_PRESERVE        1
+/*
+ * XML_SCHEMAS_FACET_REPLACE:
+ *
+ * replace the type of the facet
+ */
+#define XML_SCHEMAS_FACET_REPLACE        2
+/*
+ * XML_SCHEMAS_FACET_COLLAPSE:
+ *
+ * collapse the types of the facet
+ */
+#define XML_SCHEMAS_FACET_COLLAPSE        3
+/**
+ * A facet definition.
+ */
+struct _xmlSchemaFacet {
+    xmlSchemaTypeType type;        /* The kind of type */
+    struct _xmlSchemaFacet *next;/* the next type if in a sequence ... */
+    const xmlChar *value;
+    const xmlChar *id;
+    xmlSchemaAnnotPtr annot;
+    xmlNodePtr node;
+    int fixed;
+    int whitespace;
+    xmlSchemaValPtr val;
+    xmlRegexpPtr    regexp;
+};
+
+/**
+ * A notation definition.
+ */
+typedef struct _xmlSchemaNotation xmlSchemaNotation;
+typedef xmlSchemaNotation *xmlSchemaNotationPtr;
+struct _xmlSchemaNotation {
+    xmlSchemaTypeType type;        /* The kind of type */
+    const xmlChar *name;
+    xmlSchemaAnnotPtr annot;
+    const xmlChar *identifier;
+    const xmlChar *targetNamespace;
+};
+
+/**
+ * XML_SCHEMAS_QUALIF_ELEM:
+ *
+ * the schema requires qualified elements
+ */
+#define XML_SCHEMAS_QUALIF_ELEM                1 << 0
+/**
+ * XML_SCHEMAS_QUALIF_ATTR:
+ *
+ * the schema requires qualified attributes
+ */
+#define XML_SCHEMAS_QUALIF_ATTR            1 << 1
+/**
+ * XML_SCHEMAS_FINAL_DEFAULT_EXTENSION:
+ *
+ * the schema has "extension" in the set of finalDefault.
+ */
+#define XML_SCHEMAS_FINAL_DEFAULT_EXTENSION        1 << 2
+/**
+ * XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION:
+ *
+ * the schema has "restriction" in the set of finalDefault.
+ */
+#define XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION            1 << 3
+/**
+ * XML_SCHEMAS_FINAL_DEFAULT_LIST:
+ *
+ * the cshema has "list" in the set of finalDefault.
+ */
+#define XML_SCHEMAS_FINAL_DEFAULT_LIST            1 << 4
+/**
+ * XML_SCHEMAS_FINAL_DEFAULT_UNION:
+ *
+ * the schema has "union" in the set of finalDefault.
+ */
+#define XML_SCHEMAS_FINAL_DEFAULT_UNION            1 << 5
+/**
+ * XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION:
+ *
+ * the schema has "extension" in the set of blockDefault.
+ */
+#define XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION            1 << 6
+/**
+ * XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION:
+ *
+ * the schema has "restriction" in the set of blockDefault.
+ */
+#define XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION            1 << 7
+/**
+ * XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION:
+ *
+ * the schema has "substitution" in the set of blockDefault.
+ */
+#define XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION            1 << 8
+/**
+ * XML_SCHEMAS_INCLUDING_CONVERT_NS:
+ *
+ * the schema is currently including an other schema with
+ * no target namespace.
+ */
+#define XML_SCHEMAS_INCLUDING_CONVERT_NS            1 << 9
+/**
+ * _xmlSchema:
+ *
+ * A Schemas definition
+ */
+struct _xmlSchema {
+    const xmlChar *name;        /* schema name */
+    const xmlChar *targetNamespace;     /* the target namespace */
+    const xmlChar *version;
+    const xmlChar *id;
+    xmlDocPtr doc;
+    xmlSchemaAnnotPtr annot;
+    int flags;
+
+    xmlHashTablePtr typeDecl;
+    xmlHashTablePtr attrDecl;
+    xmlHashTablePtr attrgrpDecl;
+    xmlHashTablePtr elemDecl;
+    xmlHashTablePtr notaDecl;
+
+    xmlHashTablePtr schemasImports;
+
+    void *_private;        /* unused by the library for users or bindings */
+    xmlHashTablePtr groupDecl;
+    xmlDictPtr      dict;
+    void *includes;     /* the includes, this is opaque for now */
+    int preserve;        /* whether to free the document */
+    int counter; /* used to give ononymous components unique names */
+    xmlHashTablePtr idcDef;
+    void *volatiles; /* Misc. helper items (e.g. reference items) */
+};
+
+XMLPUBFUN void XMLCALL         xmlSchemaFreeType        (xmlSchemaTypePtr type);
+XMLPUBFUN void XMLCALL         xmlSchemaFreeWildcard(xmlSchemaWildcardPtr wildcard);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_SCHEMAS_ENABLED */
+#endif /* __XML_SCHEMA_INTERNALS_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/threads.h ./aperios/include/libxml2/libxml/threads.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/threads.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/threads.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,81 @@
+/**
+ * Summary: interfaces for thread handling
+ * Description: set of generic threading related routines
+ *              should work with pthreads, Windows native or TLS threads
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_THREADS_H__
+#define __XML_THREADS_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * xmlMutex are a simple mutual exception locks.
+ */
+typedef struct _xmlMutex xmlMutex;
+typedef xmlMutex *xmlMutexPtr;
+
+/*
+ * xmlRMutex are reentrant mutual exception locks.
+ */
+typedef struct _xmlRMutex xmlRMutex;
+typedef xmlRMutex *xmlRMutexPtr;
+
+#ifdef __cplusplus
+}
+#endif
+#include <libxml/globals.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+XMLPUBFUN xmlMutexPtr XMLCALL		
+			xmlNewMutex	(void);
+XMLPUBFUN void XMLCALL			
+			xmlMutexLock	(xmlMutexPtr tok);
+XMLPUBFUN void XMLCALL			
+			xmlMutexUnlock	(xmlMutexPtr tok);
+XMLPUBFUN void XMLCALL			
+			xmlFreeMutex	(xmlMutexPtr tok);
+
+XMLPUBFUN xmlRMutexPtr XMLCALL		
+			xmlNewRMutex	(void);
+XMLPUBFUN void XMLCALL			
+			xmlRMutexLock	(xmlRMutexPtr tok);
+XMLPUBFUN void XMLCALL			
+			xmlRMutexUnlock	(xmlRMutexPtr tok);
+XMLPUBFUN void XMLCALL			
+			xmlFreeRMutex	(xmlRMutexPtr tok);
+
+/*
+ * Library wide APIs.
+ */
+XMLPUBFUN void XMLCALL			
+			xmlInitThreads	(void);
+XMLPUBFUN void XMLCALL			
+			xmlLockLibrary	(void);
+XMLPUBFUN void XMLCALL			
+			xmlUnlockLibrary(void);
+XMLPUBFUN int XMLCALL			
+			xmlGetThreadId	(void);
+XMLPUBFUN int XMLCALL			
+			xmlIsMainThread	(void);
+XMLPUBFUN void XMLCALL			
+			xmlCleanupThreads(void);
+XMLPUBFUN xmlGlobalStatePtr XMLCALL	
+			xmlGetGlobalState(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* __XML_THREADS_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/tree.h ./aperios/include/libxml2/libxml/tree.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/tree.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/tree.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,1125 @@
+/*
+ * Summary: interfaces for tree manipulation
+ * Description: this module describes the structures found in an tree resulting
+ *              from an XML or HTML parsing, as well as the API provided for
+ *              various processing on that tree
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_TREE_H__
+#define __XML_TREE_H__
+
+#include <stdio.h>
+#include <libxml/xmlversion.h>
+#include <libxml/xmlstring.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Some of the basic types pointer to structures:
+ */
+/* xmlIO.h */
+typedef struct _xmlParserInputBuffer xmlParserInputBuffer;
+typedef xmlParserInputBuffer *xmlParserInputBufferPtr;
+
+typedef struct _xmlOutputBuffer xmlOutputBuffer;
+typedef xmlOutputBuffer *xmlOutputBufferPtr;
+
+/* parser.h */
+typedef struct _xmlParserInput xmlParserInput;
+typedef xmlParserInput *xmlParserInputPtr;
+
+typedef struct _xmlParserCtxt xmlParserCtxt;
+typedef xmlParserCtxt *xmlParserCtxtPtr;
+
+typedef struct _xmlSAXLocator xmlSAXLocator;
+typedef xmlSAXLocator *xmlSAXLocatorPtr;
+
+typedef struct _xmlSAXHandler xmlSAXHandler;
+typedef xmlSAXHandler *xmlSAXHandlerPtr;
+
+/* entities.h */
+typedef struct _xmlEntity xmlEntity;
+typedef xmlEntity *xmlEntityPtr;
+
+/**
+ * BASE_BUFFER_SIZE:
+ *
+ * default buffer size 4000.
+ */
+#define BASE_BUFFER_SIZE 4096
+
+/**
+ * XML_XML_NAMESPACE:
+ *
+ * This is the namespace for the special xml: prefix predefined in the
+ * XML Namespace specification.
+ */
+#define XML_XML_NAMESPACE \
+    (const xmlChar *) "http://www.w3.org/XML/1998/namespace"
+
+/**
+ * XML_XML_ID:
+ *
+ * This is the name for the special xml:id attribute
+ */
+#define XML_XML_ID (const xmlChar *) "xml:id"
+
+/*
+ * The different element types carried by an XML tree.
+ *
+ * NOTE: This is synchronized with DOM Level1 values
+ *       See http://www.w3.org/TR/REC-DOM-Level-1/
+ *
+ * Actually this had diverged a bit, and now XML_DOCUMENT_TYPE_NODE should
+ * be deprecated to use an XML_DTD_NODE.
+ */
+typedef enum {
+    XML_ELEMENT_NODE=		1,
+    XML_ATTRIBUTE_NODE=		2,
+    XML_TEXT_NODE=		3,
+    XML_CDATA_SECTION_NODE=	4,
+    XML_ENTITY_REF_NODE=	5,
+    XML_ENTITY_NODE=		6,
+    XML_PI_NODE=		7,
+    XML_COMMENT_NODE=		8,
+    XML_DOCUMENT_NODE=		9,
+    XML_DOCUMENT_TYPE_NODE=	10,
+    XML_DOCUMENT_FRAG_NODE=	11,
+    XML_NOTATION_NODE=		12,
+    XML_HTML_DOCUMENT_NODE=	13,
+    XML_DTD_NODE=		14,
+    XML_ELEMENT_DECL=		15,
+    XML_ATTRIBUTE_DECL=		16,
+    XML_ENTITY_DECL=		17,
+    XML_NAMESPACE_DECL=		18,
+    XML_XINCLUDE_START=		19,
+    XML_XINCLUDE_END=		20
+#ifdef LIBXML_DOCB_ENABLED
+   ,XML_DOCB_DOCUMENT_NODE=	21
+#endif
+} xmlElementType;
+
+
+/**
+ * xmlNotation:
+ *
+ * A DTD Notation definition.
+ */
+
+typedef struct _xmlNotation xmlNotation;
+typedef xmlNotation *xmlNotationPtr;
+struct _xmlNotation {
+    const xmlChar               *name;	        /* Notation name */
+    const xmlChar               *PublicID;	/* Public identifier, if any */
+    const xmlChar               *SystemID;	/* System identifier, if any */
+};
+
+/**
+ * xmlAttributeType:
+ *
+ * A DTD Attribute type definition.
+ */
+
+typedef enum {
+    XML_ATTRIBUTE_CDATA = 1,
+    XML_ATTRIBUTE_ID,
+    XML_ATTRIBUTE_IDREF	,
+    XML_ATTRIBUTE_IDREFS,
+    XML_ATTRIBUTE_ENTITY,
+    XML_ATTRIBUTE_ENTITIES,
+    XML_ATTRIBUTE_NMTOKEN,
+    XML_ATTRIBUTE_NMTOKENS,
+    XML_ATTRIBUTE_ENUMERATION,
+    XML_ATTRIBUTE_NOTATION
+} xmlAttributeType;
+
+/**
+ * xmlAttributeDefault:
+ *
+ * A DTD Attribute default definition.
+ */
+
+typedef enum {
+    XML_ATTRIBUTE_NONE = 1,
+    XML_ATTRIBUTE_REQUIRED,
+    XML_ATTRIBUTE_IMPLIED,
+    XML_ATTRIBUTE_FIXED
+} xmlAttributeDefault;
+
+/**
+ * xmlEnumeration:
+ *
+ * List structure used when there is an enumeration in DTDs.
+ */
+
+typedef struct _xmlEnumeration xmlEnumeration;
+typedef xmlEnumeration *xmlEnumerationPtr;
+struct _xmlEnumeration {
+    struct _xmlEnumeration    *next;	/* next one */
+    const xmlChar            *name;	/* Enumeration name */
+};
+
+/**
+ * xmlAttribute:
+ *
+ * An Attribute declaration in a DTD.
+ */
+
+typedef struct _xmlAttribute xmlAttribute;
+typedef xmlAttribute *xmlAttributePtr;
+struct _xmlAttribute {
+    void           *_private;	        /* application data */
+    xmlElementType          type;       /* XML_ATTRIBUTE_DECL, must be second ! */
+    const xmlChar          *name;	/* Attribute name */
+    struct _xmlNode    *children;	/* NULL */
+    struct _xmlNode        *last;	/* NULL */
+    struct _xmlDtd       *parent;	/* -> DTD */
+    struct _xmlNode        *next;	/* next sibling link  */
+    struct _xmlNode        *prev;	/* previous sibling link  */
+    struct _xmlDoc          *doc;       /* the containing document */
+
+    struct _xmlAttribute  *nexth;	/* next in hash table */
+    xmlAttributeType       atype;	/* The attribute type */
+    xmlAttributeDefault      def;	/* the default */
+    const xmlChar  *defaultValue;	/* or the default value */
+    xmlEnumerationPtr       tree;       /* or the enumeration tree if any */
+    const xmlChar        *prefix;	/* the namespace prefix if any */
+    const xmlChar          *elem;	/* Element holding the attribute */
+};
+
+/**
+ * xmlElementContentType:
+ *
+ * Possible definitions of element content types.
+ */
+typedef enum {
+    XML_ELEMENT_CONTENT_PCDATA = 1,
+    XML_ELEMENT_CONTENT_ELEMENT,
+    XML_ELEMENT_CONTENT_SEQ,
+    XML_ELEMENT_CONTENT_OR
+} xmlElementContentType;
+
+/**
+ * xmlElementContentOccur:
+ *
+ * Possible definitions of element content occurrences.
+ */
+typedef enum {
+    XML_ELEMENT_CONTENT_ONCE = 1,
+    XML_ELEMENT_CONTENT_OPT,
+    XML_ELEMENT_CONTENT_MULT,
+    XML_ELEMENT_CONTENT_PLUS
+} xmlElementContentOccur;
+
+/**
+ * xmlElementContent:
+ *
+ * An XML Element content as stored after parsing an element definition
+ * in a DTD.
+ */
+
+typedef struct _xmlElementContent xmlElementContent;
+typedef xmlElementContent *xmlElementContentPtr;
+struct _xmlElementContent {
+    xmlElementContentType     type;	/* PCDATA, ELEMENT, SEQ or OR */
+    xmlElementContentOccur    ocur;	/* ONCE, OPT, MULT or PLUS */
+    const xmlChar             *name;	/* Element name */
+    struct _xmlElementContent *c1;	/* first child */
+    struct _xmlElementContent *c2;	/* second child */
+    struct _xmlElementContent *parent;	/* parent */
+    const xmlChar             *prefix;	/* Namespace prefix */
+};
+
+/**
+ * xmlElementTypeVal:
+ *
+ * The different possibilities for an element content type.
+ */
+
+typedef enum {
+    XML_ELEMENT_TYPE_UNDEFINED = 0,
+    XML_ELEMENT_TYPE_EMPTY = 1,
+    XML_ELEMENT_TYPE_ANY,
+    XML_ELEMENT_TYPE_MIXED,
+    XML_ELEMENT_TYPE_ELEMENT
+} xmlElementTypeVal;
+
+
+#ifdef __cplusplus
+}
+#endif
+#include <libxml/xmlregexp.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlElement:
+ *
+ * An XML Element declaration from a DTD.
+ */
+
+typedef struct _xmlElement xmlElement;
+typedef xmlElement *xmlElementPtr;
+struct _xmlElement {
+    void           *_private;	        /* application data */
+    xmlElementType          type;       /* XML_ELEMENT_DECL, must be second ! */
+    const xmlChar          *name;	/* Element name */
+    struct _xmlNode    *children;	/* NULL */
+    struct _xmlNode        *last;	/* NULL */
+    struct _xmlDtd       *parent;	/* -> DTD */
+    struct _xmlNode        *next;	/* next sibling link  */
+    struct _xmlNode        *prev;	/* previous sibling link  */
+    struct _xmlDoc          *doc;       /* the containing document */
+
+    xmlElementTypeVal      etype;	/* The type */
+    xmlElementContentPtr content;	/* the allowed element content */
+    xmlAttributePtr   attributes;	/* List of the declared attributes */
+    const xmlChar        *prefix;	/* the namespace prefix if any */
+#ifdef LIBXML_REGEXP_ENABLED
+    xmlRegexpPtr       contModel;	/* the validating regexp */
+#else
+    void	      *contModel;
+#endif
+};
+
+
+/**
+ * XML_LOCAL_NAMESPACE:
+ *
+ * A namespace declaration node.
+ */
+#define XML_LOCAL_NAMESPACE XML_NAMESPACE_DECL
+typedef xmlElementType xmlNsType;
+
+/**
+ * xmlNs:
+ *
+ * An XML namespace.
+ * Note that prefix == NULL is valid, it defines the default namespace
+ * within the subtree (until overridden).
+ *
+ * xmlNsType is unified with xmlElementType.
+ */
+
+typedef struct _xmlNs xmlNs;
+typedef xmlNs *xmlNsPtr;
+struct _xmlNs {
+    struct _xmlNs  *next;	/* next Ns link for this node  */
+    xmlNsType      type;	/* global or local */
+    const xmlChar *href;	/* URL for the namespace */
+    const xmlChar *prefix;	/* prefix for the namespace */
+    void           *_private;   /* application data */
+};
+
+/**
+ * xmlDtd:
+ *
+ * An XML DTD, as defined by <!DOCTYPE ... There is actually one for
+ * the internal subset and for the external subset.
+ */
+typedef struct _xmlDtd xmlDtd;
+typedef xmlDtd *xmlDtdPtr;
+struct _xmlDtd {
+    void           *_private;	/* application data */
+    xmlElementType  type;       /* XML_DTD_NODE, must be second ! */
+    const xmlChar *name;	/* Name of the DTD */
+    struct _xmlNode *children;	/* the value of the property link */
+    struct _xmlNode *last;	/* last child link */
+    struct _xmlDoc  *parent;	/* child->parent link */
+    struct _xmlNode *next;	/* next sibling link  */
+    struct _xmlNode *prev;	/* previous sibling link  */
+    struct _xmlDoc  *doc;	/* the containing document */
+
+    /* End of common part */
+    void          *notations;   /* Hash table for notations if any */
+    void          *elements;    /* Hash table for elements if any */
+    void          *attributes;  /* Hash table for attributes if any */
+    void          *entities;    /* Hash table for entities if any */
+    const xmlChar *ExternalID;	/* External identifier for PUBLIC DTD */
+    const xmlChar *SystemID;	/* URI for a SYSTEM or PUBLIC DTD */
+    void          *pentities;   /* Hash table for param entities if any */
+};
+
+/**
+ * xmlAttr:
+ *
+ * An attribute on an XML node.
+ */
+typedef struct _xmlAttr xmlAttr;
+typedef xmlAttr *xmlAttrPtr;
+struct _xmlAttr {
+    void           *_private;	/* application data */
+    xmlElementType   type;      /* XML_ATTRIBUTE_NODE, must be second ! */
+    const xmlChar   *name;      /* the name of the property */
+    struct _xmlNode *children;	/* the value of the property */
+    struct _xmlNode *last;	/* NULL */
+    struct _xmlNode *parent;	/* child->parent link */
+    struct _xmlAttr *next;	/* next sibling link  */
+    struct _xmlAttr *prev;	/* previous sibling link  */
+    struct _xmlDoc  *doc;	/* the containing document */
+    xmlNs           *ns;        /* pointer to the associated namespace */
+    xmlAttributeType atype;     /* the attribute type if validating */
+    void            *psvi;	/* for type/PSVI informations */
+};
+
+/**
+ * xmlID:
+ *
+ * An XML ID instance.
+ */
+
+typedef struct _xmlID xmlID;
+typedef xmlID *xmlIDPtr;
+struct _xmlID {
+    struct _xmlID    *next;	/* next ID */
+    const xmlChar    *value;	/* The ID name */
+    xmlAttrPtr        attr;	/* The attribute holding it */
+    const xmlChar    *name;	/* The attribute if attr is not available */
+    int               lineno;	/* The line number if attr is not available */
+    struct _xmlDoc   *doc;	/* The document holding the ID */
+};
+
+/**
+ * xmlRef:
+ *
+ * An XML IDREF instance.
+ */
+
+typedef struct _xmlRef xmlRef;
+typedef xmlRef *xmlRefPtr;
+struct _xmlRef {
+    struct _xmlRef    *next;	/* next Ref */
+    const xmlChar     *value;	/* The Ref name */
+    xmlAttrPtr        attr;	/* The attribute holding it */
+    const xmlChar    *name;	/* The attribute if attr is not available */
+    int               lineno;	/* The line number if attr is not available */
+};
+
+/**
+ * xmlBufferAllocationScheme:
+ *
+ * A buffer allocation scheme can be defined to either match exactly the
+ * need or double it's allocated size each time it is found too small.
+ */
+
+typedef enum {
+    XML_BUFFER_ALLOC_DOUBLEIT,
+    XML_BUFFER_ALLOC_EXACT,
+    XML_BUFFER_ALLOC_IMMUTABLE
+} xmlBufferAllocationScheme;
+
+/**
+ * xmlBuffer:
+ *
+ * A buffer structure.
+ */
+typedef struct _xmlBuffer xmlBuffer;
+typedef xmlBuffer *xmlBufferPtr;
+struct _xmlBuffer {
+    xmlChar *content;		/* The buffer content UTF8 */
+    unsigned int use;		/* The buffer size used */
+    unsigned int size;		/* The buffer size */
+    xmlBufferAllocationScheme alloc; /* The realloc method */
+};
+
+/**
+ * xmlNode:
+ *
+ * A node in an XML tree.
+ */
+typedef struct _xmlNode xmlNode;
+typedef xmlNode *xmlNodePtr;
+struct _xmlNode {
+    void           *_private;	/* application data */
+    xmlElementType   type;	/* type number, must be second ! */
+    const xmlChar   *name;      /* the name of the node, or the entity */
+    struct _xmlNode *children;	/* parent->childs link */
+    struct _xmlNode *last;	/* last child link */
+    struct _xmlNode *parent;	/* child->parent link */
+    struct _xmlNode *next;	/* next sibling link  */
+    struct _xmlNode *prev;	/* previous sibling link  */
+    struct _xmlDoc  *doc;	/* the containing document */
+
+    /* End of common part */
+    xmlNs           *ns;        /* pointer to the associated namespace */
+    xmlChar         *content;   /* the content */
+    struct _xmlAttr *properties;/* properties list */
+    xmlNs           *nsDef;     /* namespace definitions on this node */
+    void            *psvi;	/* for type/PSVI informations */
+    unsigned short   line;	/* line number */
+    unsigned short   extra;	/* extra data for XPath/XSLT */
+};
+
+/**
+ * XML_GET_CONTENT:
+ *
+ * Macro to extract the content pointer of a node.
+ */
+#define XML_GET_CONTENT(n)					\
+    ((n)->type == XML_ELEMENT_NODE ? NULL : (n)->content)
+
+/**
+ * XML_GET_LINE:
+ *
+ * Macro to extract the line number of an element node. 
+ */
+#define XML_GET_LINE(n)						\
+    (xmlGetLineNo(n))
+
+
+/**
+ * xmlDoc:
+ *
+ * An XML document.
+ */
+typedef struct _xmlDoc xmlDoc;
+typedef xmlDoc *xmlDocPtr;
+struct _xmlDoc {
+    void           *_private;	/* application data */
+    xmlElementType  type;       /* XML_DOCUMENT_NODE, must be second ! */
+    char           *name;	/* name/filename/URI of the document */
+    struct _xmlNode *children;	/* the document tree */
+    struct _xmlNode *last;	/* last child link */
+    struct _xmlNode *parent;	/* child->parent link */
+    struct _xmlNode *next;	/* next sibling link  */
+    struct _xmlNode *prev;	/* previous sibling link  */
+    struct _xmlDoc  *doc;	/* autoreference to itself */
+
+    /* End of common part */
+    int             compression;/* level of zlib compression */
+    int             standalone; /* standalone document (no external refs) */
+    struct _xmlDtd  *intSubset;	/* the document internal subset */
+    struct _xmlDtd  *extSubset;	/* the document external subset */
+    struct _xmlNs   *oldNs;	/* Global namespace, the old way */
+    const xmlChar  *version;	/* the XML version string */
+    const xmlChar  *encoding;   /* external initial encoding, if any */
+    void           *ids;        /* Hash table for ID attributes if any */
+    void           *refs;       /* Hash table for IDREFs attributes if any */
+    const xmlChar  *URL;	/* The URI for that document */
+    int             charset;    /* encoding of the in-memory content
+				   actually an xmlCharEncoding */
+    struct _xmlDict *dict;      /* dict used to allocate names or NULL */
+    void           *psvi;	/* for type/PSVI informations */
+};
+
+/**
+ * xmlChildrenNode:
+ *
+ * Macro for compatibility naming layer with libxml1. Maps
+ * to "children."
+ */
+#ifndef xmlChildrenNode
+#define xmlChildrenNode children
+#endif
+
+/**
+ * xmlRootNode:
+ *
+ * Macro for compatibility naming layer with libxml1. Maps 
+ * to "children".
+ */
+#ifndef xmlRootNode
+#define xmlRootNode children
+#endif
+
+/*
+ * Variables.
+ */
+
+/*
+ * Some helper functions
+ */
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_DEBUG_ENABLED)
+XMLPUBFUN int XMLCALL
+		xmlValidateNCName	(const xmlChar *value,
+					 int space);
+#endif
+
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN int XMLCALL		
+		xmlValidateQName	(const xmlChar *value,
+					 int space);
+XMLPUBFUN int XMLCALL		
+		xmlValidateName		(const xmlChar *value,
+					 int space);
+XMLPUBFUN int XMLCALL		
+		xmlValidateNMToken	(const xmlChar *value,
+					 int space);
+#endif
+
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlBuildQName		(const xmlChar *ncname,
+					 const xmlChar *prefix,
+					 xmlChar *memory,
+					 int len);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlSplitQName2		(const xmlChar *name,
+					 xmlChar **prefix);
+XMLPUBFUN const xmlChar * XMLCALL	
+		xmlSplitQName3		(const xmlChar *name,
+					 int *len);
+
+/*
+ * Handling Buffers.
+ */
+
+XMLPUBFUN void XMLCALL		
+		xmlSetBufferAllocationScheme(xmlBufferAllocationScheme scheme);
+XMLPUBFUN xmlBufferAllocationScheme XMLCALL	 
+		xmlGetBufferAllocationScheme(void);
+
+XMLPUBFUN xmlBufferPtr XMLCALL	
+		xmlBufferCreate		(void);
+XMLPUBFUN xmlBufferPtr XMLCALL	
+		xmlBufferCreateSize	(size_t size);
+XMLPUBFUN xmlBufferPtr XMLCALL	
+		xmlBufferCreateStatic	(void *mem,
+					 size_t size);
+XMLPUBFUN int XMLCALL		
+		xmlBufferResize		(xmlBufferPtr buf,
+					 unsigned int size);
+XMLPUBFUN void XMLCALL		
+		xmlBufferFree		(xmlBufferPtr buf);
+XMLPUBFUN int XMLCALL		
+		xmlBufferDump		(FILE *file,
+					 xmlBufferPtr buf);
+XMLPUBFUN int XMLCALL		
+		xmlBufferAdd		(xmlBufferPtr buf,
+					 const xmlChar *str,
+					 int len);
+XMLPUBFUN int XMLCALL		
+		xmlBufferAddHead	(xmlBufferPtr buf,
+					 const xmlChar *str,
+					 int len);
+XMLPUBFUN int XMLCALL		
+		xmlBufferCat		(xmlBufferPtr buf,
+					 const xmlChar *str);
+XMLPUBFUN int XMLCALL	
+		xmlBufferCCat		(xmlBufferPtr buf,
+					 const char *str);
+XMLPUBFUN int XMLCALL		
+		xmlBufferShrink		(xmlBufferPtr buf,
+					 unsigned int len);
+XMLPUBFUN int XMLCALL		
+		xmlBufferGrow		(xmlBufferPtr buf,
+					 unsigned int len);
+XMLPUBFUN void XMLCALL		
+		xmlBufferEmpty		(xmlBufferPtr buf);
+XMLPUBFUN const xmlChar* XMLCALL	
+		xmlBufferContent	(const xmlBufferPtr buf);
+XMLPUBFUN void XMLCALL		
+		xmlBufferSetAllocationScheme(xmlBufferPtr buf,
+					 xmlBufferAllocationScheme scheme);
+XMLPUBFUN int XMLCALL		
+		xmlBufferLength		(const xmlBufferPtr buf);
+
+/*
+ * Creating/freeing new structures.
+ */
+XMLPUBFUN xmlDtdPtr XMLCALL	
+		xmlCreateIntSubset	(xmlDocPtr doc,
+					 const xmlChar *name,
+					 const xmlChar *ExternalID,
+					 const xmlChar *SystemID);
+XMLPUBFUN xmlDtdPtr XMLCALL	
+		xmlNewDtd		(xmlDocPtr doc,
+					 const xmlChar *name,
+					 const xmlChar *ExternalID,
+					 const xmlChar *SystemID);
+XMLPUBFUN xmlDtdPtr XMLCALL	
+		xmlGetIntSubset		(xmlDocPtr doc);
+XMLPUBFUN void XMLCALL		
+		xmlFreeDtd		(xmlDtdPtr cur);
+#ifdef LIBXML_LEGACY_ENABLED
+XMLPUBFUN xmlNsPtr XMLCALL	
+		xmlNewGlobalNs		(xmlDocPtr doc,
+					 const xmlChar *href,
+					 const xmlChar *prefix);
+#endif /* LIBXML_LEGACY_ENABLED */
+XMLPUBFUN xmlNsPtr XMLCALL	
+		xmlNewNs		(xmlNodePtr node,
+					 const xmlChar *href,
+					 const xmlChar *prefix);
+XMLPUBFUN void XMLCALL		
+		xmlFreeNs		(xmlNsPtr cur);
+XMLPUBFUN void XMLCALL		
+		xmlFreeNsList		(xmlNsPtr cur);
+XMLPUBFUN xmlDocPtr XMLCALL 	
+		xmlNewDoc		(const xmlChar *version);
+XMLPUBFUN void XMLCALL		
+		xmlFreeDoc		(xmlDocPtr cur);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlNewDocProp		(xmlDocPtr doc,
+					 const xmlChar *name,
+					 const xmlChar *value);
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \
+    defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlNewProp		(xmlNodePtr node,
+					 const xmlChar *name,
+					 const xmlChar *value);
+#endif
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlNewNsProp		(xmlNodePtr node,
+					 xmlNsPtr ns,
+					 const xmlChar *name,
+					 const xmlChar *value);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlNewNsPropEatName	(xmlNodePtr node,
+					 xmlNsPtr ns,
+					 xmlChar *name,
+					 const xmlChar *value);
+XMLPUBFUN void XMLCALL		
+		xmlFreePropList		(xmlAttrPtr cur);
+XMLPUBFUN void XMLCALL		
+		xmlFreeProp		(xmlAttrPtr cur);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlCopyProp		(xmlNodePtr target,
+					 xmlAttrPtr cur);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlCopyPropList		(xmlNodePtr target,
+					 xmlAttrPtr cur);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlDtdPtr XMLCALL	
+		xmlCopyDtd		(xmlDtdPtr dtd);
+#endif /* LIBXML_TREE_ENABLED */
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN xmlDocPtr XMLCALL	
+		xmlCopyDoc		(xmlDocPtr doc,
+					 int recursive);
+#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) */
+/*
+ * Creating new nodes.
+ */
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocNode		(xmlDocPtr doc,
+					 xmlNsPtr ns,
+					 const xmlChar *name,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocNodeEatName	(xmlDocPtr doc,
+					 xmlNsPtr ns,
+					 xmlChar *name,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewNode		(xmlNsPtr ns,
+					 const xmlChar *name);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewNodeEatName	(xmlNsPtr ns,
+					 xmlChar *name);
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewChild		(xmlNodePtr parent,
+					 xmlNsPtr ns,
+					 const xmlChar *name,
+					 const xmlChar *content);
+#endif
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocText		(xmlDocPtr doc,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewText		(const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocPI		(xmlDocPtr doc,
+					 const xmlChar *name,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewPI		(const xmlChar *name,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocTextLen	(xmlDocPtr doc,
+					 const xmlChar *content,
+					 int len);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewTextLen		(const xmlChar *content,
+					 int len);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocComment	(xmlDocPtr doc,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewComment		(const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewCDataBlock	(xmlDocPtr doc,
+					 const xmlChar *content,
+					 int len);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewCharRef		(xmlDocPtr doc,
+					 const xmlChar *name);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewReference		(xmlDocPtr doc,
+					 const xmlChar *name);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlCopyNode		(const xmlNodePtr node,
+					 int recursive);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlDocCopyNode		(const xmlNodePtr node,
+					 xmlDocPtr doc,
+					 int recursive);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlDocCopyNodeList	(xmlDocPtr doc,
+					 const xmlNodePtr node);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlCopyNodeList		(const xmlNodePtr node);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewTextChild		(xmlNodePtr parent,
+					 xmlNsPtr ns,
+					 const xmlChar *name,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocRawNode	(xmlDocPtr doc,
+					 xmlNsPtr ns,
+					 const xmlChar *name,
+					 const xmlChar *content);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlNewDocFragment	(xmlDocPtr doc);
+#endif /* LIBXML_TREE_ENABLED */
+
+/*
+ * Navigating.
+ */
+XMLPUBFUN long XMLCALL		
+		xmlGetLineNo		(xmlNodePtr node);
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED)
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlGetNodePath		(xmlNodePtr node);
+#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) */
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlDocGetRootElement	(xmlDocPtr doc);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlGetLastChild		(xmlNodePtr parent);
+XMLPUBFUN int XMLCALL		
+		xmlNodeIsText		(xmlNodePtr node);
+XMLPUBFUN int XMLCALL		
+		xmlIsBlankNode		(xmlNodePtr node);
+
+/*
+ * Changing the structure.
+ */
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED)
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlDocSetRootElement	(xmlDocPtr doc,
+					 xmlNodePtr root);
+#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlNodeSetName		(xmlNodePtr cur,
+					 const xmlChar *name);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlAddChild		(xmlNodePtr parent,
+					 xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlAddChildList		(xmlNodePtr parent,
+					 xmlNodePtr cur);
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED)
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlReplaceNode		(xmlNodePtr old,
+					 xmlNodePtr cur);
+#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \
+    defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlAddPrevSibling	(xmlNodePtr cur,
+					 xmlNodePtr elem);
+#endif /* LIBXML_TREE_ENABLED || LIBXML_HTML_ENABLED || LIBXML_SCHEMAS_ENABLED */
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlAddSibling		(xmlNodePtr cur,
+					 xmlNodePtr elem);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlAddNextSibling	(xmlNodePtr cur,
+					 xmlNodePtr elem);
+XMLPUBFUN void XMLCALL		
+		xmlUnlinkNode		(xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlTextMerge		(xmlNodePtr first,
+					 xmlNodePtr second);
+XMLPUBFUN int XMLCALL		
+		xmlTextConcat		(xmlNodePtr node,
+					 const xmlChar *content,
+					 int len);
+XMLPUBFUN void XMLCALL		
+		xmlFreeNodeList		(xmlNodePtr cur);
+XMLPUBFUN void XMLCALL		
+		xmlFreeNode		(xmlNodePtr cur);
+XMLPUBFUN void XMLCALL		
+		xmlSetTreeDoc		(xmlNodePtr tree,
+					 xmlDocPtr doc);
+XMLPUBFUN void XMLCALL		
+		xmlSetListDoc		(xmlNodePtr list,
+					 xmlDocPtr doc);
+/*
+ * Namespaces.
+ */
+XMLPUBFUN xmlNsPtr XMLCALL	
+		xmlSearchNs		(xmlDocPtr doc,
+					 xmlNodePtr node,
+					 const xmlChar *nameSpace);
+XMLPUBFUN xmlNsPtr XMLCALL	
+		xmlSearchNsByHref	(xmlDocPtr doc,
+					 xmlNodePtr node,
+					 const xmlChar *href);
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED)
+XMLPUBFUN xmlNsPtr * XMLCALL	
+		xmlGetNsList		(xmlDocPtr doc,
+					 xmlNodePtr node);
+#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) */
+
+XMLPUBFUN void XMLCALL		
+		xmlSetNs		(xmlNodePtr node,
+					 xmlNsPtr ns);
+XMLPUBFUN xmlNsPtr XMLCALL	
+		xmlCopyNamespace	(xmlNsPtr cur);
+XMLPUBFUN xmlNsPtr XMLCALL	
+		xmlCopyNamespaceList	(xmlNsPtr cur);
+
+/*
+ * Changing the content.
+ */
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED)
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlSetProp		(xmlNodePtr node,
+					 const xmlChar *name,
+					 const xmlChar *value);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlSetNsProp		(xmlNodePtr node,
+					 xmlNsPtr ns,
+					 const xmlChar *name,
+					 const xmlChar *value);
+#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) */
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlGetNoNsProp		(xmlNodePtr node,
+					 const xmlChar *name);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlGetProp		(xmlNodePtr node,
+					 const xmlChar *name);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlHasProp		(xmlNodePtr node,
+					 const xmlChar *name);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlHasNsProp		(xmlNodePtr node,
+					 const xmlChar *name,
+					 const xmlChar *nameSpace);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlGetNsProp		(xmlNodePtr node,
+					 const xmlChar *name,
+					 const xmlChar *nameSpace);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlStringGetNodeList	(xmlDocPtr doc,
+					 const xmlChar *value);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		xmlStringLenGetNodeList	(xmlDocPtr doc,
+					 const xmlChar *value,
+					 int len);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlNodeListGetString	(xmlDocPtr doc,
+					 xmlNodePtr list,
+					 int inLine);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlNodeListGetRawString	(xmlDocPtr doc,
+					 xmlNodePtr list,
+					 int inLine);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN void XMLCALL		
+		xmlNodeSetContent	(xmlNodePtr cur,
+					 const xmlChar *content);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlNodeSetContentLen	(xmlNodePtr cur,
+					 const xmlChar *content,
+					 int len);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN void XMLCALL		
+		xmlNodeAddContent	(xmlNodePtr cur,
+					 const xmlChar *content);
+XMLPUBFUN void XMLCALL		
+		xmlNodeAddContentLen	(xmlNodePtr cur,
+					 const xmlChar *content,
+					 int len);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlNodeGetContent	(xmlNodePtr cur);
+XMLPUBFUN int XMLCALL
+		xmlNodeBufGetContent	(xmlBufferPtr buffer,
+					 xmlNodePtr cur);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlNodeGetLang		(xmlNodePtr cur);
+XMLPUBFUN int XMLCALL		
+		xmlNodeGetSpacePreserve	(xmlNodePtr cur);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlNodeSetLang		(xmlNodePtr cur,
+					 const xmlChar *lang);
+XMLPUBFUN void XMLCALL		
+		xmlNodeSetSpacePreserve (xmlNodePtr cur,
+					 int val);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlNodeGetBase		(xmlDocPtr doc,
+					 xmlNodePtr cur);
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED)
+XMLPUBFUN void XMLCALL		
+		xmlNodeSetBase		(xmlNodePtr cur,
+					 const xmlChar *uri);
+#endif
+
+/*
+ * Removing content.
+ */
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN int XMLCALL		
+		xmlRemoveProp		(xmlAttrPtr cur);
+#endif /* LIBXML_TREE_ENABLED */
+#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN int XMLCALL		
+		xmlUnsetNsProp		(xmlNodePtr node,
+					 xmlNsPtr ns,
+					 const xmlChar *name);
+XMLPUBFUN int XMLCALL		
+		xmlUnsetProp		(xmlNodePtr node,
+					 const xmlChar *name);
+#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) */
+
+/*
+ * Internal, don't use.
+ */
+XMLPUBFUN void XMLCALL		
+		xmlBufferWriteCHAR	(xmlBufferPtr buf,
+					 const xmlChar *string);
+XMLPUBFUN void XMLCALL		
+		xmlBufferWriteChar	(xmlBufferPtr buf,
+					 const char *string);
+XMLPUBFUN void XMLCALL		
+		xmlBufferWriteQuotedString(xmlBufferPtr buf,
+					 const xmlChar *string);
+
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void xmlAttrSerializeTxtContent(xmlBufferPtr buf,
+					 xmlDocPtr doc,
+					 xmlAttrPtr attr,
+					 const xmlChar *string);
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+#ifdef LIBXML_TREE_ENABLED
+/*
+ * Namespace handling.
+ */
+XMLPUBFUN int XMLCALL		
+		xmlReconciliateNs	(xmlDocPtr doc,
+					 xmlNodePtr tree);
+#endif
+
+#ifdef LIBXML_OUTPUT_ENABLED
+/*
+ * Saving.
+ */
+XMLPUBFUN void XMLCALL		
+		xmlDocDumpFormatMemory	(xmlDocPtr cur,
+					 xmlChar **mem,
+					 int *size,
+					 int format);
+XMLPUBFUN void XMLCALL		
+		xmlDocDumpMemory	(xmlDocPtr cur,
+					 xmlChar **mem,
+					 int *size);
+XMLPUBFUN void XMLCALL		
+		xmlDocDumpMemoryEnc	(xmlDocPtr out_doc,
+					 xmlChar **doc_txt_ptr,
+					 int * doc_txt_len,
+					 const char *txt_encoding);
+XMLPUBFUN void XMLCALL		
+		xmlDocDumpFormatMemoryEnc(xmlDocPtr out_doc,
+					 xmlChar **doc_txt_ptr,
+					 int * doc_txt_len,
+					 const char *txt_encoding,
+					 int format);
+XMLPUBFUN int XMLCALL		
+		xmlDocFormatDump	(FILE *f,
+					 xmlDocPtr cur,
+					 int format);
+XMLPUBFUN int XMLCALL	
+		xmlDocDump		(FILE *f,
+					 xmlDocPtr cur);
+XMLPUBFUN void XMLCALL		
+		xmlElemDump		(FILE *f,
+					 xmlDocPtr doc,
+					 xmlNodePtr cur);
+XMLPUBFUN int XMLCALL		
+		xmlSaveFile		(const char *filename,
+					 xmlDocPtr cur);
+XMLPUBFUN int XMLCALL		
+		xmlSaveFormatFile	(const char *filename,
+					 xmlDocPtr cur,
+					 int format);
+XMLPUBFUN int XMLCALL		
+		xmlNodeDump		(xmlBufferPtr buf,
+					 xmlDocPtr doc,
+					 xmlNodePtr cur,
+					 int level,
+					 int format);
+
+XMLPUBFUN int XMLCALL		
+		xmlSaveFileTo		(xmlOutputBufferPtr buf,
+					 xmlDocPtr cur,
+					 const char *encoding);
+XMLPUBFUN int XMLCALL             
+		xmlSaveFormatFileTo     (xmlOutputBufferPtr buf,
+					 xmlDocPtr cur,
+				         const char *encoding,
+				         int format);
+XMLPUBFUN void XMLCALL		
+		xmlNodeDumpOutput	(xmlOutputBufferPtr buf,
+					 xmlDocPtr doc,
+					 xmlNodePtr cur,
+					 int level,
+					 int format,
+					 const char *encoding);
+
+XMLPUBFUN int XMLCALL		
+		xmlSaveFormatFileEnc    (const char *filename,
+					 xmlDocPtr cur,
+					 const char *encoding,
+					 int format);
+
+XMLPUBFUN int XMLCALL		
+		xmlSaveFileEnc		(const char *filename,
+					 xmlDocPtr cur,
+					 const char *encoding);
+
+#endif /* LIBXML_OUTPUT_ENABLED */
+/*
+ * XHTML
+ */
+XMLPUBFUN int XMLCALL		
+		xmlIsXHTML		(const xmlChar *systemID,
+					 const xmlChar *publicID);
+
+/*
+ * Compression.
+ */
+XMLPUBFUN int XMLCALL		
+		xmlGetDocCompressMode	(xmlDocPtr doc);
+XMLPUBFUN void XMLCALL		
+		xmlSetDocCompressMode	(xmlDocPtr doc,
+					 int mode);
+XMLPUBFUN int XMLCALL		
+		xmlGetCompressMode	(void);
+XMLPUBFUN void XMLCALL		
+		xmlSetCompressMode	(int mode);
+
+#ifdef __cplusplus
+}
+#endif
+#ifndef __XML_PARSER_H__
+#include <libxml/xmlmemory.h>
+#endif
+
+#endif /* __XML_TREE_H__ */
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/uri.h ./aperios/include/libxml2/libxml/uri.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/uri.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/uri.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,84 @@
+/**
+ * Summary: library of generic URI related routines
+ * Description: library of generic URI related routines
+ *              Implements RFC 2396
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_URI_H__
+#define __XML_URI_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlURI:
+ *
+ * A parsed URI reference. This is a struct containing the various fields
+ * as described in RFC 2396 but separated for further processing.
+ */
+typedef struct _xmlURI xmlURI;
+typedef xmlURI *xmlURIPtr;
+struct _xmlURI {
+    char *scheme;	/* the URI scheme */
+    char *opaque;	/* opaque part */
+    char *authority;	/* the authority part */
+    char *server;	/* the server part */
+    char *user;		/* the user part */
+    int port;		/* the port number */
+    char *path;		/* the path string */
+    char *query;	/* the query string */
+    char *fragment;	/* the fragment identifier */
+    int  cleanup;	/* parsing potentially unclean URI */
+};
+
+/*
+ * This function is in tree.h:
+ * xmlChar *	xmlNodeGetBase	(xmlDocPtr doc,
+ *                               xmlNodePtr cur);
+ */
+XMLPUBFUN xmlURIPtr XMLCALL	
+		xmlCreateURI		(void);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlBuildURI			(const xmlChar *URI,
+	                         const xmlChar *base);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlBuildRelativeURI	(const xmlChar *URI,
+	                         const xmlChar *base);
+XMLPUBFUN xmlURIPtr XMLCALL	
+		xmlParseURI		(const char *str);
+XMLPUBFUN int XMLCALL		
+		xmlParseURIReference	(xmlURIPtr uri,
+					 const char *str);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlSaveUri		(xmlURIPtr uri);
+XMLPUBFUN void XMLCALL		
+		xmlPrintURI		(FILE *stream,
+					 xmlURIPtr uri);
+XMLPUBFUN xmlChar * XMLCALL       
+		xmlURIEscapeStr         (const xmlChar *str,
+ 					 const xmlChar *list);
+XMLPUBFUN char * XMLCALL		
+		xmlURIUnescapeString	(const char *str,
+					 int len,
+					 char *target);
+XMLPUBFUN int XMLCALL		
+		xmlNormalizeURIPath	(char *path);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlURIEscape		(const xmlChar *str);
+XMLPUBFUN void XMLCALL		
+		xmlFreeURI		(xmlURIPtr uri);
+XMLPUBFUN xmlChar* XMLCALL	
+		xmlCanonicPath		(const xmlChar *path);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_URI_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/valid.h ./aperios/include/libxml2/libxml/valid.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/valid.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/valid.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,458 @@
+/*
+ * Summary: The DTD validation
+ * Description: API for the DTD handling and the validity checking
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+
+#ifndef __XML_VALID_H__
+#define __XML_VALID_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/xmlerror.h>
+#include <libxml/tree.h>
+#include <libxml/list.h>
+#include <libxml/xmlautomata.h>
+#include <libxml/xmlregexp.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Validation state added for non-determinist content model.
+ */
+typedef struct _xmlValidState xmlValidState;
+typedef xmlValidState *xmlValidStatePtr;
+
+/**
+ * xmlValidityErrorFunc:
+ * @ctx:  usually an xmlValidCtxtPtr to a validity error context,
+ *        but comes from ctxt->userData (which normally contains such
+ *        a pointer); ctxt->userData can be changed by the user.
+ * @msg:  the string to format *printf like vararg
+ * @...:  remaining arguments to the format
+ *
+ * Callback called when a validity error is found. This is a message
+ * oriented function similar to an *printf function.
+ */
+typedef void (*xmlValidityErrorFunc) (void *ctx,
+			     const char *msg,
+			     ...);
+
+/**
+ * xmlValidityWarningFunc:
+ * @ctx:  usually an xmlValidCtxtPtr to a validity error context,
+ *        but comes from ctxt->userData (which normally contains such
+ *        a pointer); ctxt->userData can be changed by the user.
+ * @msg:  the string to format *printf like vararg
+ * @...:  remaining arguments to the format
+ *
+ * Callback called when a validity warning is found. This is a message
+ * oriented function similar to an *printf function.
+ */
+typedef void (*xmlValidityWarningFunc) (void *ctx,
+			       const char *msg,
+			       ...);
+
+#ifdef IN_LIBXML
+/**
+ * XML_CTXT_FINISH_DTD_0:
+ *
+ * Special value for finishDtd field when embedded in an xmlParserCtxt
+ */
+#define XML_CTXT_FINISH_DTD_0 0xabcd1234
+/**
+ * XML_CTXT_FINISH_DTD_1:
+ *
+ * Special value for finishDtd field when embedded in an xmlParserCtxt
+ */
+#define XML_CTXT_FINISH_DTD_1 0xabcd1235
+#endif
+
+/*
+ * xmlValidCtxt:
+ * An xmlValidCtxt is used for error reporting when validating.
+ */
+typedef struct _xmlValidCtxt xmlValidCtxt;
+typedef xmlValidCtxt *xmlValidCtxtPtr;
+struct _xmlValidCtxt {
+    void *userData;			/* user specific data block */
+    xmlValidityErrorFunc error;		/* the callback in case of errors */
+    xmlValidityWarningFunc warning;	/* the callback in case of warning */
+
+    /* Node analysis stack used when validating within entities */
+    xmlNodePtr         node;          /* Current parsed Node */
+    int                nodeNr;        /* Depth of the parsing stack */
+    int                nodeMax;       /* Max depth of the parsing stack */
+    xmlNodePtr        *nodeTab;       /* array of nodes */
+
+    unsigned int     finishDtd;       /* finished validating the Dtd ? */
+    xmlDocPtr              doc;       /* the document */
+    int                  valid;       /* temporary validity check result */
+
+    /* state state used for non-determinist content validation */
+    xmlValidState     *vstate;        /* current state */
+    int                vstateNr;      /* Depth of the validation stack */
+    int                vstateMax;     /* Max depth of the validation stack */
+    xmlValidState     *vstateTab;     /* array of validation states */
+
+#ifdef LIBXML_REGEXP_ENABLED
+    xmlAutomataPtr            am;     /* the automata */
+    xmlAutomataStatePtr    state;     /* used to build the automata */
+#else
+    void                     *am;
+    void                  *state;
+#endif
+};
+
+/*
+ * ALL notation declarations are stored in a table.
+ * There is one table per DTD.
+ */
+
+typedef struct _xmlHashTable xmlNotationTable;
+typedef xmlNotationTable *xmlNotationTablePtr;
+
+/*
+ * ALL element declarations are stored in a table.
+ * There is one table per DTD.
+ */
+
+typedef struct _xmlHashTable xmlElementTable;
+typedef xmlElementTable *xmlElementTablePtr;
+
+/*
+ * ALL attribute declarations are stored in a table.
+ * There is one table per DTD.
+ */
+
+typedef struct _xmlHashTable xmlAttributeTable;
+typedef xmlAttributeTable *xmlAttributeTablePtr;
+
+/*
+ * ALL IDs attributes are stored in a table.
+ * There is one table per document.
+ */
+
+typedef struct _xmlHashTable xmlIDTable;
+typedef xmlIDTable *xmlIDTablePtr;
+
+/*
+ * ALL Refs attributes are stored in a table.
+ * There is one table per document.
+ */
+
+typedef struct _xmlHashTable xmlRefTable;
+typedef xmlRefTable *xmlRefTablePtr;
+
+/* Notation */
+XMLPUBFUN xmlNotationPtr XMLCALL	    
+		xmlAddNotationDecl	(xmlValidCtxtPtr ctxt,
+					 xmlDtdPtr dtd,
+					 const xmlChar *name,
+					 const xmlChar *PublicID,
+					 const xmlChar *SystemID);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlNotationTablePtr XMLCALL 
+		xmlCopyNotationTable	(xmlNotationTablePtr table);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN void XMLCALL		    
+		xmlFreeNotationTable	(xmlNotationTablePtr table);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL		    
+		xmlDumpNotationDecl	(xmlBufferPtr buf,
+					 xmlNotationPtr nota);
+XMLPUBFUN void XMLCALL		    
+		xmlDumpNotationTable	(xmlBufferPtr buf,
+					 xmlNotationTablePtr table);
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+/* Element Content */
+/* the non Doc version are being deprecated */
+XMLPUBFUN xmlElementContentPtr XMLCALL 
+		xmlNewElementContent	(const xmlChar *name,
+					 xmlElementContentType type);
+XMLPUBFUN xmlElementContentPtr XMLCALL 
+		xmlCopyElementContent	(xmlElementContentPtr content);
+XMLPUBFUN void XMLCALL		     
+		xmlFreeElementContent	(xmlElementContentPtr cur);
+/* the new versions with doc argument */
+XMLPUBFUN xmlElementContentPtr XMLCALL 
+		xmlNewDocElementContent	(xmlDocPtr doc,
+					 const xmlChar *name,
+					 xmlElementContentType type);
+XMLPUBFUN xmlElementContentPtr XMLCALL 
+		xmlCopyDocElementContent(xmlDocPtr doc,
+					 xmlElementContentPtr content);
+XMLPUBFUN void XMLCALL		     
+		xmlFreeDocElementContent(xmlDocPtr doc,
+					 xmlElementContentPtr cur);
+XMLPUBFUN void XMLCALL		     
+		xmlSnprintfElementContent(char *buf,
+					 int size,
+	                                 xmlElementContentPtr content,
+					 int glob);
+#ifdef LIBXML_OUTPUT_ENABLED
+/* DEPRECATED */
+XMLPUBFUN void XMLCALL		     
+		xmlSprintfElementContent(char *buf,
+	                                 xmlElementContentPtr content,
+					 int glob);
+#endif /* LIBXML_OUTPUT_ENABLED */
+/* DEPRECATED */
+
+/* Element */
+XMLPUBFUN xmlElementPtr XMLCALL	   
+		xmlAddElementDecl	(xmlValidCtxtPtr ctxt,
+					 xmlDtdPtr dtd,
+					 const xmlChar *name,
+					 xmlElementTypeVal type,
+					 xmlElementContentPtr content);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlElementTablePtr XMLCALL 
+		xmlCopyElementTable	(xmlElementTablePtr table);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN void XMLCALL		   
+		xmlFreeElementTable	(xmlElementTablePtr table);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL		   
+		xmlDumpElementTable	(xmlBufferPtr buf,
+					 xmlElementTablePtr table);
+XMLPUBFUN void XMLCALL		   
+		xmlDumpElementDecl	(xmlBufferPtr buf,
+					 xmlElementPtr elem);
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+/* Enumeration */
+XMLPUBFUN xmlEnumerationPtr XMLCALL 
+		xmlCreateEnumeration	(const xmlChar *name);
+XMLPUBFUN void XMLCALL		   
+		xmlFreeEnumeration	(xmlEnumerationPtr cur);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlEnumerationPtr XMLCALL  
+		xmlCopyEnumeration	(xmlEnumerationPtr cur);
+#endif /* LIBXML_TREE_ENABLED */
+
+/* Attribute */
+XMLPUBFUN xmlAttributePtr XMLCALL	    
+		xmlAddAttributeDecl	(xmlValidCtxtPtr ctxt,
+					 xmlDtdPtr dtd,
+					 const xmlChar *elem,
+					 const xmlChar *name,
+					 const xmlChar *ns,
+					 xmlAttributeType type,
+					 xmlAttributeDefault def,
+					 const xmlChar *defaultValue,
+					 xmlEnumerationPtr tree);
+#ifdef LIBXML_TREE_ENABLED
+XMLPUBFUN xmlAttributeTablePtr XMLCALL 
+		xmlCopyAttributeTable  (xmlAttributeTablePtr table);
+#endif /* LIBXML_TREE_ENABLED */
+XMLPUBFUN void XMLCALL		     
+		xmlFreeAttributeTable  (xmlAttributeTablePtr table);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL		     
+		xmlDumpAttributeTable  (xmlBufferPtr buf,
+					xmlAttributeTablePtr table);
+XMLPUBFUN void XMLCALL		     
+		xmlDumpAttributeDecl   (xmlBufferPtr buf,
+					xmlAttributePtr attr);
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+/* IDs */
+XMLPUBFUN xmlIDPtr XMLCALL	
+		xmlAddID	       (xmlValidCtxtPtr ctxt,
+					xmlDocPtr doc,
+					const xmlChar *value,
+					xmlAttrPtr attr);
+XMLPUBFUN void XMLCALL		
+		xmlFreeIDTable	       (xmlIDTablePtr table);
+XMLPUBFUN xmlAttrPtr XMLCALL	
+		xmlGetID	       (xmlDocPtr doc,
+					const xmlChar *ID);
+XMLPUBFUN int XMLCALL		
+		xmlIsID		       (xmlDocPtr doc,
+					xmlNodePtr elem,
+					xmlAttrPtr attr);
+XMLPUBFUN int XMLCALL		
+		xmlRemoveID	       (xmlDocPtr doc, 
+					xmlAttrPtr attr);
+
+/* IDREFs */
+XMLPUBFUN xmlRefPtr XMLCALL	
+		xmlAddRef	       (xmlValidCtxtPtr ctxt,
+					xmlDocPtr doc,
+					const xmlChar *value,
+					xmlAttrPtr attr);
+XMLPUBFUN void XMLCALL		
+		xmlFreeRefTable	       (xmlRefTablePtr table);
+XMLPUBFUN int XMLCALL		
+		xmlIsRef	       (xmlDocPtr doc,
+					xmlNodePtr elem,
+					xmlAttrPtr attr);
+XMLPUBFUN int XMLCALL		
+		xmlRemoveRef	       (xmlDocPtr doc, 
+					xmlAttrPtr attr);
+XMLPUBFUN xmlListPtr XMLCALL	
+		xmlGetRefs	       (xmlDocPtr doc,
+					const xmlChar *ID);
+
+/**
+ * The public function calls related to validity checking.
+ */
+#ifdef LIBXML_VALID_ENABLED
+/* Allocate/Release Validation Contexts */
+XMLPUBFUN xmlValidCtxtPtr XMLCALL	    
+		xmlNewValidCtxt(void);
+XMLPUBFUN void XMLCALL		    
+		xmlFreeValidCtxt(xmlValidCtxtPtr);
+
+XMLPUBFUN int XMLCALL		
+		xmlValidateRoot		(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc);
+XMLPUBFUN int XMLCALL		
+		xmlValidateElementDecl	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+		                         xmlElementPtr elem);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlValidNormalizeAttributeValue(xmlDocPtr doc,
+					 xmlNodePtr elem,
+					 const xmlChar *name,
+					 const xmlChar *value);
+XMLPUBFUN xmlChar * XMLCALL	
+		xmlValidCtxtNormalizeAttributeValue(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem,
+					 const xmlChar *name,
+					 const xmlChar *value);
+XMLPUBFUN int XMLCALL		
+		xmlValidateAttributeDecl(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+		                         xmlAttributePtr attr);
+XMLPUBFUN int XMLCALL		
+		xmlValidateAttributeValue(xmlAttributeType type,
+					 const xmlChar *value);
+XMLPUBFUN int XMLCALL		
+		xmlValidateNotationDecl	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+		                         xmlNotationPtr nota);
+XMLPUBFUN int XMLCALL		
+		xmlValidateDtd		(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlDtdPtr dtd);
+XMLPUBFUN int XMLCALL		
+		xmlValidateDtdFinal	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc);
+XMLPUBFUN int XMLCALL		
+		xmlValidateDocument	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc);
+XMLPUBFUN int XMLCALL		
+		xmlValidateElement	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem);
+XMLPUBFUN int XMLCALL		
+		xmlValidateOneElement	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+		                         xmlNodePtr elem);
+XMLPUBFUN int XMLCALL	
+		xmlValidateOneAttribute	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr	elem,
+					 xmlAttrPtr attr,
+					 const xmlChar *value);
+XMLPUBFUN int XMLCALL		
+		xmlValidateOneNamespace	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem,
+					 const xmlChar *prefix,
+					 xmlNsPtr ns,
+					 const xmlChar *value);
+XMLPUBFUN int XMLCALL		
+		xmlValidateDocumentFinal(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc);
+#endif /* LIBXML_VALID_ENABLED */
+
+#if defined(LIBXML_VALID_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN int XMLCALL		
+		xmlValidateNotationUse	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 const xmlChar *notationName);
+#endif /* LIBXML_VALID_ENABLED or LIBXML_SCHEMAS_ENABLED */
+
+XMLPUBFUN int XMLCALL		
+		xmlIsMixedElement	(xmlDocPtr doc,
+					 const xmlChar *name);
+XMLPUBFUN xmlAttributePtr XMLCALL	
+		xmlGetDtdAttrDesc	(xmlDtdPtr dtd,
+					 const xmlChar *elem,
+					 const xmlChar *name);
+XMLPUBFUN xmlAttributePtr XMLCALL	
+		xmlGetDtdQAttrDesc	(xmlDtdPtr dtd,
+					 const xmlChar *elem,
+					 const xmlChar *name,
+					 const xmlChar *prefix);
+XMLPUBFUN xmlNotationPtr XMLCALL	
+		xmlGetDtdNotationDesc	(xmlDtdPtr dtd,
+					 const xmlChar *name);
+XMLPUBFUN xmlElementPtr XMLCALL	
+		xmlGetDtdQElementDesc	(xmlDtdPtr dtd,
+					 const xmlChar *name,
+					 const xmlChar *prefix);
+XMLPUBFUN xmlElementPtr XMLCALL	
+		xmlGetDtdElementDesc	(xmlDtdPtr dtd,
+					 const xmlChar *name);
+
+#ifdef LIBXML_VALID_ENABLED
+
+XMLPUBFUN int XMLCALL		
+		xmlValidGetPotentialChildren(xmlElementContent *ctree,
+					 const xmlChar **list,
+					 int *len,
+					 int max);
+
+XMLPUBFUN int XMLCALL		
+		xmlValidGetValidElements(xmlNode *prev,
+					 xmlNode *next,
+					 const xmlChar **names,
+					 int max);
+XMLPUBFUN int XMLCALL		
+		xmlValidateNameValue	(const xmlChar *value);
+XMLPUBFUN int XMLCALL		
+		xmlValidateNamesValue	(const xmlChar *value);
+XMLPUBFUN int XMLCALL		
+		xmlValidateNmtokenValue	(const xmlChar *value);
+XMLPUBFUN int XMLCALL		
+		xmlValidateNmtokensValue(const xmlChar *value);
+
+#ifdef LIBXML_REGEXP_ENABLED
+/*
+ * Validation based on the regexp support
+ */
+XMLPUBFUN int XMLCALL		
+		xmlValidBuildContentModel(xmlValidCtxtPtr ctxt,
+					 xmlElementPtr elem);
+
+XMLPUBFUN int XMLCALL		
+		xmlValidatePushElement	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem,
+					 const xmlChar *qname);
+XMLPUBFUN int XMLCALL		
+		xmlValidatePushCData	(xmlValidCtxtPtr ctxt,
+					 const xmlChar *data,
+					 int len);
+XMLPUBFUN int XMLCALL		
+		xmlValidatePopElement	(xmlValidCtxtPtr ctxt,
+					 xmlDocPtr doc,
+					 xmlNodePtr elem,
+					 const xmlChar *qname);
+#endif /* LIBXML_REGEXP_ENABLED */
+#endif /* LIBXML_VALID_ENABLED */
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_VALID_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xinclude.h ./aperios/include/libxml2/libxml/xinclude.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xinclude.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xinclude.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,121 @@
+/*
+ * Summary: implementation of XInclude
+ * Description: API to handle XInclude processing,
+ * implements the
+ * World Wide Web Consortium Last Call Working Draft 10 November 2003
+ * http://www.w3.org/TR/2003/WD-xinclude-20031110
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_XINCLUDE_H__
+#define __XML_XINCLUDE_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+
+#ifdef LIBXML_XINCLUDE_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * XINCLUDE_NS:
+ *
+ * Macro defining the Xinclude namespace: http://www.w3.org/2003/XInclude
+ */
+#define XINCLUDE_NS (const xmlChar *) "http://www.w3.org/2003/XInclude"
+/**
+ * XINCLUDE_OLD_NS:
+ *
+ * Macro defining the draft Xinclude namespace: http://www.w3.org/2001/XInclude
+ */
+#define XINCLUDE_OLD_NS (const xmlChar *) "http://www.w3.org/2001/XInclude"
+/**
+ * XINCLUDE_NODE:
+ *
+ * Macro defining "include"
+ */
+#define XINCLUDE_NODE (const xmlChar *) "include"
+/**
+ * XINCLUDE_FALLBACK:
+ *
+ * Macro defining "fallback"
+ */
+#define XINCLUDE_FALLBACK (const xmlChar *) "fallback"
+/**
+ * XINCLUDE_HREF:
+ *
+ * Macro defining "href"
+ */
+#define XINCLUDE_HREF (const xmlChar *) "href"
+/**
+ * XINCLUDE_PARSE:
+ *
+ * Macro defining "parse"
+ */
+#define XINCLUDE_PARSE (const xmlChar *) "parse"
+/**
+ * XINCLUDE_PARSE_XML:
+ *
+ * Macro defining "xml"
+ */
+#define XINCLUDE_PARSE_XML (const xmlChar *) "xml"
+/**
+ * XINCLUDE_PARSE_TEXT:
+ *
+ * Macro defining "text"
+ */
+#define XINCLUDE_PARSE_TEXT (const xmlChar *) "text"
+/**
+ * XINCLUDE_PARSE_ENCODING:
+ *
+ * Macro defining "encoding"
+ */
+#define XINCLUDE_PARSE_ENCODING (const xmlChar *) "encoding"
+/**
+ * XINCLUDE_PARSE_XPOINTER:
+ *
+ * Macro defining "xpointer"
+ */
+#define XINCLUDE_PARSE_XPOINTER (const xmlChar *) "xpointer"
+
+typedef struct _xmlXIncludeCtxt xmlXIncludeCtxt;
+typedef xmlXIncludeCtxt *xmlXIncludeCtxtPtr;
+
+/*
+ * standalone processing
+ */
+XMLPUBFUN int XMLCALL	
+		xmlXIncludeProcess	(xmlDocPtr doc);
+XMLPUBFUN int XMLCALL	
+		xmlXIncludeProcessFlags	(xmlDocPtr doc,
+					 int flags);
+XMLPUBFUN int XMLCALL	
+		xmlXIncludeProcessTree	(xmlNodePtr tree);
+XMLPUBFUN int XMLCALL	
+		xmlXIncludeProcessTreeFlags(xmlNodePtr tree,
+					 int flags);
+/*
+ * contextual processing
+ */
+XMLPUBFUN xmlXIncludeCtxtPtr XMLCALL
+		xmlXIncludeNewContext	(xmlDocPtr doc);
+XMLPUBFUN int XMLCALL
+		xmlXIncludeSetFlags	(xmlXIncludeCtxtPtr ctxt,
+					 int flags);
+XMLPUBFUN void XMLCALL
+		xmlXIncludeFreeContext	(xmlXIncludeCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL
+		xmlXIncludeProcessNode	(xmlXIncludeCtxtPtr ctxt,
+					 xmlNodePtr tree);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_XINCLUDE_ENABLED */
+
+#endif /* __XML_XINCLUDE_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xlink.h ./aperios/include/libxml2/libxml/xlink.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xlink.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xlink.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,189 @@
+/*
+ * Summary: unfinished XLink detection module
+ * Description: unfinished XLink detection module
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_XLINK_H__
+#define __XML_XLINK_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+
+#ifdef LIBXML_XPTR_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Various defines for the various Link properties.
+ *
+ * NOTE: the link detection layer will try to resolve QName expansion
+ *       of namespaces. If "foo" is the prefix for "http://foo.com/"
+ *       then the link detection layer will expand role="foo:myrole"
+ *       to "http://foo.com/:myrole".
+ * NOTE: the link detection layer will expand URI-Refences found on
+ *       href attributes by using the base mechanism if found.
+ */
+typedef xmlChar *xlinkHRef;
+typedef xmlChar *xlinkRole;
+typedef xmlChar *xlinkTitle;
+
+typedef enum {
+    XLINK_TYPE_NONE = 0,
+    XLINK_TYPE_SIMPLE,
+    XLINK_TYPE_EXTENDED,
+    XLINK_TYPE_EXTENDED_SET
+} xlinkType;
+
+typedef enum {
+    XLINK_SHOW_NONE = 0,
+    XLINK_SHOW_NEW,
+    XLINK_SHOW_EMBED,
+    XLINK_SHOW_REPLACE
+} xlinkShow;
+
+typedef enum {
+    XLINK_ACTUATE_NONE = 0,
+    XLINK_ACTUATE_AUTO,
+    XLINK_ACTUATE_ONREQUEST
+} xlinkActuate;
+
+/**
+ * xlinkNodeDetectFunc:
+ * @ctx:  user data pointer
+ * @node:  the node to check
+ * 
+ * This is the prototype for the link detection routine.
+ * It calls the default link detection callbacks upon link detection.
+ */
+typedef void (*xlinkNodeDetectFunc) (void *ctx, xmlNodePtr node);
+
+/*
+ * The link detection module interact with the upper layers using
+ * a set of callback registered at parsing time.
+ */
+
+/**
+ * xlinkSimpleLinkFunk:
+ * @ctx:  user data pointer
+ * @node:  the node carrying the link
+ * @href:  the target of the link
+ * @role:  the role string
+ * @title:  the link title
+ *
+ * This is the prototype for a simple link detection callback.
+ */
+typedef void
+(*xlinkSimpleLinkFunk)	(void *ctx,
+			 xmlNodePtr node,
+			 const xlinkHRef href,
+			 const xlinkRole role,
+			 const xlinkTitle title);
+
+/**
+ * xlinkExtendedLinkFunk:
+ * @ctx:  user data pointer
+ * @node:  the node carrying the link
+ * @nbLocators: the number of locators detected on the link
+ * @hrefs:  pointer to the array of locator hrefs
+ * @roles:  pointer to the array of locator roles
+ * @nbArcs: the number of arcs detected on the link
+ * @from:  pointer to the array of source roles found on the arcs
+ * @to:  pointer to the array of target roles found on the arcs
+ * @show:  array of values for the show attributes found on the arcs
+ * @actuate:  array of values for the actuate attributes found on the arcs
+ * @nbTitles: the number of titles detected on the link
+ * @title:  array of titles detected on the link
+ * @langs:  array of xml:lang values for the titles
+ *
+ * This is the prototype for a extended link detection callback.
+ */
+typedef void
+(*xlinkExtendedLinkFunk)(void *ctx,
+			 xmlNodePtr node,
+			 int nbLocators,
+			 const xlinkHRef *hrefs,
+			 const xlinkRole *roles,
+			 int nbArcs,
+			 const xlinkRole *from,
+			 const xlinkRole *to,
+			 xlinkShow *show,
+			 xlinkActuate *actuate,
+			 int nbTitles,
+			 const xlinkTitle *titles,
+			 const xmlChar **langs);
+
+/**
+ * xlinkExtendedLinkSetFunk:
+ * @ctx:  user data pointer
+ * @node:  the node carrying the link
+ * @nbLocators: the number of locators detected on the link
+ * @hrefs:  pointer to the array of locator hrefs
+ * @roles:  pointer to the array of locator roles
+ * @nbTitles: the number of titles detected on the link
+ * @title:  array of titles detected on the link
+ * @langs:  array of xml:lang values for the titles
+ *
+ * This is the prototype for a extended link set detection callback.
+ */
+typedef void
+(*xlinkExtendedLinkSetFunk)	(void *ctx,
+				 xmlNodePtr node,
+				 int nbLocators,
+				 const xlinkHRef *hrefs,
+				 const xlinkRole *roles,
+				 int nbTitles,
+				 const xlinkTitle *titles,
+				 const xmlChar **langs);
+
+/**
+ * This is the structure containing a set of Links detection callbacks.
+ *
+ * There is no default xlink callbacks, if one want to get link
+ * recognition activated, those call backs must be provided before parsing.
+ */
+typedef struct _xlinkHandler xlinkHandler;
+typedef xlinkHandler *xlinkHandlerPtr;
+struct _xlinkHandler {
+    xlinkSimpleLinkFunk simple;
+    xlinkExtendedLinkFunk extended;
+    xlinkExtendedLinkSetFunk set;
+};
+
+/*
+ * The default detection routine, can be overridden, they call the default
+ * detection callbacks. 
+ */
+
+XMLPUBFUN xlinkNodeDetectFunc XMLCALL	
+		xlinkGetDefaultDetect	(void);
+XMLPUBFUN void XMLCALL			
+		xlinkSetDefaultDetect	(xlinkNodeDetectFunc func);
+
+/*
+ * Routines to set/get the default handlers.
+ */
+XMLPUBFUN xlinkHandlerPtr XMLCALL	
+		xlinkGetDefaultHandler	(void);
+XMLPUBFUN void XMLCALL		
+		xlinkSetDefaultHandler	(xlinkHandlerPtr handler);
+
+/*
+ * Link detection module itself.
+ */
+XMLPUBFUN xlinkType XMLCALL	 
+		xlinkIsLink		(xmlDocPtr doc,
+					 xmlNodePtr node);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_XPTR_ENABLED */
+
+#endif /* __XML_XLINK_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlIO.h ./aperios/include/libxml2/libxml/xmlIO.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlIO.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlIO.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,356 @@
+/*
+ * Summary: interface for the I/O interfaces used by the parser
+ * Description: interface for the I/O interfaces used by the parser
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_IO_H__
+#define __XML_IO_H__
+
+#include <stdio.h>
+#include <libxml/xmlversion.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Those are the functions and datatypes for the parser input
+ * I/O structures.
+ */
+
+/**
+ * xmlInputMatchCallback:
+ * @filename: the filename or URI
+ *
+ * Callback used in the I/O Input API to detect if the current handler 
+ * can provide input fonctionnalities for this resource.
+ *
+ * Returns 1 if yes and 0 if another Input module should be used
+ */
+typedef int (*xmlInputMatchCallback) (char const *filename);
+/**
+ * xmlInputOpenCallback:
+ * @filename: the filename or URI
+ *
+ * Callback used in the I/O Input API to open the resource
+ *
+ * Returns an Input context or NULL in case or error
+ */
+typedef void * (*xmlInputOpenCallback) (char const *filename);
+/**
+ * xmlInputReadCallback:
+ * @context:  an Input context
+ * @buffer:  the buffer to store data read
+ * @len:  the length of the buffer in bytes
+ *
+ * Callback used in the I/O Input API to read the resource
+ *
+ * Returns the number of bytes read or -1 in case of error
+ */
+typedef int (*xmlInputReadCallback) (void * context, char * buffer, int len);
+/**
+ * xmlInputCloseCallback:
+ * @context:  an Input context
+ *
+ * Callback used in the I/O Input API to close the resource
+ *
+ * Returns 0 or -1 in case of error
+ */
+typedef int (*xmlInputCloseCallback) (void * context);
+
+#ifdef LIBXML_OUTPUT_ENABLED
+/*
+ * Those are the functions and datatypes for the library output
+ * I/O structures.
+ */
+
+/**
+ * xmlOutputMatchCallback:
+ * @filename: the filename or URI
+ *
+ * Callback used in the I/O Output API to detect if the current handler 
+ * can provide output fonctionnalities for this resource.
+ *
+ * Returns 1 if yes and 0 if another Output module should be used
+ */
+typedef int (*xmlOutputMatchCallback) (char const *filename);
+/**
+ * xmlOutputOpenCallback:
+ * @filename: the filename or URI
+ *
+ * Callback used in the I/O Output API to open the resource
+ *
+ * Returns an Output context or NULL in case or error
+ */
+typedef void * (*xmlOutputOpenCallback) (char const *filename);
+/**
+ * xmlOutputWriteCallback:
+ * @context:  an Output context
+ * @buffer:  the buffer of data to write
+ * @len:  the length of the buffer in bytes
+ *
+ * Callback used in the I/O Output API to write to the resource
+ *
+ * Returns the number of bytes written or -1 in case of error
+ */
+typedef int (*xmlOutputWriteCallback) (void * context, const char * buffer,
+                                       int len);
+/**
+ * xmlOutputCloseCallback:
+ * @context:  an Output context
+ *
+ * Callback used in the I/O Output API to close the resource
+ *
+ * Returns 0 or -1 in case of error
+ */
+typedef int (*xmlOutputCloseCallback) (void * context);
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+#ifdef __cplusplus
+}
+#endif
+
+#include <libxml/globals.h>
+#include <libxml/tree.h>
+#include <libxml/parser.h>
+#include <libxml/encoding.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+struct _xmlParserInputBuffer {
+    void*                  context;
+    xmlInputReadCallback   readcallback;
+    xmlInputCloseCallback  closecallback;
+    
+    xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */
+    
+    xmlBufferPtr buffer;    /* Local buffer encoded in UTF-8 */
+    xmlBufferPtr raw;       /* if encoder != NULL buffer for raw input */
+    int	compressed;	    /* -1=unknown, 0=not compressed, 1=compressed */
+    int error;
+    unsigned long rawconsumed;/* amount consumed from raw */
+};
+
+
+#ifdef LIBXML_OUTPUT_ENABLED
+struct _xmlOutputBuffer {
+    void*                   context;
+    xmlOutputWriteCallback  writecallback;
+    xmlOutputCloseCallback  closecallback;
+    
+    xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */
+    
+    xmlBufferPtr buffer;    /* Local buffer encoded in UTF-8 or ISOLatin */
+    xmlBufferPtr conv;      /* if encoder != NULL buffer for output */
+    int written;            /* total number of byte written */
+    int error;
+};
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+/*
+ * Interfaces for input
+ */
+XMLPUBFUN void XMLCALL	
+	xmlCleanupInputCallbacks		(void);
+
+XMLPUBFUN int XMLCALL
+	xmlPopInputCallbacks			(void);
+
+XMLPUBFUN void XMLCALL	
+	xmlRegisterDefaultInputCallbacks	(void);
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
+	xmlAllocParserInputBuffer		(xmlCharEncoding enc);
+
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
+	xmlParserInputBufferCreateFilename	(const char *URI,
+                                                 xmlCharEncoding enc);
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
+	xmlParserInputBufferCreateFile		(FILE *file,
+                                                 xmlCharEncoding enc);
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
+	xmlParserInputBufferCreateFd		(int fd,
+	                                         xmlCharEncoding enc);
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
+	xmlParserInputBufferCreateMem		(const char *mem, int size,
+	                                         xmlCharEncoding enc);
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
+	xmlParserInputBufferCreateStatic	(const char *mem, int size,
+	                                         xmlCharEncoding enc);
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
+	xmlParserInputBufferCreateIO		(xmlInputReadCallback   ioread,
+						 xmlInputCloseCallback  ioclose,
+						 void *ioctx,
+	                                         xmlCharEncoding enc);
+XMLPUBFUN int XMLCALL	
+	xmlParserInputBufferRead		(xmlParserInputBufferPtr in,
+						 int len);
+XMLPUBFUN int XMLCALL	
+	xmlParserInputBufferGrow		(xmlParserInputBufferPtr in,
+						 int len);
+XMLPUBFUN int XMLCALL	
+	xmlParserInputBufferPush		(xmlParserInputBufferPtr in,
+						 int len,
+						 const char *buf);
+XMLPUBFUN void XMLCALL	
+	xmlFreeParserInputBuffer		(xmlParserInputBufferPtr in);
+XMLPUBFUN char * XMLCALL	
+	xmlParserGetDirectory			(const char *filename);
+
+XMLPUBFUN int XMLCALL     
+	xmlRegisterInputCallbacks		(xmlInputMatchCallback matchFunc,
+						 xmlInputOpenCallback openFunc,
+						 xmlInputReadCallback readFunc,
+						 xmlInputCloseCallback closeFunc);
+
+xmlParserInputBufferPtr
+	__xmlParserInputBufferCreateFilename(const char *URI,
+										xmlCharEncoding enc);
+
+#ifdef LIBXML_OUTPUT_ENABLED
+/*
+ * Interfaces for output
+ */
+XMLPUBFUN void XMLCALL	
+	xmlCleanupOutputCallbacks		(void);
+XMLPUBFUN void XMLCALL	
+	xmlRegisterDefaultOutputCallbacks(void);
+XMLPUBFUN xmlOutputBufferPtr XMLCALL
+	xmlAllocOutputBuffer		(xmlCharEncodingHandlerPtr encoder);
+
+XMLPUBFUN xmlOutputBufferPtr XMLCALL
+	xmlOutputBufferCreateFilename	(const char *URI,
+					 xmlCharEncodingHandlerPtr encoder,
+					 int compression);
+
+XMLPUBFUN xmlOutputBufferPtr XMLCALL
+	xmlOutputBufferCreateFile	(FILE *file,
+					 xmlCharEncodingHandlerPtr encoder);
+
+XMLPUBFUN xmlOutputBufferPtr XMLCALL
+	xmlOutputBufferCreateFd		(int fd,
+					 xmlCharEncodingHandlerPtr encoder);
+
+XMLPUBFUN xmlOutputBufferPtr XMLCALL
+	xmlOutputBufferCreateIO		(xmlOutputWriteCallback   iowrite,
+					 xmlOutputCloseCallback  ioclose,
+					 void *ioctx,
+					 xmlCharEncodingHandlerPtr encoder);
+
+XMLPUBFUN int XMLCALL	
+	xmlOutputBufferWrite		(xmlOutputBufferPtr out,
+					 int len,
+					 const char *buf);
+XMLPUBFUN int XMLCALL	
+	xmlOutputBufferWriteString	(xmlOutputBufferPtr out,
+					 const char *str);
+XMLPUBFUN int XMLCALL	
+	xmlOutputBufferWriteEscape	(xmlOutputBufferPtr out,
+					 const xmlChar *str,
+					 xmlCharEncodingOutputFunc escaping);
+
+XMLPUBFUN int XMLCALL	
+	xmlOutputBufferFlush		(xmlOutputBufferPtr out);
+XMLPUBFUN int XMLCALL	
+	xmlOutputBufferClose		(xmlOutputBufferPtr out);
+
+XMLPUBFUN int XMLCALL     
+	xmlRegisterOutputCallbacks	(xmlOutputMatchCallback matchFunc,
+					 xmlOutputOpenCallback openFunc,
+					 xmlOutputWriteCallback writeFunc,
+					 xmlOutputCloseCallback closeFunc);
+
+xmlOutputBufferPtr
+	__xmlOutputBufferCreateFilename(const char *URI,
+                              xmlCharEncodingHandlerPtr encoder,
+                              int compression);
+
+#ifdef LIBXML_HTTP_ENABLED
+/*  This function only exists if HTTP support built into the library  */
+XMLPUBFUN void XMLCALL	
+	xmlRegisterHTTPPostCallbacks	(void );
+#endif /* LIBXML_HTTP_ENABLED */
+	
+#endif /* LIBXML_OUTPUT_ENABLED */
+
+XMLPUBFUN xmlParserInputPtr XMLCALL
+	xmlCheckHTTPInput		(xmlParserCtxtPtr ctxt,
+					 xmlParserInputPtr ret);
+
+/*
+ * A predefined entity loader disabling network accesses
+ */
+XMLPUBFUN xmlParserInputPtr XMLCALL 
+	xmlNoNetExternalEntityLoader	(const char *URL,
+					 const char *ID,
+					 xmlParserCtxtPtr ctxt);
+
+/* 
+ * xmlNormalizeWindowsPath is obsolete, don't use it. 
+ * Check xmlCanonicPath in uri.h for a better alternative.
+ */
+XMLPUBFUN xmlChar * XMLCALL 
+	xmlNormalizeWindowsPath		(const xmlChar *path);
+
+XMLPUBFUN int XMLCALL	
+	xmlCheckFilename		(const char *path);
+/**
+ * Default 'file://' protocol callbacks 
+ */
+XMLPUBFUN int XMLCALL	
+	xmlFileMatch 			(const char *filename);
+XMLPUBFUN void * XMLCALL	
+	xmlFileOpen 			(const char *filename);
+XMLPUBFUN int XMLCALL	
+	xmlFileRead 			(void * context, 
+					 char * buffer, 
+					 int len);
+XMLPUBFUN int XMLCALL	
+	xmlFileClose 			(void * context);
+
+/**
+ * Default 'http://' protocol callbacks 
+ */
+#ifdef LIBXML_HTTP_ENABLED
+XMLPUBFUN int XMLCALL	
+	xmlIOHTTPMatch 			(const char *filename);
+XMLPUBFUN void * XMLCALL	
+	xmlIOHTTPOpen 			(const char *filename);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void * XMLCALL	
+	xmlIOHTTPOpenW			(const char * post_uri,
+					 int   compression );
+#endif /* LIBXML_OUTPUT_ENABLED */
+XMLPUBFUN int XMLCALL 	
+	xmlIOHTTPRead			(void * context, 
+					 char * buffer, 
+					 int len);
+XMLPUBFUN int XMLCALL	
+	xmlIOHTTPClose 			(void * context);
+#endif /* LIBXML_HTTP_ENABLED */
+
+/**
+ * Default 'ftp://' protocol callbacks 
+ */
+#ifdef LIBXML_FTP_ENABLED 
+XMLPUBFUN int XMLCALL	
+	xmlIOFTPMatch 			(const char *filename);
+XMLPUBFUN void * XMLCALL	
+	xmlIOFTPOpen 			(const char *filename);
+XMLPUBFUN int XMLCALL 	
+	xmlIOFTPRead			(void * context, 
+					 char * buffer, 
+					 int len);
+XMLPUBFUN int XMLCALL 	
+	xmlIOFTPClose 			(void * context);
+#endif /* LIBXML_FTP_ENABLED */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __XML_IO_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlautomata.h ./aperios/include/libxml2/libxml/xmlautomata.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlautomata.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlautomata.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,138 @@
+/*
+ * Summary: API to build regexp automata
+ * Description: the API to build regexp automata
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_AUTOMATA_H__
+#define __XML_AUTOMATA_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+
+#ifdef LIBXML_REGEXP_ENABLED
+#ifdef LIBXML_AUTOMATA_ENABLED
+#include <libxml/xmlregexp.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlAutomataPtr:
+ *
+ * A libxml automata description, It can be compiled into a regexp
+ */
+typedef struct _xmlAutomata xmlAutomata;
+typedef xmlAutomata *xmlAutomataPtr;
+
+/**
+ * xmlAutomataStatePtr:
+ *
+ * A state int the automata description,
+ */
+typedef struct _xmlAutomataState xmlAutomataState;
+typedef xmlAutomataState *xmlAutomataStatePtr;
+
+/*
+ * Building API
+ */
+XMLPUBFUN xmlAutomataPtr XMLCALL		
+		    xmlNewAutomata		(void);
+XMLPUBFUN void XMLCALL			
+		    xmlFreeAutomata		(xmlAutomataPtr am);
+
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataGetInitState	(xmlAutomataPtr am);
+XMLPUBFUN int XMLCALL			
+		    xmlAutomataSetFinalState	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr state);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewState		(xmlAutomataPtr am);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewTransition	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 const xmlChar *token,
+						 void *data);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewTransition2	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 const xmlChar *token,
+						 const xmlChar *token2,
+						 void *data);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewCountTrans	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 const xmlChar *token,
+						 int min,
+						 int max,
+						 void *data);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewCountTrans2	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 const xmlChar *token,
+						 const xmlChar *token2,
+						 int min,
+						 int max,
+						 void *data);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewOnceTrans	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 const xmlChar *token,
+						 int min,
+						 int max,
+						 void *data);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL
+		    xmlAutomataNewOnceTrans2	(xmlAutomataPtr am, 
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to, 
+						 const xmlChar *token,
+						 const xmlChar *token2,
+						 int min, 
+						 int max, 
+						 void *data);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewAllTrans	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 int lax);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewEpsilon	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewCountedTrans	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 int counter);
+XMLPUBFUN xmlAutomataStatePtr XMLCALL	
+		    xmlAutomataNewCounterTrans	(xmlAutomataPtr am,
+						 xmlAutomataStatePtr from,
+						 xmlAutomataStatePtr to,
+						 int counter);
+XMLPUBFUN int XMLCALL			
+		    xmlAutomataNewCounter	(xmlAutomataPtr am,
+						 int min,
+						 int max);
+
+XMLPUBFUN xmlRegexpPtr XMLCALL		
+		    xmlAutomataCompile		(xmlAutomataPtr am);
+XMLPUBFUN int XMLCALL	    		
+		    xmlAutomataIsDeterminist	(xmlAutomataPtr am);
+
+#ifdef __cplusplus
+}
+#endif 
+
+#endif /* LIBXML_AUTOMATA_ENABLED */
+#endif /* LIBXML_REGEXP_ENABLED */
+
+#endif /* __XML_AUTOMATA_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlerror.h ./aperios/include/libxml2/libxml/xmlerror.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlerror.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlerror.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,910 @@
+/*
+ * Summary: error handling
+ * Description: the API used to report errors
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#include <libxml/parser.h>
+
+#ifndef __XML_ERROR_H__
+#define __XML_ERROR_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlErrorLevel:
+ *
+ * Indicates the level of an error
+ */
+typedef enum {
+    XML_ERR_NONE = 0,
+    XML_ERR_WARNING = 1,	/* A simple warning */
+    XML_ERR_ERROR = 2,		/* A recoverable error */
+    XML_ERR_FATAL = 3		/* A fatal error */
+} xmlErrorLevel;
+
+/**
+ * xmlErrorDomain:
+ *
+ * Indicates where an error may have come from
+ */
+typedef enum {
+    XML_FROM_NONE = 0,
+    XML_FROM_PARSER,	/* The XML parser */
+    XML_FROM_TREE,	/* The tree module */
+    XML_FROM_NAMESPACE,	/* The XML Namespace module */
+    XML_FROM_DTD,	/* The XML DTD validation with parser context*/
+    XML_FROM_HTML,	/* The HTML parser */
+    XML_FROM_MEMORY,	/* The memory allocator */
+    XML_FROM_OUTPUT,	/* The serialization code */
+    XML_FROM_IO,	/* The Input/Output stack */
+    XML_FROM_FTP,	/* The FTP module */
+    XML_FROM_HTTP,	/* The HTTP module */
+    XML_FROM_XINCLUDE,	/* The XInclude processing */
+    XML_FROM_XPATH,	/* The XPath module */
+    XML_FROM_XPOINTER,	/* The XPointer module */
+    XML_FROM_REGEXP,	/* The regular expressions module */
+    XML_FROM_DATATYPE,	/* The W3C XML Schemas Datatype module */
+    XML_FROM_SCHEMASP,	/* The W3C XML Schemas parser module */
+    XML_FROM_SCHEMASV,	/* The W3C XML Schemas validation module */
+    XML_FROM_RELAXNGP,	/* The Relax-NG parser module */
+    XML_FROM_RELAXNGV,	/* The Relax-NG validator module */
+    XML_FROM_CATALOG,	/* The Catalog module */
+    XML_FROM_C14N,	/* The Canonicalization module */
+    XML_FROM_XSLT,	/* The XSLT engine from libxslt */
+    XML_FROM_VALID,	/* The XML DTD validation with valid context */
+    XML_FROM_CHECK,	/* The error checking module */
+    XML_FROM_WRITER,	/* The xmlwriter module */
+    XML_FROM_MODULE	/* The dynamically loaded module module*/
+} xmlErrorDomain;
+
+/**
+ * xmlError:
+ *
+ * An XML Error instance.
+ */
+
+typedef struct _xmlError xmlError;
+typedef xmlError *xmlErrorPtr;
+struct _xmlError {
+    int		domain;	/* What part of the library raised this error */
+    int		code;	/* The error code, e.g. an xmlParserError */
+    char       *message;/* human-readable informative error message */
+    xmlErrorLevel level;/* how consequent is the error */
+    char       *file;	/* the filename */
+    int		line;	/* the line number if available */
+    char       *str1;	/* extra string information */
+    char       *str2;	/* extra string information */
+    char       *str3;	/* extra string information */
+    int		int1;	/* extra number information */
+    int		int2;	/* column number of the error or 0 if N/A (todo: rename this field when we would break ABI) */
+    void       *ctxt;   /* the parser context if available */
+    void       *node;   /* the node in the tree */
+};
+
+/**
+ * xmlParserError:
+ *
+ * This is an error that the XML (or HTML) parser can generate
+ */
+typedef enum {
+    XML_ERR_OK = 0,
+    XML_ERR_INTERNAL_ERROR, /* 1 */
+    XML_ERR_NO_MEMORY, /* 2 */
+    XML_ERR_DOCUMENT_START, /* 3 */
+    XML_ERR_DOCUMENT_EMPTY, /* 4 */
+    XML_ERR_DOCUMENT_END, /* 5 */
+    XML_ERR_INVALID_HEX_CHARREF, /* 6 */
+    XML_ERR_INVALID_DEC_CHARREF, /* 7 */
+    XML_ERR_INVALID_CHARREF, /* 8 */
+    XML_ERR_INVALID_CHAR, /* 9 */
+    XML_ERR_CHARREF_AT_EOF, /* 10 */
+    XML_ERR_CHARREF_IN_PROLOG, /* 11 */
+    XML_ERR_CHARREF_IN_EPILOG, /* 12 */
+    XML_ERR_CHARREF_IN_DTD, /* 13 */
+    XML_ERR_ENTITYREF_AT_EOF, /* 14 */
+    XML_ERR_ENTITYREF_IN_PROLOG, /* 15 */
+    XML_ERR_ENTITYREF_IN_EPILOG, /* 16 */
+    XML_ERR_ENTITYREF_IN_DTD, /* 17 */
+    XML_ERR_PEREF_AT_EOF, /* 18 */
+    XML_ERR_PEREF_IN_PROLOG, /* 19 */
+    XML_ERR_PEREF_IN_EPILOG, /* 20 */
+    XML_ERR_PEREF_IN_INT_SUBSET, /* 21 */
+    XML_ERR_ENTITYREF_NO_NAME, /* 22 */
+    XML_ERR_ENTITYREF_SEMICOL_MISSING, /* 23 */
+    XML_ERR_PEREF_NO_NAME, /* 24 */
+    XML_ERR_PEREF_SEMICOL_MISSING, /* 25 */
+    XML_ERR_UNDECLARED_ENTITY, /* 26 */
+    XML_WAR_UNDECLARED_ENTITY, /* 27 */
+    XML_ERR_UNPARSED_ENTITY, /* 28 */
+    XML_ERR_ENTITY_IS_EXTERNAL, /* 29 */
+    XML_ERR_ENTITY_IS_PARAMETER, /* 30 */
+    XML_ERR_UNKNOWN_ENCODING, /* 31 */
+    XML_ERR_UNSUPPORTED_ENCODING, /* 32 */
+    XML_ERR_STRING_NOT_STARTED, /* 33 */
+    XML_ERR_STRING_NOT_CLOSED, /* 34 */
+    XML_ERR_NS_DECL_ERROR, /* 35 */
+    XML_ERR_ENTITY_NOT_STARTED, /* 36 */
+    XML_ERR_ENTITY_NOT_FINISHED, /* 37 */
+    XML_ERR_LT_IN_ATTRIBUTE, /* 38 */
+    XML_ERR_ATTRIBUTE_NOT_STARTED, /* 39 */
+    XML_ERR_ATTRIBUTE_NOT_FINISHED, /* 40 */
+    XML_ERR_ATTRIBUTE_WITHOUT_VALUE, /* 41 */
+    XML_ERR_ATTRIBUTE_REDEFINED, /* 42 */
+    XML_ERR_LITERAL_NOT_STARTED, /* 43 */
+    XML_ERR_LITERAL_NOT_FINISHED, /* 44 */
+    XML_ERR_COMMENT_NOT_FINISHED, /* 45 */
+    XML_ERR_PI_NOT_STARTED, /* 46 */
+    XML_ERR_PI_NOT_FINISHED, /* 47 */
+    XML_ERR_NOTATION_NOT_STARTED, /* 48 */
+    XML_ERR_NOTATION_NOT_FINISHED, /* 49 */
+    XML_ERR_ATTLIST_NOT_STARTED, /* 50 */
+    XML_ERR_ATTLIST_NOT_FINISHED, /* 51 */
+    XML_ERR_MIXED_NOT_STARTED, /* 52 */
+    XML_ERR_MIXED_NOT_FINISHED, /* 53 */
+    XML_ERR_ELEMCONTENT_NOT_STARTED, /* 54 */
+    XML_ERR_ELEMCONTENT_NOT_FINISHED, /* 55 */
+    XML_ERR_XMLDECL_NOT_STARTED, /* 56 */
+    XML_ERR_XMLDECL_NOT_FINISHED, /* 57 */
+    XML_ERR_CONDSEC_NOT_STARTED, /* 58 */
+    XML_ERR_CONDSEC_NOT_FINISHED, /* 59 */
+    XML_ERR_EXT_SUBSET_NOT_FINISHED, /* 60 */
+    XML_ERR_DOCTYPE_NOT_FINISHED, /* 61 */
+    XML_ERR_MISPLACED_CDATA_END, /* 62 */
+    XML_ERR_CDATA_NOT_FINISHED, /* 63 */
+    XML_ERR_RESERVED_XML_NAME, /* 64 */
+    XML_ERR_SPACE_REQUIRED, /* 65 */
+    XML_ERR_SEPARATOR_REQUIRED, /* 66 */
+    XML_ERR_NMTOKEN_REQUIRED, /* 67 */
+    XML_ERR_NAME_REQUIRED, /* 68 */
+    XML_ERR_PCDATA_REQUIRED, /* 69 */
+    XML_ERR_URI_REQUIRED, /* 70 */
+    XML_ERR_PUBID_REQUIRED, /* 71 */
+    XML_ERR_LT_REQUIRED, /* 72 */
+    XML_ERR_GT_REQUIRED, /* 73 */
+    XML_ERR_LTSLASH_REQUIRED, /* 74 */
+    XML_ERR_EQUAL_REQUIRED, /* 75 */
+    XML_ERR_TAG_NAME_MISMATCH, /* 76 */
+    XML_ERR_TAG_NOT_FINISHED, /* 77 */
+    XML_ERR_STANDALONE_VALUE, /* 78 */
+    XML_ERR_ENCODING_NAME, /* 79 */
+    XML_ERR_HYPHEN_IN_COMMENT, /* 80 */
+    XML_ERR_INVALID_ENCODING, /* 81 */
+    XML_ERR_EXT_ENTITY_STANDALONE, /* 82 */
+    XML_ERR_CONDSEC_INVALID, /* 83 */
+    XML_ERR_VALUE_REQUIRED, /* 84 */
+    XML_ERR_NOT_WELL_BALANCED, /* 85 */
+    XML_ERR_EXTRA_CONTENT, /* 86 */
+    XML_ERR_ENTITY_CHAR_ERROR, /* 87 */
+    XML_ERR_ENTITY_PE_INTERNAL, /* 88 */
+    XML_ERR_ENTITY_LOOP, /* 89 */
+    XML_ERR_ENTITY_BOUNDARY, /* 90 */
+    XML_ERR_INVALID_URI, /* 91 */
+    XML_ERR_URI_FRAGMENT, /* 92 */
+    XML_WAR_CATALOG_PI, /* 93 */
+    XML_ERR_NO_DTD, /* 94 */
+    XML_ERR_CONDSEC_INVALID_KEYWORD, /* 95 */
+    XML_ERR_VERSION_MISSING, /* 96 */
+    XML_WAR_UNKNOWN_VERSION, /* 97 */
+    XML_WAR_LANG_VALUE, /* 98 */
+    XML_WAR_NS_URI, /* 99 */
+    XML_WAR_NS_URI_RELATIVE, /* 100 */
+    XML_ERR_MISSING_ENCODING, /* 101 */
+    XML_NS_ERR_XML_NAMESPACE = 200,
+    XML_NS_ERR_UNDEFINED_NAMESPACE, /* 201 */
+    XML_NS_ERR_QNAME, /* 202 */
+    XML_NS_ERR_ATTRIBUTE_REDEFINED, /* 203 */
+    XML_DTD_ATTRIBUTE_DEFAULT = 500,
+    XML_DTD_ATTRIBUTE_REDEFINED, /* 501 */
+    XML_DTD_ATTRIBUTE_VALUE, /* 502 */
+    XML_DTD_CONTENT_ERROR, /* 503 */
+    XML_DTD_CONTENT_MODEL, /* 504 */
+    XML_DTD_CONTENT_NOT_DETERMINIST, /* 505 */
+    XML_DTD_DIFFERENT_PREFIX, /* 506 */
+    XML_DTD_ELEM_DEFAULT_NAMESPACE, /* 507 */
+    XML_DTD_ELEM_NAMESPACE, /* 508 */
+    XML_DTD_ELEM_REDEFINED, /* 509 */
+    XML_DTD_EMPTY_NOTATION, /* 510 */
+    XML_DTD_ENTITY_TYPE, /* 511 */
+    XML_DTD_ID_FIXED, /* 512 */
+    XML_DTD_ID_REDEFINED, /* 513 */
+    XML_DTD_ID_SUBSET, /* 514 */
+    XML_DTD_INVALID_CHILD, /* 515 */
+    XML_DTD_INVALID_DEFAULT, /* 516 */
+    XML_DTD_LOAD_ERROR, /* 517 */
+    XML_DTD_MISSING_ATTRIBUTE, /* 518 */
+    XML_DTD_MIXED_CORRUPT, /* 519 */
+    XML_DTD_MULTIPLE_ID, /* 520 */
+    XML_DTD_NO_DOC, /* 521 */
+    XML_DTD_NO_DTD, /* 522 */
+    XML_DTD_NO_ELEM_NAME, /* 523 */
+    XML_DTD_NO_PREFIX, /* 524 */
+    XML_DTD_NO_ROOT, /* 525 */
+    XML_DTD_NOTATION_REDEFINED, /* 526 */
+    XML_DTD_NOTATION_VALUE, /* 527 */
+    XML_DTD_NOT_EMPTY, /* 528 */
+    XML_DTD_NOT_PCDATA, /* 529 */
+    XML_DTD_NOT_STANDALONE, /* 530 */
+    XML_DTD_ROOT_NAME, /* 531 */
+    XML_DTD_STANDALONE_WHITE_SPACE, /* 532 */
+    XML_DTD_UNKNOWN_ATTRIBUTE, /* 533 */
+    XML_DTD_UNKNOWN_ELEM, /* 534 */
+    XML_DTD_UNKNOWN_ENTITY, /* 535 */
+    XML_DTD_UNKNOWN_ID, /* 536 */
+    XML_DTD_UNKNOWN_NOTATION, /* 537 */
+    XML_DTD_STANDALONE_DEFAULTED, /* 538 */
+    XML_DTD_XMLID_VALUE, /* 539 */
+    XML_DTD_XMLID_TYPE, /* 540 */
+    XML_HTML_STRUCURE_ERROR = 800,
+    XML_HTML_UNKNOWN_TAG, /* 801 */
+    XML_RNGP_ANYNAME_ATTR_ANCESTOR = 1000,
+    XML_RNGP_ATTR_CONFLICT, /* 1001 */
+    XML_RNGP_ATTRIBUTE_CHILDREN, /* 1002 */
+    XML_RNGP_ATTRIBUTE_CONTENT, /* 1003 */
+    XML_RNGP_ATTRIBUTE_EMPTY, /* 1004 */
+    XML_RNGP_ATTRIBUTE_NOOP, /* 1005 */
+    XML_RNGP_CHOICE_CONTENT, /* 1006 */
+    XML_RNGP_CHOICE_EMPTY, /* 1007 */
+    XML_RNGP_CREATE_FAILURE, /* 1008 */
+    XML_RNGP_DATA_CONTENT, /* 1009 */
+    XML_RNGP_DEF_CHOICE_AND_INTERLEAVE, /* 1010 */
+    XML_RNGP_DEFINE_CREATE_FAILED, /* 1011 */
+    XML_RNGP_DEFINE_EMPTY, /* 1012 */
+    XML_RNGP_DEFINE_MISSING, /* 1013 */
+    XML_RNGP_DEFINE_NAME_MISSING, /* 1014 */
+    XML_RNGP_ELEM_CONTENT_EMPTY, /* 1015 */
+    XML_RNGP_ELEM_CONTENT_ERROR, /* 1016 */
+    XML_RNGP_ELEMENT_EMPTY, /* 1017 */
+    XML_RNGP_ELEMENT_CONTENT, /* 1018 */
+    XML_RNGP_ELEMENT_NAME, /* 1019 */
+    XML_RNGP_ELEMENT_NO_CONTENT, /* 1020 */
+    XML_RNGP_ELEM_TEXT_CONFLICT, /* 1021 */
+    XML_RNGP_EMPTY, /* 1022 */
+    XML_RNGP_EMPTY_CONSTRUCT, /* 1023 */
+    XML_RNGP_EMPTY_CONTENT, /* 1024 */
+    XML_RNGP_EMPTY_NOT_EMPTY, /* 1025 */
+    XML_RNGP_ERROR_TYPE_LIB, /* 1026 */
+    XML_RNGP_EXCEPT_EMPTY, /* 1027 */
+    XML_RNGP_EXCEPT_MISSING, /* 1028 */
+    XML_RNGP_EXCEPT_MULTIPLE, /* 1029 */
+    XML_RNGP_EXCEPT_NO_CONTENT, /* 1030 */
+    XML_RNGP_EXTERNALREF_EMTPY, /* 1031 */
+    XML_RNGP_EXTERNAL_REF_FAILURE, /* 1032 */
+    XML_RNGP_EXTERNALREF_RECURSE, /* 1033 */
+    XML_RNGP_FORBIDDEN_ATTRIBUTE, /* 1034 */
+    XML_RNGP_FOREIGN_ELEMENT, /* 1035 */
+    XML_RNGP_GRAMMAR_CONTENT, /* 1036 */
+    XML_RNGP_GRAMMAR_EMPTY, /* 1037 */
+    XML_RNGP_GRAMMAR_MISSING, /* 1038 */
+    XML_RNGP_GRAMMAR_NO_START, /* 1039 */
+    XML_RNGP_GROUP_ATTR_CONFLICT, /* 1040 */
+    XML_RNGP_HREF_ERROR, /* 1041 */
+    XML_RNGP_INCLUDE_EMPTY, /* 1042 */
+    XML_RNGP_INCLUDE_FAILURE, /* 1043 */
+    XML_RNGP_INCLUDE_RECURSE, /* 1044 */
+    XML_RNGP_INTERLEAVE_ADD, /* 1045 */
+    XML_RNGP_INTERLEAVE_CREATE_FAILED, /* 1046 */
+    XML_RNGP_INTERLEAVE_EMPTY, /* 1047 */
+    XML_RNGP_INTERLEAVE_NO_CONTENT, /* 1048 */
+    XML_RNGP_INVALID_DEFINE_NAME, /* 1049 */
+    XML_RNGP_INVALID_URI, /* 1050 */
+    XML_RNGP_INVALID_VALUE, /* 1051 */
+    XML_RNGP_MISSING_HREF, /* 1052 */
+    XML_RNGP_NAME_MISSING, /* 1053 */
+    XML_RNGP_NEED_COMBINE, /* 1054 */
+    XML_RNGP_NOTALLOWED_NOT_EMPTY, /* 1055 */
+    XML_RNGP_NSNAME_ATTR_ANCESTOR, /* 1056 */
+    XML_RNGP_NSNAME_NO_NS, /* 1057 */
+    XML_RNGP_PARAM_FORBIDDEN, /* 1058 */
+    XML_RNGP_PARAM_NAME_MISSING, /* 1059 */
+    XML_RNGP_PARENTREF_CREATE_FAILED, /* 1060 */
+    XML_RNGP_PARENTREF_NAME_INVALID, /* 1061 */
+    XML_RNGP_PARENTREF_NO_NAME, /* 1062 */
+    XML_RNGP_PARENTREF_NO_PARENT, /* 1063 */
+    XML_RNGP_PARENTREF_NOT_EMPTY, /* 1064 */
+    XML_RNGP_PARSE_ERROR, /* 1065 */
+    XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME, /* 1066 */
+    XML_RNGP_PAT_ATTR_ATTR, /* 1067 */
+    XML_RNGP_PAT_ATTR_ELEM, /* 1068 */
+    XML_RNGP_PAT_DATA_EXCEPT_ATTR, /* 1069 */
+    XML_RNGP_PAT_DATA_EXCEPT_ELEM, /* 1070 */
+    XML_RNGP_PAT_DATA_EXCEPT_EMPTY, /* 1071 */
+    XML_RNGP_PAT_DATA_EXCEPT_GROUP, /* 1072 */
+    XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE, /* 1073 */
+    XML_RNGP_PAT_DATA_EXCEPT_LIST, /* 1074 */
+    XML_RNGP_PAT_DATA_EXCEPT_ONEMORE, /* 1075 */
+    XML_RNGP_PAT_DATA_EXCEPT_REF, /* 1076 */
+    XML_RNGP_PAT_DATA_EXCEPT_TEXT, /* 1077 */
+    XML_RNGP_PAT_LIST_ATTR, /* 1078 */
+    XML_RNGP_PAT_LIST_ELEM, /* 1079 */
+    XML_RNGP_PAT_LIST_INTERLEAVE, /* 1080 */
+    XML_RNGP_PAT_LIST_LIST, /* 1081 */
+    XML_RNGP_PAT_LIST_REF, /* 1082 */
+    XML_RNGP_PAT_LIST_TEXT, /* 1083 */
+    XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME, /* 1084 */
+    XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME, /* 1085 */
+    XML_RNGP_PAT_ONEMORE_GROUP_ATTR, /* 1086 */
+    XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR, /* 1087 */
+    XML_RNGP_PAT_START_ATTR, /* 1088 */
+    XML_RNGP_PAT_START_DATA, /* 1089 */
+    XML_RNGP_PAT_START_EMPTY, /* 1090 */
+    XML_RNGP_PAT_START_GROUP, /* 1091 */
+    XML_RNGP_PAT_START_INTERLEAVE, /* 1092 */
+    XML_RNGP_PAT_START_LIST, /* 1093 */
+    XML_RNGP_PAT_START_ONEMORE, /* 1094 */
+    XML_RNGP_PAT_START_TEXT, /* 1095 */
+    XML_RNGP_PAT_START_VALUE, /* 1096 */
+    XML_RNGP_PREFIX_UNDEFINED, /* 1097 */
+    XML_RNGP_REF_CREATE_FAILED, /* 1098 */
+    XML_RNGP_REF_CYCLE, /* 1099 */
+    XML_RNGP_REF_NAME_INVALID, /* 1100 */
+    XML_RNGP_REF_NO_DEF, /* 1101 */
+    XML_RNGP_REF_NO_NAME, /* 1102 */
+    XML_RNGP_REF_NOT_EMPTY, /* 1103 */
+    XML_RNGP_START_CHOICE_AND_INTERLEAVE, /* 1104 */
+    XML_RNGP_START_CONTENT, /* 1105 */
+    XML_RNGP_START_EMPTY, /* 1106 */
+    XML_RNGP_START_MISSING, /* 1107 */
+    XML_RNGP_TEXT_EXPECTED, /* 1108 */
+    XML_RNGP_TEXT_HAS_CHILD, /* 1109 */
+    XML_RNGP_TYPE_MISSING, /* 1110 */
+    XML_RNGP_TYPE_NOT_FOUND, /* 1111 */
+    XML_RNGP_TYPE_VALUE, /* 1112 */
+    XML_RNGP_UNKNOWN_ATTRIBUTE, /* 1113 */
+    XML_RNGP_UNKNOWN_COMBINE, /* 1114 */
+    XML_RNGP_UNKNOWN_CONSTRUCT, /* 1115 */
+    XML_RNGP_UNKNOWN_TYPE_LIB, /* 1116 */
+    XML_RNGP_URI_FRAGMENT, /* 1117 */
+    XML_RNGP_URI_NOT_ABSOLUTE, /* 1118 */
+    XML_RNGP_VALUE_EMPTY, /* 1119 */
+    XML_RNGP_VALUE_NO_CONTENT, /* 1120 */
+    XML_RNGP_XMLNS_NAME, /* 1121 */
+    XML_RNGP_XML_NS, /* 1122 */
+    XML_XPATH_EXPRESSION_OK = 1200,
+    XML_XPATH_NUMBER_ERROR, /* 1201 */
+    XML_XPATH_UNFINISHED_LITERAL_ERROR, /* 1202 */
+    XML_XPATH_START_LITERAL_ERROR, /* 1203 */
+    XML_XPATH_VARIABLE_REF_ERROR, /* 1204 */
+    XML_XPATH_UNDEF_VARIABLE_ERROR, /* 1205 */
+    XML_XPATH_INVALID_PREDICATE_ERROR, /* 1206 */
+    XML_XPATH_EXPR_ERROR, /* 1207 */
+    XML_XPATH_UNCLOSED_ERROR, /* 1208 */
+    XML_XPATH_UNKNOWN_FUNC_ERROR, /* 1209 */
+    XML_XPATH_INVALID_OPERAND, /* 1210 */
+    XML_XPATH_INVALID_TYPE, /* 1211 */
+    XML_XPATH_INVALID_ARITY, /* 1212 */
+    XML_XPATH_INVALID_CTXT_SIZE, /* 1213 */
+    XML_XPATH_INVALID_CTXT_POSITION, /* 1214 */
+    XML_XPATH_MEMORY_ERROR, /* 1215 */
+    XML_XPTR_SYNTAX_ERROR, /* 1216 */
+    XML_XPTR_RESOURCE_ERROR, /* 1217 */
+    XML_XPTR_SUB_RESOURCE_ERROR, /* 1218 */
+    XML_XPATH_UNDEF_PREFIX_ERROR, /* 1219 */
+    XML_XPATH_ENCODING_ERROR, /* 1220 */
+    XML_XPATH_INVALID_CHAR_ERROR, /* 1221 */
+    XML_TREE_INVALID_HEX = 1300,
+    XML_TREE_INVALID_DEC, /* 1301 */
+    XML_TREE_UNTERMINATED_ENTITY, /* 1302 */
+    XML_SAVE_NOT_UTF8 = 1400,
+    XML_SAVE_CHAR_INVALID, /* 1401 */
+    XML_SAVE_NO_DOCTYPE, /* 1402 */
+    XML_SAVE_UNKNOWN_ENCODING, /* 1403 */
+    XML_REGEXP_COMPILE_ERROR = 1450,
+    XML_IO_UNKNOWN = 1500,
+    XML_IO_EACCES, /* 1501 */
+    XML_IO_EAGAIN, /* 1502 */
+    XML_IO_EBADF, /* 1503 */
+    XML_IO_EBADMSG, /* 1504 */
+    XML_IO_EBUSY, /* 1505 */
+    XML_IO_ECANCELED, /* 1506 */
+    XML_IO_ECHILD, /* 1507 */
+    XML_IO_EDEADLK, /* 1508 */
+    XML_IO_EDOM, /* 1509 */
+    XML_IO_EEXIST, /* 1510 */
+    XML_IO_EFAULT, /* 1511 */
+    XML_IO_EFBIG, /* 1512 */
+    XML_IO_EINPROGRESS, /* 1513 */
+    XML_IO_EINTR, /* 1514 */
+    XML_IO_EINVAL, /* 1515 */
+    XML_IO_EIO, /* 1516 */
+    XML_IO_EISDIR, /* 1517 */
+    XML_IO_EMFILE, /* 1518 */
+    XML_IO_EMLINK, /* 1519 */
+    XML_IO_EMSGSIZE, /* 1520 */
+    XML_IO_ENAMETOOLONG, /* 1521 */
+    XML_IO_ENFILE, /* 1522 */
+    XML_IO_ENODEV, /* 1523 */
+    XML_IO_ENOENT, /* 1524 */
+    XML_IO_ENOEXEC, /* 1525 */
+    XML_IO_ENOLCK, /* 1526 */
+    XML_IO_ENOMEM, /* 1527 */
+    XML_IO_ENOSPC, /* 1528 */
+    XML_IO_ENOSYS, /* 1529 */
+    XML_IO_ENOTDIR, /* 1530 */
+    XML_IO_ENOTEMPTY, /* 1531 */
+    XML_IO_ENOTSUP, /* 1532 */
+    XML_IO_ENOTTY, /* 1533 */
+    XML_IO_ENXIO, /* 1534 */
+    XML_IO_EPERM, /* 1535 */
+    XML_IO_EPIPE, /* 1536 */
+    XML_IO_ERANGE, /* 1537 */
+    XML_IO_EROFS, /* 1538 */
+    XML_IO_ESPIPE, /* 1539 */
+    XML_IO_ESRCH, /* 1540 */
+    XML_IO_ETIMEDOUT, /* 1541 */
+    XML_IO_EXDEV, /* 1542 */
+    XML_IO_NETWORK_ATTEMPT, /* 1543 */
+    XML_IO_ENCODER, /* 1544 */
+    XML_IO_FLUSH, /* 1545 */
+    XML_IO_WRITE, /* 1546 */
+    XML_IO_NO_INPUT, /* 1547 */
+    XML_IO_BUFFER_FULL, /* 1548 */
+    XML_IO_LOAD_ERROR, /* 1549 */
+    XML_IO_ENOTSOCK, /* 1550 */
+    XML_IO_EISCONN, /* 1551 */
+    XML_IO_ECONNREFUSED, /* 1552 */
+    XML_IO_ENETUNREACH, /* 1553 */
+    XML_IO_EADDRINUSE, /* 1554 */
+    XML_IO_EALREADY, /* 1555 */
+    XML_IO_EAFNOSUPPORT, /* 1556 */
+    XML_XINCLUDE_RECURSION=1600,
+    XML_XINCLUDE_PARSE_VALUE, /* 1601 */
+    XML_XINCLUDE_ENTITY_DEF_MISMATCH, /* 1602 */
+    XML_XINCLUDE_NO_HREF, /* 1603 */
+    XML_XINCLUDE_NO_FALLBACK, /* 1604 */
+    XML_XINCLUDE_HREF_URI, /* 1605 */
+    XML_XINCLUDE_TEXT_FRAGMENT, /* 1606 */
+    XML_XINCLUDE_TEXT_DOCUMENT, /* 1607 */
+    XML_XINCLUDE_INVALID_CHAR, /* 1608 */
+    XML_XINCLUDE_BUILD_FAILED, /* 1609 */
+    XML_XINCLUDE_UNKNOWN_ENCODING, /* 1610 */
+    XML_XINCLUDE_MULTIPLE_ROOT, /* 1611 */
+    XML_XINCLUDE_XPTR_FAILED, /* 1612 */
+    XML_XINCLUDE_XPTR_RESULT, /* 1613 */
+    XML_XINCLUDE_INCLUDE_IN_INCLUDE, /* 1614 */
+    XML_XINCLUDE_FALLBACKS_IN_INCLUDE, /* 1615 */
+    XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE, /* 1616 */
+    XML_XINCLUDE_DEPRECATED_NS, /* 1617 */
+    XML_XINCLUDE_FRAGMENT_ID, /* 1618 */
+    XML_CATALOG_MISSING_ATTR = 1650,
+    XML_CATALOG_ENTRY_BROKEN, /* 1651 */
+    XML_CATALOG_PREFER_VALUE, /* 1652 */
+    XML_CATALOG_NOT_CATALOG, /* 1653 */
+    XML_CATALOG_RECURSION, /* 1654 */
+    XML_SCHEMAP_PREFIX_UNDEFINED = 1700,
+    XML_SCHEMAP_ATTRFORMDEFAULT_VALUE, /* 1701 */
+    XML_SCHEMAP_ATTRGRP_NONAME_NOREF, /* 1702 */
+    XML_SCHEMAP_ATTR_NONAME_NOREF, /* 1703 */
+    XML_SCHEMAP_COMPLEXTYPE_NONAME_NOREF, /* 1704 */
+    XML_SCHEMAP_ELEMFORMDEFAULT_VALUE, /* 1705 */
+    XML_SCHEMAP_ELEM_NONAME_NOREF, /* 1706 */
+    XML_SCHEMAP_EXTENSION_NO_BASE, /* 1707 */
+    XML_SCHEMAP_FACET_NO_VALUE, /* 1708 */
+    XML_SCHEMAP_FAILED_BUILD_IMPORT, /* 1709 */
+    XML_SCHEMAP_GROUP_NONAME_NOREF, /* 1710 */
+    XML_SCHEMAP_IMPORT_NAMESPACE_NOT_URI, /* 1711 */
+    XML_SCHEMAP_IMPORT_REDEFINE_NSNAME, /* 1712 */
+    XML_SCHEMAP_IMPORT_SCHEMA_NOT_URI, /* 1713 */
+    XML_SCHEMAP_INVALID_BOOLEAN, /* 1714 */
+    XML_SCHEMAP_INVALID_ENUM, /* 1715 */
+    XML_SCHEMAP_INVALID_FACET, /* 1716 */
+    XML_SCHEMAP_INVALID_FACET_VALUE, /* 1717 */
+    XML_SCHEMAP_INVALID_MAXOCCURS, /* 1718 */
+    XML_SCHEMAP_INVALID_MINOCCURS, /* 1719 */
+    XML_SCHEMAP_INVALID_REF_AND_SUBTYPE, /* 1720 */
+    XML_SCHEMAP_INVALID_WHITE_SPACE, /* 1721 */
+    XML_SCHEMAP_NOATTR_NOREF, /* 1722 */
+    XML_SCHEMAP_NOTATION_NO_NAME, /* 1723 */
+    XML_SCHEMAP_NOTYPE_NOREF, /* 1724 */
+    XML_SCHEMAP_REF_AND_SUBTYPE, /* 1725 */
+    XML_SCHEMAP_RESTRICTION_NONAME_NOREF, /* 1726 */
+    XML_SCHEMAP_SIMPLETYPE_NONAME, /* 1727 */
+    XML_SCHEMAP_TYPE_AND_SUBTYPE, /* 1728 */
+    XML_SCHEMAP_UNKNOWN_ALL_CHILD, /* 1729 */
+    XML_SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD, /* 1730 */
+    XML_SCHEMAP_UNKNOWN_ATTR_CHILD, /* 1731 */
+    XML_SCHEMAP_UNKNOWN_ATTRGRP_CHILD, /* 1732 */
+    XML_SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP, /* 1733 */
+    XML_SCHEMAP_UNKNOWN_BASE_TYPE, /* 1734 */
+    XML_SCHEMAP_UNKNOWN_CHOICE_CHILD, /* 1735 */
+    XML_SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD, /* 1736 */
+    XML_SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD, /* 1737 */
+    XML_SCHEMAP_UNKNOWN_ELEM_CHILD, /* 1738 */
+    XML_SCHEMAP_UNKNOWN_EXTENSION_CHILD, /* 1739 */
+    XML_SCHEMAP_UNKNOWN_FACET_CHILD, /* 1740 */
+    XML_SCHEMAP_UNKNOWN_FACET_TYPE, /* 1741 */
+    XML_SCHEMAP_UNKNOWN_GROUP_CHILD, /* 1742 */
+    XML_SCHEMAP_UNKNOWN_IMPORT_CHILD, /* 1743 */
+    XML_SCHEMAP_UNKNOWN_LIST_CHILD, /* 1744 */
+    XML_SCHEMAP_UNKNOWN_NOTATION_CHILD, /* 1745 */
+    XML_SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD, /* 1746 */
+    XML_SCHEMAP_UNKNOWN_REF, /* 1747 */
+    XML_SCHEMAP_UNKNOWN_RESTRICTION_CHILD, /* 1748 */
+    XML_SCHEMAP_UNKNOWN_SCHEMAS_CHILD, /* 1749 */
+    XML_SCHEMAP_UNKNOWN_SEQUENCE_CHILD, /* 1750 */
+    XML_SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD, /* 1751 */
+    XML_SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD, /* 1752 */
+    XML_SCHEMAP_UNKNOWN_TYPE, /* 1753 */
+    XML_SCHEMAP_UNKNOWN_UNION_CHILD, /* 1754 */
+    XML_SCHEMAP_ELEM_DEFAULT_FIXED, /* 1755 */
+    XML_SCHEMAP_REGEXP_INVALID, /* 1756 */
+    XML_SCHEMAP_FAILED_LOAD, /* 1757 */
+    XML_SCHEMAP_NOTHING_TO_PARSE, /* 1758 */
+    XML_SCHEMAP_NOROOT, /* 1759 */
+    XML_SCHEMAP_REDEFINED_GROUP, /* 1760 */
+    XML_SCHEMAP_REDEFINED_TYPE, /* 1761 */
+    XML_SCHEMAP_REDEFINED_ELEMENT, /* 1762 */
+    XML_SCHEMAP_REDEFINED_ATTRGROUP, /* 1763 */
+    XML_SCHEMAP_REDEFINED_ATTR, /* 1764 */
+    XML_SCHEMAP_REDEFINED_NOTATION, /* 1765 */
+    XML_SCHEMAP_FAILED_PARSE, /* 1766 */
+    XML_SCHEMAP_UNKNOWN_PREFIX, /* 1767 */
+    XML_SCHEMAP_DEF_AND_PREFIX, /* 1768 */
+    XML_SCHEMAP_UNKNOWN_INCLUDE_CHILD, /* 1769 */
+    XML_SCHEMAP_INCLUDE_SCHEMA_NOT_URI, /* 1770 */
+    XML_SCHEMAP_INCLUDE_SCHEMA_NO_URI, /* 1771 */
+    XML_SCHEMAP_NOT_SCHEMA, /* 1772 */
+    XML_SCHEMAP_UNKNOWN_MEMBER_TYPE, /* 1773 */
+    XML_SCHEMAP_INVALID_ATTR_USE, /* 1774 */
+    XML_SCHEMAP_RECURSIVE, /* 1775 */
+    XML_SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE, /* 1776 */
+    XML_SCHEMAP_INVALID_ATTR_COMBINATION, /* 1777 */
+    XML_SCHEMAP_INVALID_ATTR_INLINE_COMBINATION, /* 1778 */
+    XML_SCHEMAP_MISSING_SIMPLETYPE_CHILD, /* 1779 */
+    XML_SCHEMAP_INVALID_ATTR_NAME, /* 1780 */
+    XML_SCHEMAP_REF_AND_CONTENT, /* 1781 */
+    XML_SCHEMAP_CT_PROPS_CORRECT_1, /* 1782 */
+    XML_SCHEMAP_CT_PROPS_CORRECT_2, /* 1783 */
+    XML_SCHEMAP_CT_PROPS_CORRECT_3, /* 1784 */
+    XML_SCHEMAP_CT_PROPS_CORRECT_4, /* 1785 */
+    XML_SCHEMAP_CT_PROPS_CORRECT_5, /* 1786 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, /* 1787 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1, /* 1788 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2, /* 1789 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2, /* 1790 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3, /* 1791 */
+    XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER, /* 1792 */
+    XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE, /* 1793 */
+    XML_SCHEMAP_UNION_NOT_EXPRESSIBLE, /* 1794 */
+    XML_SCHEMAP_SRC_IMPORT_3_1, /* 1795 */
+    XML_SCHEMAP_SRC_IMPORT_3_2, /* 1796 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1, /* 1797 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2, /* 1798 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_3, /* 1799 */
+    XML_SCHEMAP_COS_CT_EXTENDS_1_3, /* 1800 */
+    XML_SCHEMAV_NOROOT = 1801,
+    XML_SCHEMAV_UNDECLAREDELEM, /* 1802 */
+    XML_SCHEMAV_NOTTOPLEVEL, /* 1803 */
+    XML_SCHEMAV_MISSING, /* 1804 */
+    XML_SCHEMAV_WRONGELEM, /* 1805 */
+    XML_SCHEMAV_NOTYPE, /* 1806 */
+    XML_SCHEMAV_NOROLLBACK, /* 1807 */
+    XML_SCHEMAV_ISABSTRACT, /* 1808 */
+    XML_SCHEMAV_NOTEMPTY, /* 1809 */
+    XML_SCHEMAV_ELEMCONT, /* 1810 */
+    XML_SCHEMAV_HAVEDEFAULT, /* 1811 */
+    XML_SCHEMAV_NOTNILLABLE, /* 1812 */
+    XML_SCHEMAV_EXTRACONTENT, /* 1813 */
+    XML_SCHEMAV_INVALIDATTR, /* 1814 */
+    XML_SCHEMAV_INVALIDELEM, /* 1815 */
+    XML_SCHEMAV_NOTDETERMINIST, /* 1816 */
+    XML_SCHEMAV_CONSTRUCT, /* 1817 */
+    XML_SCHEMAV_INTERNAL, /* 1818 */
+    XML_SCHEMAV_NOTSIMPLE, /* 1819 */
+    XML_SCHEMAV_ATTRUNKNOWN, /* 1820 */
+    XML_SCHEMAV_ATTRINVALID, /* 1821 */
+    XML_SCHEMAV_VALUE, /* 1822 */
+    XML_SCHEMAV_FACET, /* 1823 */
+    XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1, /* 1824 */
+    XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2, /* 1825 */
+    XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3, /* 1826 */
+    XML_SCHEMAV_CVC_TYPE_3_1_1, /* 1827 */
+    XML_SCHEMAV_CVC_TYPE_3_1_2, /* 1828 */
+    XML_SCHEMAV_CVC_FACET_VALID, /* 1829 */
+    XML_SCHEMAV_CVC_LENGTH_VALID, /* 1830 */
+    XML_SCHEMAV_CVC_MINLENGTH_VALID, /* 1831 */
+    XML_SCHEMAV_CVC_MAXLENGTH_VALID, /* 1832 */
+    XML_SCHEMAV_CVC_MININCLUSIVE_VALID, /* 1833 */
+    XML_SCHEMAV_CVC_MAXINCLUSIVE_VALID, /* 1834 */
+    XML_SCHEMAV_CVC_MINEXCLUSIVE_VALID, /* 1835 */
+    XML_SCHEMAV_CVC_MAXEXCLUSIVE_VALID, /* 1836 */
+    XML_SCHEMAV_CVC_TOTALDIGITS_VALID, /* 1837 */
+    XML_SCHEMAV_CVC_FRACTIONDIGITS_VALID, /* 1838 */
+    XML_SCHEMAV_CVC_PATTERN_VALID, /* 1839 */
+    XML_SCHEMAV_CVC_ENUMERATION_VALID, /* 1840 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1, /* 1841 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2, /* 1842 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3, /* 1843 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_2_4, /* 1844 */
+    XML_SCHEMAV_CVC_ELT_1, /* 1845 */
+    XML_SCHEMAV_CVC_ELT_2, /* 1846 */
+    XML_SCHEMAV_CVC_ELT_3_1, /* 1847 */
+    XML_SCHEMAV_CVC_ELT_3_2_1, /* 1848 */
+    XML_SCHEMAV_CVC_ELT_3_2_2, /* 1849 */
+    XML_SCHEMAV_CVC_ELT_4_1, /* 1850 */
+    XML_SCHEMAV_CVC_ELT_4_2, /* 1851 */
+    XML_SCHEMAV_CVC_ELT_4_3, /* 1852 */
+    XML_SCHEMAV_CVC_ELT_5_1_1, /* 1853 */
+    XML_SCHEMAV_CVC_ELT_5_1_2, /* 1854 */
+    XML_SCHEMAV_CVC_ELT_5_2_1, /* 1855 */  
+    XML_SCHEMAV_CVC_ELT_5_2_2_1, /* 1856 */
+    XML_SCHEMAV_CVC_ELT_5_2_2_2_1, /* 1857 */
+    XML_SCHEMAV_CVC_ELT_5_2_2_2_2, /* 1858 */
+    XML_SCHEMAV_CVC_ELT_6, /* 1859 */
+    XML_SCHEMAV_CVC_ELT_7, /* 1860 */
+    XML_SCHEMAV_CVC_ATTRIBUTE_1, /* 1861 */
+    XML_SCHEMAV_CVC_ATTRIBUTE_2, /* 1862 */
+    XML_SCHEMAV_CVC_ATTRIBUTE_3, /* 1863 */
+    XML_SCHEMAV_CVC_ATTRIBUTE_4, /* 1864 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_3_1, /* 1865 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1, /* 1866 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_2, /* 1867 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_4, /* 1868 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_5_1, /* 1869 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_5_2, /* 1870 */
+    XML_SCHEMAV_ELEMENT_CONTENT, /* 1871 */
+    XML_SCHEMAV_DOCUMENT_ELEMENT_MISSING, /* 1872 */
+    XML_SCHEMAV_CVC_COMPLEX_TYPE_1, /* 1873 */
+    XML_SCHEMAV_CVC_AU, /* 1874 */
+    XML_SCHEMAV_CVC_TYPE_1, /* 1875 */
+    XML_SCHEMAV_CVC_TYPE_2, /* 1876 */
+    XML_SCHEMAV_CVC_IDC, /* 1877 */
+    XML_SCHEMAV_CVC_WILDCARD, /* 1878 */
+    XML_XPTR_UNKNOWN_SCHEME = 1900, 
+    XML_XPTR_CHILDSEQ_START, /* 1901 */
+    XML_XPTR_EVAL_FAILED, /* 1902 */
+    XML_XPTR_EXTRA_OBJECTS, /* 1903 */
+    XML_C14N_CREATE_CTXT = 1950,
+    XML_C14N_REQUIRES_UTF8, /* 1951 */
+    XML_C14N_CREATE_STACK, /* 1952 */
+    XML_C14N_INVALID_NODE, /* 1953 */
+    XML_C14N_UNKNOW_NODE, /* 1954 */
+    XML_C14N_RELATIVE_NAMESPACE, /* 1955 */
+    XML_FTP_PASV_ANSWER = 2000,
+    XML_FTP_EPSV_ANSWER, /* 2001 */
+    XML_FTP_ACCNT, /* 2002 */
+    XML_FTP_URL_SYNTAX, /* 2003 */
+    XML_HTTP_URL_SYNTAX = 2020,
+    XML_HTTP_USE_IP, /* 2021 */
+    XML_HTTP_UNKNOWN_HOST, /* 2022 */
+    XML_SCHEMAP_SRC_SIMPLE_TYPE_1 = 3000,
+    XML_SCHEMAP_SRC_SIMPLE_TYPE_2, /* 3001 */
+    XML_SCHEMAP_SRC_SIMPLE_TYPE_3, /* 3002 */
+    XML_SCHEMAP_SRC_SIMPLE_TYPE_4, /* 3003 */
+    XML_SCHEMAP_SRC_RESOLVE, /* 3004 */ 
+    XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE, /* 3005 */
+    XML_SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE, /* 3006 */
+    XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES, /* 3007 */
+    XML_SCHEMAP_ST_PROPS_CORRECT_1, /* 3008 */
+    XML_SCHEMAP_ST_PROPS_CORRECT_2, /* 3009 */
+    XML_SCHEMAP_ST_PROPS_CORRECT_3, /* 3010 */     
+    XML_SCHEMAP_COS_ST_RESTRICTS_1_1, /* 3011 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_1_2, /* 3012 */    
+    XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1, /* 3013 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_1_3_2, /* 3014 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_1, /* 3015 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1, /* 3016 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2, /* 3017 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1, /* 3018 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2, /* 3019 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3, /* 3020 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4, /* 3021 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_5, /* 3022 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_1, /* 3023 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1, /* 3024 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2, /* 3025 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2, /* 3026 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1, /* 3027 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3, /* 3028 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4, /* 3029 */
+    XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_5, /* 3030 */
+    XML_SCHEMAP_COS_ST_DERIVED_OK_2_1, /* 3031 */ 
+    XML_SCHEMAP_COS_ST_DERIVED_OK_2_2, /* 3032 */
+    XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, /* 3033 */
+    XML_SCHEMAP_S4S_ELEM_MISSING, /* 3034 */
+    XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, /* 3035 */
+    XML_SCHEMAP_S4S_ATTR_MISSING, /* 3036 */
+    XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* 3037 */
+    XML_SCHEMAP_SRC_ELEMENT_1, /* 3038 */
+    XML_SCHEMAP_SRC_ELEMENT_2_1, /* 3039 */
+    XML_SCHEMAP_SRC_ELEMENT_2_2, /* 3040 */
+    XML_SCHEMAP_SRC_ELEMENT_3, /* 3041 */
+    XML_SCHEMAP_P_PROPS_CORRECT_1, /* 3042 */
+    XML_SCHEMAP_P_PROPS_CORRECT_2_1, /* 3043 */
+    XML_SCHEMAP_P_PROPS_CORRECT_2_2, /* 3044 */
+    XML_SCHEMAP_E_PROPS_CORRECT_2, /* 3045 */
+    XML_SCHEMAP_E_PROPS_CORRECT_3, /* 3046 */
+    XML_SCHEMAP_E_PROPS_CORRECT_4, /* 3047 */
+    XML_SCHEMAP_E_PROPS_CORRECT_5, /* 3048 */
+    XML_SCHEMAP_E_PROPS_CORRECT_6, /* 3049 */
+    XML_SCHEMAP_SRC_INCLUDE, /* 3050 */    
+    XML_SCHEMAP_SRC_ATTRIBUTE_1, /* 3051 */
+    XML_SCHEMAP_SRC_ATTRIBUTE_2, /* 3052 */
+    XML_SCHEMAP_SRC_ATTRIBUTE_3_1, /* 3053 */
+    XML_SCHEMAP_SRC_ATTRIBUTE_3_2, /* 3054 */
+    XML_SCHEMAP_SRC_ATTRIBUTE_4, /* 3055 */
+    XML_SCHEMAP_NO_XMLNS, /* 3056 */
+    XML_SCHEMAP_NO_XSI, /* 3057 */      
+    XML_SCHEMAP_COS_VALID_DEFAULT_1, /* 3058 */
+    XML_SCHEMAP_COS_VALID_DEFAULT_2_1, /* 3059 */
+    XML_SCHEMAP_COS_VALID_DEFAULT_2_2_1, /* 3060 */
+    XML_SCHEMAP_COS_VALID_DEFAULT_2_2_2, /* 3061 */
+    XML_SCHEMAP_CVC_SIMPLE_TYPE, /* 3062 */
+    XML_SCHEMAP_COS_CT_EXTENDS_1_1, /* 3063 */
+    XML_SCHEMAP_SRC_IMPORT_1_1, /* 3064 */
+    XML_SCHEMAP_SRC_IMPORT_1_2, /* 3065 */
+    XML_SCHEMAP_SRC_IMPORT_2, /* 3066 */
+    XML_SCHEMAP_SRC_IMPORT_2_1, /* 3067 */
+    XML_SCHEMAP_SRC_IMPORT_2_2, /* 3068 */
+    XML_SCHEMAP_INTERNAL, /* 3069 non-W3C */
+    XML_SCHEMAP_NOT_DETERMINISTIC, /* 3070 non-W3C */
+    XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_1, /* 3071 */
+    XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_2, /* 3072 */
+    XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_3, /* 3073 */
+    XML_SCHEMAP_MG_PROPS_CORRECT_1, /* 3074 */
+    XML_SCHEMAP_MG_PROPS_CORRECT_2, /* 3075 */
+    XML_SCHEMAP_SRC_CT_1, /* 3076 */
+    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3, /* 3077 */
+    XML_SCHEMAP_AU_PROPS_CORRECT_2, /* 3078 */
+    XML_SCHEMAP_A_PROPS_CORRECT_2, /* 3079 */
+    XML_MODULE_OPEN = 4900, /* 4900 */
+    XML_MODULE_CLOSE, /* 4901 */
+    XML_CHECK_FOUND_ELEMENT = 5000,
+    XML_CHECK_FOUND_ATTRIBUTE, /* 5001 */
+    XML_CHECK_FOUND_TEXT, /* 5002 */
+    XML_CHECK_FOUND_CDATA, /* 5003 */
+    XML_CHECK_FOUND_ENTITYREF, /* 5004 */
+    XML_CHECK_FOUND_ENTITY, /* 5005 */
+    XML_CHECK_FOUND_PI, /* 5006 */
+    XML_CHECK_FOUND_COMMENT, /* 5007 */
+    XML_CHECK_FOUND_DOCTYPE, /* 5008 */
+    XML_CHECK_FOUND_FRAGMENT, /* 5009 */
+    XML_CHECK_FOUND_NOTATION, /* 5010 */
+    XML_CHECK_UNKNOWN_NODE, /* 5011 */
+    XML_CHECK_ENTITY_TYPE, /* 5012 */
+    XML_CHECK_NO_PARENT, /* 5013 */
+    XML_CHECK_NO_DOC, /* 5014 */
+    XML_CHECK_NO_NAME, /* 5015 */
+    XML_CHECK_NO_ELEM, /* 5016 */
+    XML_CHECK_WRONG_DOC, /* 5017 */
+    XML_CHECK_NO_PREV, /* 5018 */
+    XML_CHECK_WRONG_PREV, /* 5019 */
+    XML_CHECK_NO_NEXT, /* 5020 */
+    XML_CHECK_WRONG_NEXT, /* 5021 */
+    XML_CHECK_NOT_DTD, /* 5022 */
+    XML_CHECK_NOT_ATTR, /* 5023 */
+    XML_CHECK_NOT_ATTR_DECL, /* 5024 */
+    XML_CHECK_NOT_ELEM_DECL, /* 5025 */
+    XML_CHECK_NOT_ENTITY_DECL, /* 5026 */
+    XML_CHECK_NOT_NS_DECL, /* 5027 */
+    XML_CHECK_NO_HREF, /* 5028 */
+    XML_CHECK_WRONG_PARENT,/* 5029 */
+    XML_CHECK_NS_SCOPE, /* 5030 */
+    XML_CHECK_NS_ANCESTOR, /* 5031 */
+    XML_CHECK_NOT_UTF8, /* 5032 */
+    XML_CHECK_NO_DICT, /* 5033 */
+    XML_CHECK_NOT_NCNAME, /* 5034 */
+    XML_CHECK_OUTSIDE_DICT, /* 5035 */
+    XML_CHECK_WRONG_NAME, /* 5036 */
+    XML_CHECK_NAME_NOT_NULL /* 5037 */
+#if 0
+    XML_CHECK_, /* 5033 */
+    XML_CHECK_X /* 503 */
+#endif
+} xmlParserErrors;
+
+/**
+ * xmlGenericErrorFunc:
+ * @ctx:  a parsing context
+ * @msg:  the message
+ * @...:  the extra arguments of the varags to format the message
+ *
+ * Signature of the function to use when there is an error and
+ * no parsing or validity context available .
+ */
+typedef void (*xmlGenericErrorFunc) (void *ctx,
+				 const char *msg,
+	 			 ...);
+/**
+ * xmlStructuredErrorFunc:
+ * @userData:  user provided data for the error callback
+ * @error:  the error being raised.
+ *
+ * Signature of the function to use when there is an error and
+ * the module handles the new error reporting mechanism.
+ */
+typedef void (*xmlStructuredErrorFunc) (void *userData, xmlErrorPtr error);
+
+/*
+ * Use the following function to reset the two global variables
+ * xmlGenericError and xmlGenericErrorContext.
+ */
+XMLPUBFUN void XMLCALL	
+    xmlSetGenericErrorFunc	(void *ctx,
+				 xmlGenericErrorFunc handler);
+XMLPUBFUN void XMLCALL	
+    initGenericErrorDefaultFunc	(xmlGenericErrorFunc *handler);
+
+XMLPUBFUN void XMLCALL	
+    xmlSetStructuredErrorFunc	(void *ctx,
+				 xmlStructuredErrorFunc handler);
+/*
+ * Default message routines used by SAX and Valid context for error
+ * and warning reporting.
+ */
+XMLPUBFUN void XMLCALL	
+    xmlParserError		(void *ctx,
+				 const char *msg,
+				 ...);
+XMLPUBFUN void XMLCALL	
+    xmlParserWarning		(void *ctx,
+				 const char *msg,
+				 ...);
+XMLPUBFUN void XMLCALL	
+    xmlParserValidityError	(void *ctx,
+				 const char *msg,
+				 ...);
+XMLPUBFUN void XMLCALL	
+    xmlParserValidityWarning	(void *ctx,
+				 const char *msg,
+				 ...);
+XMLPUBFUN void XMLCALL	
+    xmlParserPrintFileInfo	(xmlParserInputPtr input);
+XMLPUBFUN void XMLCALL	
+    xmlParserPrintFileContext	(xmlParserInputPtr input);
+
+/*
+ * Extended error information routines
+ */
+XMLPUBFUN xmlErrorPtr XMLCALL
+    xmlGetLastError		(void);
+XMLPUBFUN void XMLCALL
+    xmlResetLastError		(void);
+XMLPUBFUN xmlErrorPtr XMLCALL
+    xmlCtxtGetLastError		(void *ctx);
+XMLPUBFUN void XMLCALL
+    xmlCtxtResetLastError	(void *ctx);
+XMLPUBFUN void XMLCALL
+    xmlResetError		(xmlErrorPtr err);
+XMLPUBFUN int XMLCALL
+    xmlCopyError		(xmlErrorPtr from,
+    				 xmlErrorPtr to);
+
+#ifdef IN_LIBXML
+/*
+ * Internal callback reporting routine
+ */
+XMLPUBFUN void XMLCALL 
+    __xmlRaiseError		(xmlStructuredErrorFunc schannel,
+    				 xmlGenericErrorFunc channel,
+    				 void *data,
+                                 void *ctx,
+    				 void *node,
+    				 int domain,
+				 int code,
+				 xmlErrorLevel level,
+				 const char *file,
+				 int line,
+				 const char *str1,
+				 const char *str2,
+				 const char *str3,
+				 int int1,
+				 int col,
+				 const char *msg,
+				 ...);
+XMLPUBFUN void XMLCALL 
+    __xmlSimpleError		(int domain,
+    				 int code,
+				 xmlNodePtr node,
+				 const char *msg,
+				 const char *extra);
+#endif
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_ERROR_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlexports.h ./aperios/include/libxml2/libxml/xmlexports.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlexports.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlexports.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,138 @@
+/*
+ * Summary: macros for marking symbols as exportable/importable.
+ * Description: macros for marking symbols as exportable/importable.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Igor Zlatovic <igor@zlatkovic.com>
+ */
+
+#ifndef __XML_EXPORTS_H__
+#define __XML_EXPORTS_H__
+
+/**
+ * XMLPUBFUN, XMLPUBVAR, XMLCALL
+ *
+ * Macros which declare an exportable function, an exportable variable and
+ * the calling convention used for functions.
+ *
+ * Please use an extra block for every platform/compiler combination when
+ * modifying this, rather than overlong #ifdef lines. This helps
+ * readability as well as the fact that different compilers on the same
+ * platform might need different definitions.
+ */
+
+/**
+ * XMLPUBFUN:
+ *
+ * Macros which declare an exportable function
+ */
+#define XMLPUBFUN
+/**
+ * XMLPUBVAR:
+ *
+ * Macros which declare an exportable variable
+ */
+#define XMLPUBVAR extern
+/**
+ * XMLCALL:
+ *
+ * Macros which declare the called convention for exported functions
+ */
+#define XMLCALL
+
+/** DOC_DISABLE */
+
+/* Windows platform with MS compiler */
+#if defined(_WIN32) && defined(_MSC_VER)
+  #undef XMLPUBFUN
+  #undef XMLPUBVAR
+  #undef XMLCALL
+  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
+    #define XMLPUBFUN __declspec(dllexport)
+    #define XMLPUBVAR __declspec(dllexport)
+  #else
+    #define XMLPUBFUN
+    #if !defined(LIBXML_STATIC)
+      #define XMLPUBVAR __declspec(dllimport) extern
+    #else
+      #define XMLPUBVAR extern
+    #endif
+  #endif
+  #define XMLCALL __cdecl
+  #if !defined _REENTRANT
+    #define _REENTRANT
+  #endif
+#endif
+
+/* Windows platform with Borland compiler */
+#if defined(_WIN32) && defined(__BORLANDC__)
+  #undef XMLPUBFUN
+  #undef XMLPUBVAR
+  #undef XMLCALL
+  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
+    #define XMLPUBFUN __declspec(dllexport)
+    #define XMLPUBVAR __declspec(dllexport) extern
+  #else
+    #define XMLPUBFUN
+    #if !defined(LIBXML_STATIC)
+      #define XMLPUBVAR __declspec(dllimport) extern
+    #else
+      #define XMLPUBVAR extern
+    #endif
+  #endif
+  #define XMLCALL __cdecl
+  #if !defined _REENTRANT
+    #define _REENTRANT
+  #endif
+#endif
+
+/* Windows platform with GNU compiler (Mingw) */
+#if defined(_WIN32) && defined(__MINGW32__)
+  #undef XMLPUBFUN
+  #undef XMLPUBVAR
+  #undef XMLCALL
+  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
+    #define XMLPUBFUN __declspec(dllexport)
+    #define XMLPUBVAR __declspec(dllexport)
+  #else
+    #define XMLPUBFUN
+    #if !defined(LIBXML_STATIC)
+      #define XMLPUBVAR __declspec(dllimport) extern
+    #else
+      #define XMLPUBVAR extern
+    #endif
+  #endif
+  #define XMLCALL __cdecl
+  #if !defined _REENTRANT
+    #define _REENTRANT
+  #endif
+#endif
+
+/* Cygwin platform, GNU compiler */
+#if defined(_WIN32) && defined(__CYGWIN__)
+  #undef XMLPUBFUN
+  #undef XMLPUBVAR
+  #undef XMLCALL
+  #if defined(IN_LIBXML) && !defined(LIBXML_STATIC)
+    #define XMLPUBFUN __declspec(dllexport)
+    #define XMLPUBVAR __declspec(dllexport)
+  #else
+    #define XMLPUBFUN
+    #if !defined(LIBXML_STATIC)
+      #define XMLPUBVAR __declspec(dllimport) extern
+    #else
+      #define XMLPUBVAR
+    #endif
+  #endif
+  #define XMLCALL __cdecl
+#endif
+
+/* Compatibility */
+#if !defined(LIBXML_DLL_IMPORT)
+#define LIBXML_DLL_IMPORT XMLPUBVAR
+#endif
+
+#endif /* __XML_EXPORTS_H__ */
+
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlmemory.h ./aperios/include/libxml2/libxml/xmlmemory.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlmemory.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlmemory.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,222 @@
+/*
+ * Summary: interface for the memory allocator
+ * Description: provides interfaces for the memory allocator,
+ *              including debugging capabilities.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+
+#ifndef __DEBUG_MEMORY_ALLOC__
+#define __DEBUG_MEMORY_ALLOC__
+
+#include <stdio.h>
+#include <libxml/xmlversion.h>
+
+/**
+ * DEBUG_MEMORY:
+ *
+ * DEBUG_MEMORY replaces the allocator with a collect and debug
+ * shell to the libc allocator.
+ * DEBUG_MEMORY should only be activated when debugging 
+ * libxml i.e. if libxml has been configured with --with-debug-mem too.
+ */
+/* #define DEBUG_MEMORY_FREED */
+/* #define DEBUG_MEMORY_LOCATION */
+
+#ifdef DEBUG
+#ifndef DEBUG_MEMORY
+#define DEBUG_MEMORY
+#endif
+#endif
+
+/**
+ * DEBUG_MEMORY_LOCATION:
+ *
+ * DEBUG_MEMORY_LOCATION should be activated only when debugging 
+ * libxml i.e. if libxml has been configured with --with-debug-mem too.
+ */
+#ifdef DEBUG_MEMORY_LOCATION
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The XML memory wrapper support 4 basic overloadable functions.
+ */
+/**
+ * xmlFreeFunc:
+ * @mem: an already allocated block of memory
+ *
+ * Signature for a free() implementation.
+ */
+typedef void (XMLCALL *xmlFreeFunc)(void *mem);
+/**
+ * xmlMallocFunc:
+ * @size:  the size requested in bytes
+ *
+ * Signature for a malloc() implementation.
+ *
+ * Returns a pointer to the newly allocated block or NULL in case of error.
+ */
+typedef void *(XMLCALL *xmlMallocFunc)(size_t size);
+
+/**
+ * xmlReallocFunc:
+ * @mem: an already allocated block of memory
+ * @size:  the new size requested in bytes
+ *
+ * Signature for a realloc() implementation.
+ *
+ * Returns a pointer to the newly reallocated block or NULL in case of error.
+ */
+typedef void *(XMLCALL *xmlReallocFunc)(void *mem, size_t size);
+
+/**
+ * xmlStrdupFunc:
+ * @str: a zero terminated string
+ *
+ * Signature for an strdup() implementation.
+ *
+ * Returns the copy of the string or NULL in case of error.
+ */
+typedef char *(XMLCALL *xmlStrdupFunc)(const char *str);
+
+/*
+ * The 4 interfaces used for all memory handling within libxml.
+LIBXML_DLL_IMPORT extern xmlFreeFunc xmlFree;
+LIBXML_DLL_IMPORT extern xmlMallocFunc xmlMalloc;
+LIBXML_DLL_IMPORT extern xmlMallocFunc xmlMallocAtomic;
+LIBXML_DLL_IMPORT extern xmlReallocFunc xmlRealloc;
+LIBXML_DLL_IMPORT extern xmlStrdupFunc xmlMemStrdup;
+ */
+
+/*
+ * The way to overload the existing functions.
+ * The xmlGc function have an extra entry for atomic block
+ * allocations useful for garbage collected memory allocators
+ */
+XMLPUBFUN int XMLCALL
+	xmlMemSetup	(xmlFreeFunc freeFunc,
+			 xmlMallocFunc mallocFunc,
+			 xmlReallocFunc reallocFunc,
+			 xmlStrdupFunc strdupFunc);
+XMLPUBFUN int XMLCALL     
+	xmlMemGet	(xmlFreeFunc *freeFunc,
+			 xmlMallocFunc *mallocFunc,
+			 xmlReallocFunc *reallocFunc,
+			 xmlStrdupFunc *strdupFunc);
+XMLPUBFUN int XMLCALL     
+	xmlGcMemSetup	(xmlFreeFunc freeFunc,
+			 xmlMallocFunc mallocFunc,
+			 xmlMallocFunc mallocAtomicFunc,
+			 xmlReallocFunc reallocFunc,
+			 xmlStrdupFunc strdupFunc);
+XMLPUBFUN int XMLCALL     
+	xmlGcMemGet	(xmlFreeFunc *freeFunc,
+			 xmlMallocFunc *mallocFunc,
+			 xmlMallocFunc *mallocAtomicFunc,
+			 xmlReallocFunc *reallocFunc,
+			 xmlStrdupFunc *strdupFunc);
+
+/*
+ * Initialization of the memory layer.
+ */
+XMLPUBFUN int XMLCALL	
+	xmlInitMemory	(void);
+
+/* 
+ * Cleanup of the memory layer.
+ */
+XMLPUBFUN void XMLCALL                
+                xmlCleanupMemory        (void);
+/*
+ * These are specific to the XML debug memory wrapper.
+ */
+XMLPUBFUN int XMLCALL	
+	xmlMemUsed	(void);
+XMLPUBFUN int XMLCALL	
+	xmlMemBlocks	(void);
+XMLPUBFUN void XMLCALL	
+	xmlMemDisplay	(FILE *fp);
+XMLPUBFUN void XMLCALL	
+	xmlMemShow	(FILE *fp, int nr);
+XMLPUBFUN void XMLCALL	
+	xmlMemoryDump	(void);
+XMLPUBFUN void * XMLCALL	
+	xmlMemMalloc	(size_t size);
+XMLPUBFUN void * XMLCALL	
+	xmlMemRealloc	(void *ptr,size_t size);
+XMLPUBFUN void XMLCALL	
+	xmlMemFree	(void *ptr);
+XMLPUBFUN char * XMLCALL	
+	xmlMemoryStrdup	(const char *str);
+XMLPUBFUN void * XMLCALL  
+	xmlMallocLoc	(size_t size, const char *file, int line);
+XMLPUBFUN void * XMLCALL	
+	xmlReallocLoc	(void *ptr, size_t size, const char *file, int line);
+XMLPUBFUN void * XMLCALL	
+	xmlMallocAtomicLoc (size_t size, const char *file, int line);
+XMLPUBFUN char * XMLCALL	
+	xmlMemStrdupLoc	(const char *str, const char *file, int line);
+
+
+#ifdef DEBUG_MEMORY_LOCATION
+/**
+ * xmlMalloc:
+ * @size:  number of bytes to allocate
+ *
+ * Wrapper for the malloc() function used in the XML library.
+ *
+ * Returns the pointer to the allocated area or NULL in case of error.
+ */
+#define xmlMalloc(size) xmlMallocLoc((size), __FILE__, __LINE__)
+/**
+ * xmlMallocAtomic:
+ * @size:  number of bytes to allocate
+ *
+ * Wrapper for the malloc() function used in the XML library for allocation
+ * of block not containing pointers to other areas.
+ *
+ * Returns the pointer to the allocated area or NULL in case of error.
+ */
+#define xmlMallocAtomic(size) xmlMallocAtomicLoc((size), __FILE__, __LINE__)
+/**
+ * xmlRealloc:
+ * @ptr:  pointer to the existing allocated area
+ * @size:  number of bytes to allocate
+ *
+ * Wrapper for the realloc() function used in the XML library.
+ *
+ * Returns the pointer to the allocated area or NULL in case of error.
+ */
+#define xmlRealloc(ptr, size) xmlReallocLoc((ptr), (size), __FILE__, __LINE__)
+/**
+ * xmlMemStrdup:
+ * @str:  pointer to the existing string
+ *
+ * Wrapper for the strdup() function, xmlStrdup() is usually preferred.
+ *
+ * Returns the pointer to the allocated area or NULL in case of error.
+ */
+#define xmlMemStrdup(str) xmlMemStrdupLoc((str), __FILE__, __LINE__)
+
+#endif /* DEBUG_MEMORY_LOCATION */
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#ifndef __XML_GLOBALS_H
+#ifndef __XML_THREADS_H__
+#include <libxml/threads.h>
+#include <libxml/globals.h>
+#endif
+#endif
+
+#endif  /* __DEBUG_MEMORY_ALLOC__ */
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlmodule.h ./aperios/include/libxml2/libxml/xmlmodule.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlmodule.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlmodule.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,57 @@
+/*
+ * Summary: dynamic module loading
+ * Description: basic API for dynamic module loading, used by
+ *              libexslt added in 2.6.17
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Joel W. Reed
+ */
+
+#ifndef __XML_MODULE_H__
+#define __XML_MODULE_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_MODULES_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlModulePtr:
+ *
+ * A handle to a dynamically loaded module
+ */
+typedef struct _xmlModule xmlModule;
+typedef xmlModule *xmlModulePtr;
+
+/**
+ * xmlModuleOption:
+ *
+ * enumeration of options that can be passed down to xmlModuleOpen()
+ */
+typedef enum {
+    XML_MODULE_LAZY = 1,	/* lazy binding */
+    XML_MODULE_LOCAL= 2		/* local binding */
+} xmlModuleOption;
+
+XMLPUBFUN xmlModulePtr XMLCALL xmlModuleOpen	(const char *filename,
+						 int options);
+
+XMLPUBFUN int XMLCALL xmlModuleSymbol		(xmlModulePtr module,
+						 const char* name,
+						 void **result);
+
+XMLPUBFUN int XMLCALL xmlModuleClose		(xmlModulePtr module);
+
+XMLPUBFUN int XMLCALL xmlModuleFree		(xmlModulePtr module);
+
+#ifdef __cplusplus
+}
+#endif 
+
+#endif /* LIBXML_MODULES_ENABLED */
+
+#endif /*__XML_MODULE_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlreader.h ./aperios/include/libxml2/libxml/xmlreader.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlreader.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlreader.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,392 @@
+/*
+ * Summary: the XMLReader implementation
+ * Description: API of the XML streaming API based on C# interfaces.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_XMLREADER_H__
+#define __XML_XMLREADER_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+#include <libxml/xmlIO.h>
+#ifdef LIBXML_SCHEMAS_ENABLED
+#include <libxml/relaxng.h>
+#endif
+
+#ifdef LIBXML_READER_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlTextReaderMode:
+ *
+ * Internal state values for the reader.
+ */
+typedef enum {
+    XML_TEXTREADER_MODE_INITIAL = 0,
+    XML_TEXTREADER_MODE_INTERACTIVE = 1,
+    XML_TEXTREADER_MODE_ERROR = 2,
+    XML_TEXTREADER_MODE_EOF =3,
+    XML_TEXTREADER_MODE_CLOSED = 4,
+    XML_TEXTREADER_MODE_READING = 5
+} xmlTextReaderMode;
+
+/**
+ * xmlParserProperties:
+ *
+ * Some common options to use with xmlTextReaderSetParserProp, but it
+ * is better to use xmlParserOption and the xmlReaderNewxxx and 
+ * xmlReaderForxxx APIs now.
+ */
+typedef enum {
+    XML_PARSER_LOADDTD = 1,
+    XML_PARSER_DEFAULTATTRS = 2,
+    XML_PARSER_VALIDATE = 3,
+    XML_PARSER_SUBST_ENTITIES = 4
+} xmlParserProperties;
+
+/**
+ * xmlParserSeverities:
+ *
+ * How severe an error callback is when the per-reader error callback API
+ * is used.
+ */
+typedef enum {
+    XML_PARSER_SEVERITY_VALIDITY_WARNING = 1,
+    XML_PARSER_SEVERITY_VALIDITY_ERROR = 2,
+    XML_PARSER_SEVERITY_WARNING = 3,
+    XML_PARSER_SEVERITY_ERROR = 4
+} xmlParserSeverities;
+
+/**
+ * xmlReaderTypes:
+ *
+ * Predefined constants for the different types of nodes.
+ */
+typedef enum {
+    XML_READER_TYPE_NONE = 0,
+    XML_READER_TYPE_ELEMENT = 1,
+    XML_READER_TYPE_ATTRIBUTE = 2,
+    XML_READER_TYPE_TEXT = 3,
+    XML_READER_TYPE_CDATA = 4,
+    XML_READER_TYPE_ENTITY_REFERENCE = 5,
+    XML_READER_TYPE_ENTITY = 6,
+    XML_READER_TYPE_PROCESSING_INSTRUCTION = 7,
+    XML_READER_TYPE_COMMENT = 8,
+    XML_READER_TYPE_DOCUMENT = 9,
+    XML_READER_TYPE_DOCUMENT_TYPE = 10,
+    XML_READER_TYPE_DOCUMENT_FRAGMENT = 11,
+    XML_READER_TYPE_NOTATION = 12,
+    XML_READER_TYPE_WHITESPACE = 13,
+    XML_READER_TYPE_SIGNIFICANT_WHITESPACE = 14,
+    XML_READER_TYPE_END_ELEMENT = 15,
+    XML_READER_TYPE_END_ENTITY = 16,
+    XML_READER_TYPE_XML_DECLARATION = 17
+} xmlReaderTypes;
+
+/**
+ * xmlTextReader:
+ *
+ * Structure for an xmlReader context.
+ */
+typedef struct _xmlTextReader xmlTextReader;
+
+/**
+ * xmlTextReaderPtr:
+ *
+ * Pointer to an xmlReader context.
+ */
+typedef xmlTextReader *xmlTextReaderPtr;
+
+/*
+ * Constructors & Destructor
+ */
+XMLPUBFUN xmlTextReaderPtr XMLCALL
+			xmlNewTextReader	(xmlParserInputBufferPtr input,
+	                                         const char *URI);
+XMLPUBFUN xmlTextReaderPtr XMLCALL	
+			xmlNewTextReaderFilename(const char *URI);
+XMLPUBFUN void XMLCALL			
+			xmlFreeTextReader	(xmlTextReaderPtr reader);
+
+/*
+ * Iterators
+ */
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderRead	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderReadInnerXml	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderReadOuterXml	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderReadString		(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderReadAttributeValue	(xmlTextReaderPtr reader);
+
+/*
+ * Attributes of the node
+ */
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderAttributeCount(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderDepth	(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderHasAttributes(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderHasValue(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderIsDefault	(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderIsEmptyElement(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderNodeType	(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderQuoteChar	(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+			xmlTextReaderReadState	(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL
+                        xmlTextReaderIsNamespaceDecl(xmlTextReaderPtr reader);
+
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstBaseUri	(xmlTextReaderPtr reader);
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstLocalName	(xmlTextReaderPtr reader);
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstName	(xmlTextReaderPtr reader);
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstNamespaceUri(xmlTextReaderPtr reader);
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstPrefix	(xmlTextReaderPtr reader);
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstXmlLang	(xmlTextReaderPtr reader);
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstString	(xmlTextReaderPtr reader,
+		    				 const xmlChar *str);
+XMLPUBFUN const xmlChar * XMLCALL	
+		    xmlTextReaderConstValue	(xmlTextReaderPtr reader);
+
+/*
+ * use the Const version of the routine for
+ * better performance and simpler code
+ */
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderBaseUri	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderLocalName	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderName	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderNamespaceUri(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderPrefix	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderXmlLang	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+			xmlTextReaderValue	(xmlTextReaderPtr reader);
+
+/*
+ * Methods of the XmlTextReader
+ */
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderClose		(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+		    xmlTextReaderGetAttributeNo	(xmlTextReaderPtr reader,
+						 int no);
+XMLPUBFUN xmlChar * XMLCALL	
+		    xmlTextReaderGetAttribute	(xmlTextReaderPtr reader,
+						 const xmlChar *name);
+XMLPUBFUN xmlChar * XMLCALL	
+		    xmlTextReaderGetAttributeNs	(xmlTextReaderPtr reader,
+						 const xmlChar *localName,
+						 const xmlChar *namespaceURI);
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL 
+		    xmlTextReaderGetRemainder	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlChar * XMLCALL	
+		    xmlTextReaderLookupNamespace(xmlTextReaderPtr reader,
+						 const xmlChar *prefix);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderMoveToAttributeNo(xmlTextReaderPtr reader,
+						 int no);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderMoveToAttribute(xmlTextReaderPtr reader,
+						 const xmlChar *name);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderMoveToAttributeNs(xmlTextReaderPtr reader,
+						 const xmlChar *localName,
+						 const xmlChar *namespaceURI);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderMoveToFirstAttribute(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderMoveToNextAttribute(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderMoveToElement	(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderNormalization	(xmlTextReaderPtr reader);
+XMLPUBFUN const xmlChar * XMLCALL
+		    xmlTextReaderConstEncoding  (xmlTextReaderPtr reader);
+
+/*
+ * Extensions
+ */
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderSetParserProp	(xmlTextReaderPtr reader,
+						 int prop,
+						 int value);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderGetParserProp	(xmlTextReaderPtr reader,
+						 int prop);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		    xmlTextReaderCurrentNode	(xmlTextReaderPtr reader);
+
+XMLPUBFUN int XMLCALL
+            xmlTextReaderGetParserLineNumber(xmlTextReaderPtr reader);
+
+XMLPUBFUN int XMLCALL
+            xmlTextReaderGetParserColumnNumber(xmlTextReaderPtr reader);
+
+XMLPUBFUN xmlNodePtr XMLCALL	
+		    xmlTextReaderPreserve	(xmlTextReaderPtr reader);
+#ifdef LIBXML_PATTERN_ENABLED
+XMLPUBFUN int XMLCALL	
+		    xmlTextReaderPreservePattern(xmlTextReaderPtr reader,
+		    				 const xmlChar *pattern,
+						 const xmlChar **namespaces);
+#endif /* LIBXML_PATTERN_ENABLED */
+XMLPUBFUN xmlDocPtr XMLCALL	
+		    xmlTextReaderCurrentDoc	(xmlTextReaderPtr reader);
+XMLPUBFUN xmlNodePtr XMLCALL	
+		    xmlTextReaderExpand		(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderNext		(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL
+		    xmlTextReaderNextSibling	(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderIsValid	(xmlTextReaderPtr reader);
+#ifdef LIBXML_SCHEMAS_ENABLED
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderRelaxNGValidate(xmlTextReaderPtr reader,
+						 const char *rng);
+XMLPUBFUN int XMLCALL		
+		    xmlTextReaderRelaxNGSetSchema(xmlTextReaderPtr reader,
+						 xmlRelaxNGPtr schema);
+#endif
+XMLPUBFUN const xmlChar * XMLCALL
+		    xmlTextReaderConstXmlVersion(xmlTextReaderPtr reader);
+XMLPUBFUN int XMLCALL
+		    xmlTextReaderStandalone     (xmlTextReaderPtr reader);
+
+
+/*
+ * Index lookup
+ */
+XMLPUBFUN long XMLCALL
+		xmlTextReaderByteConsumed	(xmlTextReaderPtr reader);
+
+/*
+ * New more complete APIs for simpler creation and reuse of readers
+ */
+XMLPUBFUN xmlTextReaderPtr XMLCALL
+		xmlReaderWalker		(xmlDocPtr doc);
+XMLPUBFUN xmlTextReaderPtr XMLCALL
+		xmlReaderForDoc		(const xmlChar * cur,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlTextReaderPtr XMLCALL
+		xmlReaderForFile	(const char *filename,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlTextReaderPtr XMLCALL
+		xmlReaderForMemory	(const char *buffer,
+					 int size,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlTextReaderPtr XMLCALL
+		xmlReaderForFd		(int fd,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlTextReaderPtr XMLCALL
+		xmlReaderForIO		(xmlInputReadCallback ioread,
+					 xmlInputCloseCallback ioclose,
+					 void *ioctx,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+
+XMLPUBFUN int XMLCALL
+		xmlReaderNewWalker	(xmlTextReaderPtr reader,
+					 xmlDocPtr doc);
+XMLPUBFUN int XMLCALL
+		xmlReaderNewDoc		(xmlTextReaderPtr reader,
+					 const xmlChar * cur,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN int XMLCALL
+		xmlReaderNewFile	(xmlTextReaderPtr reader,
+					 const char *filename,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN int XMLCALL
+		xmlReaderNewMemory	(xmlTextReaderPtr reader,
+					 const char *buffer,
+					 int size,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN int XMLCALL
+		xmlReaderNewFd		(xmlTextReaderPtr reader,
+					 int fd,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN int XMLCALL
+		xmlReaderNewIO		(xmlTextReaderPtr reader,
+					 xmlInputReadCallback ioread,
+					 xmlInputCloseCallback ioclose,
+					 void *ioctx,
+					 const char *URL,
+					 const char *encoding,
+					 int options);
+/*
+ * Error handling extensions
+ */
+typedef void *  xmlTextReaderLocatorPtr;
+typedef void   (XMLCALL *xmlTextReaderErrorFunc)        (void *arg, 
+						 const char *msg,
+						 xmlParserSeverities severity,
+						 xmlTextReaderLocatorPtr locator);
+XMLPUBFUN int XMLCALL             
+		    xmlTextReaderLocatorLineNumber(xmlTextReaderLocatorPtr locator);
+/*int             xmlTextReaderLocatorLinePosition(xmlTextReaderLocatorPtr locator);*/
+XMLPUBFUN xmlChar * XMLCALL       
+		    xmlTextReaderLocatorBaseURI (xmlTextReaderLocatorPtr locator);
+XMLPUBFUN void XMLCALL            
+		    xmlTextReaderSetErrorHandler(xmlTextReaderPtr reader, 
+						 xmlTextReaderErrorFunc f, 
+						 void *arg);
+XMLPUBFUN void XMLCALL
+		    xmlTextReaderSetStructuredErrorHandler(xmlTextReaderPtr reader,
+							   xmlStructuredErrorFunc f,
+							   void *arg);
+XMLPUBFUN void XMLCALL            
+		    xmlTextReaderGetErrorHandler(xmlTextReaderPtr reader, 
+						 xmlTextReaderErrorFunc *f, 
+						 void **arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_READER_ENABLED */
+
+#endif /* __XML_XMLREADER_H__ */
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlregexp.h ./aperios/include/libxml2/libxml/xmlregexp.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlregexp.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlregexp.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,108 @@
+/*
+ * Summary: regular expressions handling
+ * Description: basic API for libxml regular expressions handling used
+ *              for XML Schemas and validation.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_REGEXP_H__
+#define __XML_REGEXP_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_REGEXP_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlRegexpPtr:
+ *
+ * A libxml regular expression, they can actually be far more complex
+ * thank the POSIX regex expressions.
+ */
+typedef struct _xmlRegexp xmlRegexp;
+typedef xmlRegexp *xmlRegexpPtr;
+
+/**
+ * xmlRegExecCtxtPtr:
+ *
+ * A libxml progressive regular expression evaluation context
+ */
+typedef struct _xmlRegExecCtxt xmlRegExecCtxt;
+typedef xmlRegExecCtxt *xmlRegExecCtxtPtr;
+
+#ifdef __cplusplus
+}
+#endif 
+#include <libxml/tree.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The POSIX like API
+ */
+XMLPUBFUN xmlRegexpPtr XMLCALL
+		    xmlRegexpCompile	(const xmlChar *regexp);
+XMLPUBFUN void XMLCALL			 xmlRegFreeRegexp(xmlRegexpPtr regexp);
+XMLPUBFUN int XMLCALL			
+		    xmlRegexpExec	(xmlRegexpPtr comp,
+					 const xmlChar *value);
+XMLPUBFUN void XMLCALL			
+    		    xmlRegexpPrint	(FILE *output,
+					 xmlRegexpPtr regexp);
+XMLPUBFUN int XMLCALL			
+		    xmlRegexpIsDeterminist(xmlRegexpPtr comp);
+
+/*
+ * Callback function when doing a transition in the automata
+ */
+typedef void (*xmlRegExecCallbacks) (xmlRegExecCtxtPtr exec,
+	                             const xmlChar *token,
+				     void *transdata,
+				     void *inputdata);
+
+/*
+ * The progressive API
+ */
+XMLPUBFUN xmlRegExecCtxtPtr XMLCALL	
+    		    xmlRegNewExecCtxt	(xmlRegexpPtr comp,
+					 xmlRegExecCallbacks callback,
+					 void *data);
+XMLPUBFUN void XMLCALL			
+		    xmlRegFreeExecCtxt	(xmlRegExecCtxtPtr exec);
+XMLPUBFUN int XMLCALL			
+    		    xmlRegExecPushString(xmlRegExecCtxtPtr exec,
+					 const xmlChar *value,
+					 void *data);
+XMLPUBFUN int XMLCALL			
+		    xmlRegExecPushString2(xmlRegExecCtxtPtr exec,
+					 const xmlChar *value,
+					 const xmlChar *value2,
+					 void *data);
+
+XMLPUBFUN int XMLCALL
+		    xmlRegExecNextValues(xmlRegExecCtxtPtr exec,
+		    			 int *nbval,
+		    			 int *nbneg,
+					 xmlChar **values,
+					 int *terminal);
+XMLPUBFUN int XMLCALL
+		    xmlRegExecErrInfo	(xmlRegExecCtxtPtr exec,
+		    			 const xmlChar **string,
+					 int *nbval,
+		    			 int *nbneg,
+					 xmlChar **values,
+					 int *terminal);
+#ifdef __cplusplus
+}
+#endif 
+
+#endif /* LIBXML_REGEXP_ENABLED */
+
+#endif /*__XML_REGEXP_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlsave.h ./aperios/include/libxml2/libxml/xmlsave.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlsave.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlsave.h	Wed Jun  1 01:48:01 2005
@@ -0,0 +1,83 @@
+/*
+ * Summary: the XML document serializer
+ * Description: API to save document or subtree of document
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_XMLSAVE_H__
+#define __XML_XMLSAVE_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/tree.h>
+#include <libxml/encoding.h>
+#include <libxml/xmlIO.h>
+
+#ifdef LIBXML_OUTPUT_ENABLED
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlSaveOption:
+ *
+ * This is the set of XML save options that can be passed down
+ * to the xmlSaveToFd() and similar calls.
+ */
+typedef enum {
+    XML_SAVE_FORMAT     = 1<<0	/* format save output */
+} xmlSaveOption;
+
+
+typedef struct _xmlSaveCtxt xmlSaveCtxt;
+typedef xmlSaveCtxt *xmlSaveCtxtPtr;
+
+XMLPUBFUN xmlSaveCtxtPtr XMLCALL
+		xmlSaveToFd		(int fd,
+					 const char *encoding,
+					 int options);
+XMLPUBFUN xmlSaveCtxtPtr XMLCALL
+		xmlSaveToFilename	(const char *filename,
+					 const char *encoding,
+					 int options);
+/******
+  Not yet implemented.
+
+XMLPUBFUN xmlSaveCtxtPtr XMLCALL
+		xmlSaveToBuffer		(xmlBufferPtr buffer,
+					 const char *encoding,
+					 int options);
+ ******/
+XMLPUBFUN xmlSaveCtxtPtr XMLCALL
+		xmlSaveToIO		(xmlOutputWriteCallback iowrite,
+					 xmlOutputCloseCallback ioclose,
+					 void *ioctx,
+					 const char *encoding,
+					 int options);
+
+XMLPUBFUN long XMLCALL
+		xmlSaveDoc		(xmlSaveCtxtPtr ctxt,
+					 xmlDocPtr doc);
+XMLPUBFUN long XMLCALL
+		xmlSaveTree		(xmlSaveCtxtPtr ctxt,
+					 xmlNodePtr node);
+
+XMLPUBFUN int XMLCALL
+		xmlSaveFlush		(xmlSaveCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL
+		xmlSaveClose		(xmlSaveCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL
+		xmlSaveSetEscape	(xmlSaveCtxtPtr ctxt,
+					 xmlCharEncodingOutputFunc escape);
+XMLPUBFUN int XMLCALL
+		xmlSaveSetAttrEscape	(xmlSaveCtxtPtr ctxt,
+					 xmlCharEncodingOutputFunc escape);
+#ifdef __cplusplus
+}
+#endif
+#endif /* LIBXML_OUTPUT_ENABLED */
+#endif /* __XML_XMLSAVE_H__ */
+
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlschemas.h ./aperios/include/libxml2/libxml/xmlschemas.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlschemas.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlschemas.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,170 @@
+/*
+ * Summary: incomplete XML Schemas structure implementation
+ * Description: interface to the XML Schemas handling and schema validity
+ *              checking, it is incomplete right now.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+
+#ifndef __XML_SCHEMA_H__
+#define __XML_SCHEMA_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_SCHEMAS_ENABLED
+
+#include <libxml/tree.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * This error codes are obsolete; not used any more.
+ */
+typedef enum {
+    XML_SCHEMAS_ERR_OK		= 0,
+    XML_SCHEMAS_ERR_NOROOT	= 1,
+    XML_SCHEMAS_ERR_UNDECLAREDELEM,
+    XML_SCHEMAS_ERR_NOTTOPLEVEL,
+    XML_SCHEMAS_ERR_MISSING,
+    XML_SCHEMAS_ERR_WRONGELEM,
+    XML_SCHEMAS_ERR_NOTYPE,
+    XML_SCHEMAS_ERR_NOROLLBACK,
+    XML_SCHEMAS_ERR_ISABSTRACT,
+    XML_SCHEMAS_ERR_NOTEMPTY,
+    XML_SCHEMAS_ERR_ELEMCONT,
+    XML_SCHEMAS_ERR_HAVEDEFAULT,
+    XML_SCHEMAS_ERR_NOTNILLABLE,
+    XML_SCHEMAS_ERR_EXTRACONTENT,
+    XML_SCHEMAS_ERR_INVALIDATTR,
+    XML_SCHEMAS_ERR_INVALIDELEM,
+    XML_SCHEMAS_ERR_NOTDETERMINIST,
+    XML_SCHEMAS_ERR_CONSTRUCT,
+    XML_SCHEMAS_ERR_INTERNAL,
+    XML_SCHEMAS_ERR_NOTSIMPLE,
+    XML_SCHEMAS_ERR_ATTRUNKNOWN,
+    XML_SCHEMAS_ERR_ATTRINVALID,
+    XML_SCHEMAS_ERR_VALUE,
+    XML_SCHEMAS_ERR_FACET,
+    XML_SCHEMAS_ERR_,
+    XML_SCHEMAS_ERR_XXX
+} xmlSchemaValidError;
+
+/*
+* ATTENTION: Change xmlSchemaSetValidOptions's check
+* for invalid values, if adding to the validation 
+* options below.
+*/
+/**
+ * xmlSchemaValidOption:
+ *
+ * This is the set of XML Schema validation options.
+ */
+typedef enum {
+    XML_SCHEMA_VAL_VC_I_CREATE			= 1<<0
+	/* Default/fixed: create an attribute node
+	* or an element's text node on the instance.
+	*/
+} xmlSchemaValidOption;
+
+/*
+    XML_SCHEMA_VAL_XSI_ASSEMBLE			= 1<<1,
+	* assemble schemata using
+	* xsi:schemaLocation and
+	* xsi:noNamespaceSchemaLocation
+*/
+
+/**
+ * The schemas related types are kept internal
+ */
+typedef struct _xmlSchema xmlSchema;
+typedef xmlSchema *xmlSchemaPtr;
+
+/**
+ * A schemas validation context
+ */
+typedef void (*xmlSchemaValidityErrorFunc) (void *ctx, const char *msg, ...);
+typedef void (*xmlSchemaValidityWarningFunc) (void *ctx, const char *msg, ...);
+
+typedef struct _xmlSchemaParserCtxt xmlSchemaParserCtxt;
+typedef xmlSchemaParserCtxt *xmlSchemaParserCtxtPtr;
+
+typedef struct _xmlSchemaValidCtxt xmlSchemaValidCtxt;
+typedef xmlSchemaValidCtxt *xmlSchemaValidCtxtPtr;
+
+/*
+ * Interfaces for parsing.
+ */
+XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL 
+	    xmlSchemaNewParserCtxt	(const char *URL);
+XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL 
+	    xmlSchemaNewMemParserCtxt	(const char *buffer,
+					 int size);
+XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL
+	    xmlSchemaNewDocParserCtxt	(xmlDocPtr doc);
+XMLPUBFUN void XMLCALL		
+	    xmlSchemaFreeParserCtxt	(xmlSchemaParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL		
+	    xmlSchemaSetParserErrors	(xmlSchemaParserCtxtPtr ctxt,
+					 xmlSchemaValidityErrorFunc err,
+					 xmlSchemaValidityWarningFunc warn,
+					 void *ctx);
+XMLPUBFUN int XMLCALL
+		xmlSchemaGetParserErrors	(xmlSchemaParserCtxtPtr ctxt,
+					xmlSchemaValidityErrorFunc * err,
+					xmlSchemaValidityWarningFunc * warn,
+					void **ctx);
+XMLPUBFUN xmlSchemaPtr XMLCALL	
+	    xmlSchemaParse		(xmlSchemaParserCtxtPtr ctxt);
+XMLPUBFUN void XMLCALL		
+	    xmlSchemaFree		(xmlSchemaPtr schema);
+#ifdef LIBXML_OUTPUT_ENABLED
+XMLPUBFUN void XMLCALL		
+	    xmlSchemaDump		(FILE *output,
+					 xmlSchemaPtr schema);
+#endif /* LIBXML_OUTPUT_ENABLED */
+/*
+ * Interfaces for validating
+ */
+XMLPUBFUN void XMLCALL		
+	    xmlSchemaSetValidErrors	(xmlSchemaValidCtxtPtr ctxt,
+					 xmlSchemaValidityErrorFunc err,
+					 xmlSchemaValidityWarningFunc warn,
+					 void *ctx);
+XMLPUBFUN int XMLCALL
+	    xmlSchemaGetValidErrors	(xmlSchemaValidCtxtPtr ctxt,
+					 xmlSchemaValidityErrorFunc *err,
+					 xmlSchemaValidityWarningFunc *warn,
+					 void **ctx);
+XMLPUBFUN int XMLCALL
+	    xmlSchemaSetValidOptions	(xmlSchemaValidCtxtPtr ctxt,
+					 int options);
+XMLPUBFUN int XMLCALL
+	    xmlSchemaValidCtxtGetOptions(xmlSchemaValidCtxtPtr ctxt);
+
+XMLPUBFUN xmlSchemaValidCtxtPtr XMLCALL	
+	    xmlSchemaNewValidCtxt	(xmlSchemaPtr schema);
+XMLPUBFUN void XMLCALL			
+	    xmlSchemaFreeValidCtxt	(xmlSchemaValidCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL			
+	    xmlSchemaValidateDoc	(xmlSchemaValidCtxtPtr ctxt,
+					 xmlDocPtr instance);
+XMLPUBFUN int XMLCALL
+            xmlSchemaValidateOneElement (xmlSchemaValidCtxtPtr ctxt,
+			                 xmlNodePtr elem);
+XMLPUBFUN int XMLCALL			
+	    xmlSchemaValidateStream	(xmlSchemaValidCtxtPtr ctxt,
+					 xmlParserInputBufferPtr input,
+					 xmlCharEncoding enc,
+					 xmlSAXHandlerPtr sax,
+					 void *user_data);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_SCHEMAS_ENABLED */
+#endif /* __XML_SCHEMA_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlschemastypes.h ./aperios/include/libxml2/libxml/xmlschemastypes.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlschemastypes.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlschemastypes.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,136 @@
+/*
+ * Summary: implementation of XML Schema Datatypes
+ * Description: module providing the XML Schema Datatypes implementation
+ *              both definition and validity checking
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+
+#ifndef __XML_SCHEMA_TYPES_H__
+#define __XML_SCHEMA_TYPES_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_SCHEMAS_ENABLED
+
+#include <libxml/schemasInternals.h>
+#include <libxml/xmlschemas.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    XML_SCHEMA_WHITESPACE_UNKNOWN = 0,
+    XML_SCHEMA_WHITESPACE_PRESERVE = 1,
+    XML_SCHEMA_WHITESPACE_REPLACE = 2,
+    XML_SCHEMA_WHITESPACE_COLLAPSE = 3
+} xmlSchemaWhitespaceValueType;
+
+XMLPUBFUN void XMLCALL		
+    		xmlSchemaInitTypes		(void);
+XMLPUBFUN void XMLCALL		
+		xmlSchemaCleanupTypes		(void);
+XMLPUBFUN xmlSchemaTypePtr XMLCALL 
+		xmlSchemaGetPredefinedType	(const xmlChar *name,
+						 const xmlChar *ns);
+XMLPUBFUN int XMLCALL		
+		xmlSchemaValidatePredefinedType	(xmlSchemaTypePtr type,
+						 const xmlChar *value,
+						 xmlSchemaValPtr *val);
+XMLPUBFUN int XMLCALL		
+		xmlSchemaValPredefTypeNode	(xmlSchemaTypePtr type,
+						 const xmlChar *value,
+						 xmlSchemaValPtr *val,
+						 xmlNodePtr node);
+XMLPUBFUN int XMLCALL		
+		xmlSchemaValidateFacet		(xmlSchemaTypePtr base,
+						 xmlSchemaFacetPtr facet,
+						 const xmlChar *value,
+						 xmlSchemaValPtr val);
+XMLPUBFUN int XMLCALL
+		xmlSchemaValidateFacetWhtsp	(xmlSchemaFacetPtr facet,
+						 xmlSchemaWhitespaceValueType fws,
+						 xmlSchemaValType valType,						 
+						 const xmlChar *value,
+						 xmlSchemaValPtr val,
+						 xmlSchemaWhitespaceValueType ws);
+XMLPUBFUN void XMLCALL		
+		xmlSchemaFreeValue		(xmlSchemaValPtr val);
+XMLPUBFUN xmlSchemaFacetPtr XMLCALL 
+		xmlSchemaNewFacet		(void);
+XMLPUBFUN int XMLCALL		
+		xmlSchemaCheckFacet		(xmlSchemaFacetPtr facet,
+						 xmlSchemaTypePtr typeDecl,
+						 xmlSchemaParserCtxtPtr ctxt,
+						 const xmlChar *name);
+XMLPUBFUN void XMLCALL		
+		xmlSchemaFreeFacet		(xmlSchemaFacetPtr facet);
+XMLPUBFUN int XMLCALL		
+		xmlSchemaCompareValues		(xmlSchemaValPtr x,
+						 xmlSchemaValPtr y);
+XMLPUBFUN xmlSchemaTypePtr XMLCALL		
+    xmlSchemaGetBuiltInListSimpleTypeItemType	(xmlSchemaTypePtr type);
+XMLPUBFUN int XMLCALL
+    xmlSchemaValidateListSimpleTypeFacet	(xmlSchemaFacetPtr facet,
+						 const xmlChar *value,
+						 unsigned long actualLen,
+						 unsigned long *expectedLen);
+XMLPUBFUN xmlSchemaTypePtr XMLCALL
+		xmlSchemaGetBuiltInType		(xmlSchemaValType type);
+XMLPUBFUN int XMLCALL
+		xmlSchemaIsBuiltInTypeFacet	(xmlSchemaTypePtr type, 
+						 int facetType);
+XMLPUBFUN xmlChar * XMLCALL
+		xmlSchemaCollapseString		(const xmlChar *value);
+XMLPUBFUN xmlChar * XMLCALL
+		xmlSchemaWhiteSpaceReplace	(const xmlChar *value);
+XMLPUBFUN unsigned long  XMLCALL
+		xmlSchemaGetFacetValueAsULong	(xmlSchemaFacetPtr facet);
+XMLPUBFUN int XMLCALL
+		xmlSchemaValidateLengthFacet	(xmlSchemaTypePtr type, 
+						 xmlSchemaFacetPtr facet,
+						 const xmlChar *value,
+						 xmlSchemaValPtr val,
+						 unsigned long *length);
+XMLPUBFUN int XMLCALL
+		xmlSchemaValidateLengthFacetWhtsp(xmlSchemaFacetPtr facet,
+						  xmlSchemaValType valType,
+						  const xmlChar *value,
+						  xmlSchemaValPtr val,						  
+						  unsigned long *length,
+						  xmlSchemaWhitespaceValueType ws);
+XMLPUBFUN int XMLCALL
+		xmlSchemaValPredefTypeNodeNoNorm(xmlSchemaTypePtr type, 
+						 const xmlChar *value,
+						 xmlSchemaValPtr *val, 
+						 xmlNodePtr node);
+XMLPUBFUN int XMLCALL
+		xmlSchemaGetCanonValue		(xmlSchemaValPtr val,
+						 const xmlChar **retValue);
+XMLPUBFUN xmlSchemaValPtr XMLCALL
+		xmlSchemaNewStringValue		(xmlSchemaValType type,
+						 const xmlChar *value);
+XMLPUBFUN xmlSchemaValPtr XMLCALL
+		xmlSchemaNewNOTATIONValue	(const xmlChar *name,
+						 const xmlChar *ns);
+
+XMLPUBFUN int XMLCALL
+		xmlSchemaCompareValuesWhtsp	(xmlSchemaValPtr x,
+						 xmlSchemaWhitespaceValueType xws,
+						 xmlSchemaValPtr y,
+						 xmlSchemaWhitespaceValueType yws);
+XMLPUBFUN xmlSchemaValPtr XMLCALL
+		xmlSchemaCopyValue		(xmlSchemaValPtr val);
+XMLPUBFUN xmlSchemaValType XMLCALL
+		xmlSchemaGetValType		(xmlSchemaValPtr val);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_SCHEMAS_ENABLED */
+#endif /* __XML_SCHEMA_TYPES_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlstring.h ./aperios/include/libxml2/libxml/xmlstring.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlstring.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlstring.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,141 @@
+/*
+ * Summary: set of routines to process strings
+ * Description: type and interfaces needed for the internal string handling
+ *              of the library, especially UTF8 processing.
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_STRING_H__
+#define __XML_STRING_H__
+
+#include <stdarg.h>
+#include <libxml/xmlversion.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * xmlChar:
+ *
+ * This is a basic byte in an UTF-8 encoded string.
+ * It's unsigned allowing to pinpoint case where char * are assigned
+ * to xmlChar * (possibly making serialization back impossible).
+ */
+
+typedef unsigned char xmlChar;
+
+/**
+ * BAD_CAST:
+ *
+ * Macro to cast a string to an xmlChar * when one know its safe.
+ */
+#define BAD_CAST (xmlChar *)
+
+/*
+ * xmlChar handling
+ */
+XMLPUBFUN xmlChar * XMLCALL
+                xmlStrdup                (const xmlChar *cur);
+XMLPUBFUN xmlChar * XMLCALL
+                xmlStrndup               (const xmlChar *cur,
+                                         int len);
+XMLPUBFUN xmlChar * XMLCALL
+                xmlCharStrndup           (const char *cur,
+                                         int len);
+XMLPUBFUN xmlChar * XMLCALL
+                xmlCharStrdup            (const char *cur);
+XMLPUBFUN xmlChar * XMLCALL
+                xmlStrsub                (const xmlChar *str,
+                                         int start,
+                                         int len);
+XMLPUBFUN const xmlChar * XMLCALL
+                xmlStrchr                (const xmlChar *str,
+                                         xmlChar val);
+XMLPUBFUN const xmlChar * XMLCALL
+                xmlStrstr                (const xmlChar *str,
+                                         const xmlChar *val);
+XMLPUBFUN const xmlChar * XMLCALL
+                xmlStrcasestr            (const xmlChar *str,
+                                         xmlChar *val);
+XMLPUBFUN int XMLCALL
+                xmlStrcmp                (const xmlChar *str1,
+                                         const xmlChar *str2);
+XMLPUBFUN int XMLCALL
+                xmlStrncmp               (const xmlChar *str1,
+                                         const xmlChar *str2,
+                                         int len);
+XMLPUBFUN int XMLCALL
+                xmlStrcasecmp            (const xmlChar *str1,
+                                         const xmlChar *str2);
+XMLPUBFUN int XMLCALL
+                xmlStrncasecmp           (const xmlChar *str1,
+                                         const xmlChar *str2,
+                                         int len);
+XMLPUBFUN int XMLCALL
+                xmlStrEqual              (const xmlChar *str1,
+                                         const xmlChar *str2);
+XMLPUBFUN int XMLCALL
+                xmlStrQEqual             (const xmlChar *pref,
+                                         const xmlChar *name,
+                                         const xmlChar *str);
+XMLPUBFUN int XMLCALL
+                xmlStrlen                (const xmlChar *str);
+XMLPUBFUN xmlChar * XMLCALL
+                xmlStrcat                (xmlChar *cur,
+                                         const xmlChar *add);
+XMLPUBFUN xmlChar * XMLCALL
+                xmlStrncat               (xmlChar *cur,
+                                         const xmlChar *add,
+                                         int len);
+XMLPUBFUN xmlChar * XMLCALL
+                xmlStrncatNew            (const xmlChar *str1,
+                                         const xmlChar *str2,
+                                         int len);
+XMLPUBFUN int XMLCALL
+                xmlStrPrintf             (xmlChar *buf,
+                                         int len,
+                                         const xmlChar *msg,
+                                         ...);
+XMLPUBFUN int XMLCALL
+                xmlStrVPrintf                (xmlChar *buf,
+                                         int len,
+                                         const xmlChar *msg,
+                                         va_list ap);
+
+XMLPUBFUN int XMLCALL
+        xmlGetUTF8Char                   (const unsigned char *utf,
+                                         int *len);
+XMLPUBFUN int XMLCALL
+        xmlCheckUTF8                     (const unsigned char *utf);
+XMLPUBFUN int XMLCALL
+        xmlUTF8Strsize                   (const xmlChar *utf,
+                                         int len);
+XMLPUBFUN xmlChar * XMLCALL 
+        xmlUTF8Strndup                   (const xmlChar *utf,
+                                         int len);
+XMLPUBFUN const xmlChar * XMLCALL 
+        xmlUTF8Strpos                    (const xmlChar *utf,
+                                         int pos);
+XMLPUBFUN int XMLCALL
+        xmlUTF8Strloc                    (const xmlChar *utf,
+                                         const xmlChar *utfchar);
+XMLPUBFUN xmlChar * XMLCALL 
+        xmlUTF8Strsub                    (const xmlChar *utf,
+                                         int start,
+                                         int len);
+XMLPUBFUN int XMLCALL
+        xmlUTF8Strlen                    (const xmlChar *utf);
+XMLPUBFUN int XMLCALL
+        xmlUTF8Size                      (const xmlChar *utf);
+XMLPUBFUN int XMLCALL
+        xmlUTF8Charcmp                   (const xmlChar *utf1,
+                                         const xmlChar *utf2);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* __XML_STRING_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlunicode.h ./aperios/include/libxml2/libxml/xmlunicode.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlunicode.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlunicode.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,202 @@
+/*
+ * Summary: Unicode character APIs
+ * Description: API for the Unicode character APIs
+ *
+ * This file is automatically generated from the
+ * UCS description files of the Unicode Character Database
+ * http://www.unicode.org/Public/4.0-Update1/UCD-4.0.1d5b.html
+ * using the genUnicode.py Python script.
+ *
+ * Generation date: Mon Nov 10 22:35:10 2003
+ * Sources: Blocks-4.0.1d1b.txt UnicodeData-4.0.1d1b.txt
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_UNICODE_H__
+#define __XML_UNICODE_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_UNICODE_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+XMLPUBFUN int XMLCALL xmlUCSIsAegeanNumbers	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsAlphabeticPresentationForms	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsArabic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsArabicPresentationFormsA	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsArabicPresentationFormsB	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsArmenian	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsArrows	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBasicLatin	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBengali	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBlockElements	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBopomofo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBopomofoExtended	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBoxDrawing	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBraillePatterns	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsBuhid	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsByzantineMusicalSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibility	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityForms	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityIdeographs	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityIdeographsSupplement	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKRadicalsSupplement	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKSymbolsandPunctuation	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographs	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographsExtensionA	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographsExtensionB	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCherokee	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCombiningDiacriticalMarks	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCombiningDiacriticalMarksforSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCombiningHalfMarks	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCombiningMarksforSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsControlPictures	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCurrencySymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCypriotSyllabary	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCyrillic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCyrillicSupplement	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsDeseret	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsDevanagari	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsDingbats	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsEnclosedAlphanumerics	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsEnclosedCJKLettersandMonths	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsEthiopic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGeneralPunctuation	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGeometricShapes	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGeorgian	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGothic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGreek	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGreekExtended	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGreekandCoptic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGujarati	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsGurmukhi	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHalfwidthandFullwidthForms	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHangulCompatibilityJamo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHangulJamo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHangulSyllables	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHanunoo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHebrew	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHighPrivateUseSurrogates	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHighSurrogates	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsHiragana	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsIPAExtensions	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsIdeographicDescriptionCharacters	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsKanbun	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsKangxiRadicals	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsKannada	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsKatakana	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsKatakanaPhoneticExtensions	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsKhmer	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsKhmerSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLao	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLatin1Supplement	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedA	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedB	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedAdditional	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLetterlikeSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLimbu	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLinearBIdeograms	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLinearBSyllabary	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsLowSurrogates	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMalayalam	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMathematicalAlphanumericSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMathematicalOperators	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousMathematicalSymbolsA	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousMathematicalSymbolsB	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousSymbolsandArrows	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousTechnical	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMongolian	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMusicalSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsMyanmar	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsNumberForms	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsOgham	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsOldItalic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsOpticalCharacterRecognition	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsOriya	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsOsmanya	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsPhoneticExtensions	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsPrivateUse	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsPrivateUseArea	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsRunic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsShavian	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSinhala	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSmallFormVariants	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSpacingModifierLetters	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSpecials	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSuperscriptsandSubscripts	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSupplementalArrowsA	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSupplementalArrowsB	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSupplementalMathematicalOperators	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSupplementaryPrivateUseAreaA	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSupplementaryPrivateUseAreaB	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsSyriac	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTagalog	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTagbanwa	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTags	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTaiLe	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTaiXuanJingSymbols	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTamil	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTelugu	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsThaana	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsThai	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsTibetan	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsUgaritic	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsUnifiedCanadianAboriginalSyllabics	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsVariationSelectors	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsVariationSelectorsSupplement	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsYiRadicals	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsYiSyllables	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsYijingHexagramSymbols	(int code);
+
+XMLPUBFUN int XMLCALL xmlUCSIsBlock	(int code, const char *block);
+
+XMLPUBFUN int XMLCALL xmlUCSIsCatC	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatCc	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatCf	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatCo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatCs	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatL	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatLl	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatLm	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatLo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatLt	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatLu	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatM	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatMc	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatMe	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatMn	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatN	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatNd	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatNl	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatNo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatP	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatPc	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatPd	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatPe	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatPf	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatPi	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatPo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatPs	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatS	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatSc	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatSk	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatSm	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatSo	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatZ	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatZl	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatZp	(int code);
+XMLPUBFUN int XMLCALL xmlUCSIsCatZs	(int code);
+
+XMLPUBFUN int XMLCALL xmlUCSIsCat	(int code, const char *cat);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_UNICODE_ENABLED */
+
+#endif /* __XML_UNICODE_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlversion.h ./aperios/include/libxml2/libxml/xmlversion.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlversion.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlversion.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,373 @@
+/*
+ * Summary: compile-time version informations
+ * Description: compile-time version informations for the XML library
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_VERSION_H__
+#define __XML_VERSION_H__
+
+#include <libxml/xmlexports.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * use those to be sure nothing nasty will happen if
+ * your library and includes mismatch
+ */
+#ifndef LIBXML2_COMPILING_MSCCDEF
+XMLPUBFUN void XMLCALL xmlCheckVersion(int version);
+#endif /* LIBXML2_COMPILING_MSCCDEF */
+
+/**
+ * LIBXML_DOTTED_VERSION:
+ *
+ * the version string like "1.2.3"
+ */
+#define LIBXML_DOTTED_VERSION "2.6.19"
+
+/**
+ * LIBXML_VERSION:
+ *
+ * the version number: 1.2.3 value is 1002003
+ */
+#define LIBXML_VERSION 20619
+
+/**
+ * LIBXML_VERSION_STRING:
+ *
+ * the version number string, 1.2.3 value is "1002003"
+ */
+#define LIBXML_VERSION_STRING "20619"
+
+/**
+ * LIBXML_VERSION_EXTRA:
+ *
+ * extra version information, used to show a CVS compilation
+ */
+#define LIBXML_VERSION_EXTRA ""
+
+/**
+ * LIBXML_TEST_VERSION:
+ *
+ * Macro to check that the libxml version in use is compatible with
+ * the version the software has been compiled against
+ */
+#define LIBXML_TEST_VERSION xmlCheckVersion(20619);
+
+#ifndef VMS
+#if 1
+/**
+ * WITH_TRIO:
+ *
+ * defined if the trio support need to be configured in
+ */
+#define WITH_TRIO
+#else
+/**
+ * WITHOUT_TRIO:
+ *
+ * defined if the trio support should not be configured in
+ */
+#define WITHOUT_TRIO
+#endif
+#else /* VMS */
+/**
+ * WITH_TRIO:
+ *
+ * defined if the trio support need to be configured in
+ */
+#define WITH_TRIO 1
+#endif /* VMS */
+
+/**
+ * LIBXML_THREAD_ENABLED:
+ *
+ * Whether the thread support is configured in
+ */
+#if 0
+#if defined(_REENTRANT) || defined(__MT__) || (_POSIX_C_SOURCE - 0 >= 199506L)
+#define LIBXML_THREAD_ENABLED
+#endif
+#endif
+
+/**
+ * LIBXML_TREE_ENABLED:
+ *
+ * Whether the DOM like tree manipulation API support is configured in
+ */
+#if 1
+#define LIBXML_TREE_ENABLED
+#endif
+
+/**
+ * LIBXML_OUTPUT_ENABLED:
+ *
+ * Whether the serialization/saving support is configured in
+ */
+#if 1
+#define LIBXML_OUTPUT_ENABLED
+#endif
+
+/**
+ * LIBXML_PUSH_ENABLED:
+ *
+ * Whether the push parsing interfaces are configured in
+ */
+#if 1
+#define LIBXML_PUSH_ENABLED
+#endif
+
+/**
+ * LIBXML_READER_ENABLED:
+ *
+ * Whether the xmlReader parsing interface is configured in
+ */
+#if 1
+#define LIBXML_READER_ENABLED
+#endif
+
+/**
+ * LIBXML_PATTERN_ENABLED:
+ *
+ * Whether the xmlPattern node selection interface is configured in
+ */
+#if 0
+#define LIBXML_PATTERN_ENABLED
+#endif
+
+/**
+ * LIBXML_WRITER_ENABLED:
+ *
+ * Whether the xmlWriter saving interface is configured in
+ */
+#if 1
+#define LIBXML_WRITER_ENABLED
+#endif
+
+/**
+ * LIBXML_SAX1_ENABLED:
+ *
+ * Whether the older SAX1 interface is configured in
+ */
+#if 0
+#define LIBXML_SAX1_ENABLED
+#endif
+
+/**
+ * LIBXML_FTP_ENABLED:
+ *
+ * Whether the FTP support is configured in
+ */
+#if 0
+#define LIBXML_FTP_ENABLED
+#endif
+
+/**
+ * LIBXML_HTTP_ENABLED:
+ *
+ * Whether the HTTP support is configured in
+ */
+#if 0
+#define LIBXML_HTTP_ENABLED
+#endif
+
+/**
+ * LIBXML_VALID_ENABLED:
+ *
+ * Whether the DTD validation support is configured in
+ */
+#if 1
+#define LIBXML_VALID_ENABLED
+#endif
+
+/**
+ * LIBXML_HTML_ENABLED:
+ *
+ * Whether the HTML support is configured in
+ */
+#if 1
+#define LIBXML_HTML_ENABLED
+#endif
+
+/**
+ * LIBXML_LEGACY_ENABLED:
+ *
+ * Whether the deprecated APIs are compiled in for compatibility
+ */
+#if 0
+#define LIBXML_LEGACY_ENABLED
+#endif
+
+/**
+ * LIBXML_C14N_ENABLED:
+ *
+ * Whether the Canonicalization support is configured in
+ */
+#if 0
+#define LIBXML_C14N_ENABLED
+#endif
+
+/**
+ * LIBXML_CATALOG_ENABLED:
+ *
+ * Whether the Catalog support is configured in
+ */
+#if 0
+#define LIBXML_CATALOG_ENABLED
+#endif
+
+/**
+ * LIBXML_DOCB_ENABLED:
+ *
+ * Whether the SGML Docbook support is configured in
+ */
+#if 0
+#define LIBXML_DOCB_ENABLED
+#endif
+
+/**
+ * LIBXML_XPATH_ENABLED:
+ *
+ * Whether XPath is configured in
+ */
+#if 1
+#define LIBXML_XPATH_ENABLED
+#endif
+
+/**
+ * LIBXML_XPTR_ENABLED:
+ *
+ * Whether XPointer is configured in
+ */
+#if 1
+#define LIBXML_XPTR_ENABLED
+#endif
+
+/**
+ * LIBXML_XINCLUDE_ENABLED:
+ *
+ * Whether XInclude is configured in
+ */
+#if 1
+#define LIBXML_XINCLUDE_ENABLED
+#endif
+
+/**
+ * LIBXML_ICONV_ENABLED:
+ *
+ * Whether iconv support is available
+ */
+#if 0
+#define LIBXML_ICONV_ENABLED
+#endif
+
+/**
+ * LIBXML_ISO8859X_ENABLED:
+ *
+ * Whether ISO-8859-* support is made available in case iconv is not
+ */
+#if 1
+#define LIBXML_ISO8859X_ENABLED
+#endif
+
+/**
+ * LIBXML_DEBUG_ENABLED:
+ *
+ * Whether Debugging module is configured in
+ */
+#if 0
+#define LIBXML_DEBUG_ENABLED
+#endif
+
+/**
+ * DEBUG_MEMORY_LOCATION:
+ *
+ * Whether the memory debugging is configured in
+ */
+#if 0
+#define DEBUG_MEMORY_LOCATION
+#endif
+
+/**
+ * LIBXML_DEBUG_RUNTIME:
+ *
+ * Whether the runtime debugging is configured in
+ */
+#if 0
+#define LIBXML_DEBUG_RUNTIME
+#endif
+
+/**
+ * LIBXML_UNICODE_ENABLED:
+ *
+ * Whether the Unicode related interfaces are compiled in
+ */
+#if 0
+#define LIBXML_UNICODE_ENABLED
+#endif
+
+/**
+ * LIBXML_REGEXP_ENABLED:
+ *
+ * Whether the regular expressions interfaces are compiled in
+ */
+#if 0
+#define LIBXML_REGEXP_ENABLED
+#endif
+
+/**
+ * LIBXML_AUTOMATA_ENABLED:
+ *
+ * Whether the automata interfaces are compiled in
+ */
+#if 0
+#define LIBXML_AUTOMATA_ENABLED
+#endif
+
+/**
+ * LIBXML_SCHEMAS_ENABLED:
+ *
+ * Whether the Schemas validation interfaces are compiled in
+ */
+#if 0
+#define LIBXML_SCHEMAS_ENABLED
+#endif
+
+/**
+ * LIBXML_MODULES_ENABLED:
+ *
+ * Whether the module interfaces are compiled in
+ */
+#if 0
+#define LIBXML_MODULES_ENABLED
+#define LIBXML_MODULE_EXTENSION ".so" 
+#endif
+
+/**
+ * ATTRIBUTE_UNUSED:
+ *
+ * Macro used to signal to GCC unused function parameters
+ */
+#ifdef __GNUC__
+#ifdef HAVE_ANSIDECL_H
+#include <ansidecl.h>
+#endif
+#ifndef ATTRIBUTE_UNUSED
+#define ATTRIBUTE_UNUSED __attribute__((unused))
+#endif
+#else
+#define ATTRIBUTE_UNUSED
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif
+
+
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlwriter.h ./aperios/include/libxml2/libxml/xmlwriter.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xmlwriter.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xmlwriter.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,459 @@
+
+/*
+ * Summary: text writing API for XML
+ * Description: text writing API for XML
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Alfred Mickautsch <alfred@mickautsch.de>
+ */
+
+#ifndef __XML_XMLWRITER_H__
+#define __XML_XMLWRITER_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_WRITER_ENABLED
+
+#include <stdarg.h>
+#include <libxml/xmlIO.h>
+#include <libxml/list.h>
+#include <libxml/xmlstring.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+    typedef struct _xmlTextWriter xmlTextWriter;
+    typedef xmlTextWriter *xmlTextWriterPtr;
+
+/*
+ * Constructors & Destructor
+ */
+    XMLPUBFUN xmlTextWriterPtr XMLCALL
+        xmlNewTextWriter(xmlOutputBufferPtr out);
+    XMLPUBFUN xmlTextWriterPtr XMLCALL
+        xmlNewTextWriterFilename(const char *uri, int compression);
+    XMLPUBFUN xmlTextWriterPtr XMLCALL
+        xmlNewTextWriterMemory(xmlBufferPtr buf, int compression);
+    XMLPUBFUN xmlTextWriterPtr XMLCALL
+        xmlNewTextWriterPushParser(xmlParserCtxtPtr ctxt, int compression);
+    XMLPUBFUN xmlTextWriterPtr XMLCALL
+        xmlNewTextWriterDoc(xmlDocPtr * doc, int compression);
+    XMLPUBFUN xmlTextWriterPtr XMLCALL
+        xmlNewTextWriterTree(xmlDocPtr doc, xmlNodePtr node,
+                             int compression);
+    XMLPUBFUN void XMLCALL xmlFreeTextWriter(xmlTextWriterPtr writer);
+
+/*
+ * Functions
+ */
+
+
+/*
+ * Document
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartDocument(xmlTextWriterPtr writer,
+                                   const char *version,
+                                   const char *encoding,
+                                   const char *standalone);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndDocument(xmlTextWriterPtr
+                                                   writer);
+
+/*
+ * Comments
+ */
+    XMLPUBFUN int XMLCALL xmlTextWriterStartComment(xmlTextWriterPtr
+                                                    writer);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndComment(xmlTextWriterPtr writer);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatComment(xmlTextWriterPtr writer,
+                                        const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatComment(xmlTextWriterPtr writer,
+                                         const char *format,
+                                         va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteComment(xmlTextWriterPtr
+                                                    writer,
+                                                    const xmlChar *
+                                                    content);
+
+/*
+ * Elements
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartElement(xmlTextWriterPtr writer,
+                                  const xmlChar * name);
+    XMLPUBFUN int XMLCALL xmlTextWriterStartElementNS(xmlTextWriterPtr
+                                                      writer,
+                                                      const xmlChar *
+                                                      prefix,
+                                                      const xmlChar * name,
+                                                      const xmlChar *
+                                                      namespaceURI);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndElement(xmlTextWriterPtr writer);
+    XMLPUBFUN int XMLCALL xmlTextWriterFullEndElement(xmlTextWriterPtr
+                                                      writer);
+
+/*
+ * Elements conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatElement(xmlTextWriterPtr writer,
+                                        const xmlChar * name,
+                                        const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatElement(xmlTextWriterPtr writer,
+                                         const xmlChar * name,
+                                         const char *format,
+                                         va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteElement(xmlTextWriterPtr
+                                                    writer,
+                                                    const xmlChar * name,
+                                                    const xmlChar *
+                                                    content);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatElementNS(xmlTextWriterPtr writer,
+                                          const xmlChar * prefix,
+                                          const xmlChar * name,
+                                          const xmlChar * namespaceURI,
+                                          const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatElementNS(xmlTextWriterPtr writer,
+                                           const xmlChar * prefix,
+                                           const xmlChar * name,
+                                           const xmlChar * namespaceURI,
+                                           const char *format,
+                                           va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteElementNS(xmlTextWriterPtr
+                                                      writer,
+                                                      const xmlChar *
+                                                      prefix,
+                                                      const xmlChar * name,
+                                                      const xmlChar *
+                                                      namespaceURI,
+                                                      const xmlChar *
+                                                      content);
+
+/*
+ * Text
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatRaw(xmlTextWriterPtr writer,
+                                    const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatRaw(xmlTextWriterPtr writer,
+                                     const char *format, va_list argptr);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteRawLen(xmlTextWriterPtr writer,
+                                 const xmlChar * content, int len);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteRaw(xmlTextWriterPtr writer,
+                              const xmlChar * content);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteFormatString(xmlTextWriterPtr
+                                                         writer,
+                                                         const char
+                                                         *format, ...);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteVFormatString(xmlTextWriterPtr
+                                                          writer,
+                                                          const char
+                                                          *format,
+                                                          va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteString(xmlTextWriterPtr writer,
+                                                   const xmlChar *
+                                                   content);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteBase64(xmlTextWriterPtr writer,
+                                                   const char *data,
+                                                   int start, int len);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteBinHex(xmlTextWriterPtr writer,
+                                                   const char *data,
+                                                   int start, int len);
+
+/*
+ * Attributes
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartAttribute(xmlTextWriterPtr writer,
+                                    const xmlChar * name);
+    XMLPUBFUN int XMLCALL xmlTextWriterStartAttributeNS(xmlTextWriterPtr
+                                                        writer,
+                                                        const xmlChar *
+                                                        prefix,
+                                                        const xmlChar *
+                                                        name,
+                                                        const xmlChar *
+                                                        namespaceURI);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndAttribute(xmlTextWriterPtr
+                                                    writer);
+
+/*
+ * Attributes conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatAttribute(xmlTextWriterPtr writer,
+                                          const xmlChar * name,
+                                          const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatAttribute(xmlTextWriterPtr writer,
+                                           const xmlChar * name,
+                                           const char *format,
+                                           va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteAttribute(xmlTextWriterPtr
+                                                      writer,
+                                                      const xmlChar * name,
+                                                      const xmlChar *
+                                                      content);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatAttributeNS(xmlTextWriterPtr writer,
+                                            const xmlChar * prefix,
+                                            const xmlChar * name,
+                                            const xmlChar * namespaceURI,
+                                            const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatAttributeNS(xmlTextWriterPtr writer,
+                                             const xmlChar * prefix,
+                                             const xmlChar * name,
+                                             const xmlChar * namespaceURI,
+                                             const char *format,
+                                             va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteAttributeNS(xmlTextWriterPtr
+                                                        writer,
+                                                        const xmlChar *
+                                                        prefix,
+                                                        const xmlChar *
+                                                        name,
+                                                        const xmlChar *
+                                                        namespaceURI,
+                                                        const xmlChar *
+                                                        content);
+
+/*
+ * PI's
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartPI(xmlTextWriterPtr writer,
+                             const xmlChar * target);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndPI(xmlTextWriterPtr writer);
+
+/*
+ * PI conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatPI(xmlTextWriterPtr writer,
+                                   const xmlChar * target,
+                                   const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatPI(xmlTextWriterPtr writer,
+                                    const xmlChar * target,
+                                    const char *format, va_list argptr);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWritePI(xmlTextWriterPtr writer,
+                             const xmlChar * target,
+                             const xmlChar * content);
+
+/**
+ * xmlTextWriterWriteProcessingInstruction:
+ *
+ * This macro maps to xmlTextWriterWritePI
+ */
+#define xmlTextWriterWriteProcessingInstruction xmlTextWriterWritePI
+
+/*
+ * CDATA
+ */
+    XMLPUBFUN int XMLCALL xmlTextWriterStartCDATA(xmlTextWriterPtr writer);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndCDATA(xmlTextWriterPtr writer);
+
+/*
+ * CDATA conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatCDATA(xmlTextWriterPtr writer,
+                                      const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatCDATA(xmlTextWriterPtr writer,
+                                       const char *format, va_list argptr);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteCDATA(xmlTextWriterPtr writer,
+                                const xmlChar * content);
+
+/*
+ * DTD
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartDTD(xmlTextWriterPtr writer,
+                              const xmlChar * name,
+                              const xmlChar * pubid,
+                              const xmlChar * sysid);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndDTD(xmlTextWriterPtr writer);
+
+/*
+ * DTD conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatDTD(xmlTextWriterPtr writer,
+                                    const xmlChar * name,
+                                    const xmlChar * pubid,
+                                    const xmlChar * sysid,
+                                    const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatDTD(xmlTextWriterPtr writer,
+                                     const xmlChar * name,
+                                     const xmlChar * pubid,
+                                     const xmlChar * sysid,
+                                     const char *format, va_list argptr);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteDTD(xmlTextWriterPtr writer,
+                              const xmlChar * name,
+                              const xmlChar * pubid,
+                              const xmlChar * sysid,
+                              const xmlChar * subset);
+
+/**
+ * xmlTextWriterWriteDocType:
+ *
+ * this macro maps to xmlTextWriterWriteDTD
+ */
+#define xmlTextWriterWriteDocType xmlTextWriterWriteDTD
+
+/*
+ * DTD element definition
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartDTDElement(xmlTextWriterPtr writer,
+                                     const xmlChar * name);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndDTDElement(xmlTextWriterPtr
+                                                     writer);
+
+/*
+ * DTD element definition conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatDTDElement(xmlTextWriterPtr writer,
+                                           const xmlChar * name,
+                                           const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatDTDElement(xmlTextWriterPtr writer,
+                                            const xmlChar * name,
+                                            const char *format,
+                                            va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDElement(xmlTextWriterPtr
+                                                       writer,
+                                                       const xmlChar *
+                                                       name,
+                                                       const xmlChar *
+                                                       content);
+
+/*
+ * DTD attribute list definition
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartDTDAttlist(xmlTextWriterPtr writer,
+                                     const xmlChar * name);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndDTDAttlist(xmlTextWriterPtr
+                                                     writer);
+
+/*
+ * DTD attribute list definition conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatDTDAttlist(xmlTextWriterPtr writer,
+                                           const xmlChar * name,
+                                           const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatDTDAttlist(xmlTextWriterPtr writer,
+                                            const xmlChar * name,
+                                            const char *format,
+                                            va_list argptr);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDAttlist(xmlTextWriterPtr
+                                                       writer,
+                                                       const xmlChar *
+                                                       name,
+                                                       const xmlChar *
+                                                       content);
+
+/*
+ * DTD entity definition
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterStartDTDEntity(xmlTextWriterPtr writer,
+                                    int pe, const xmlChar * name);
+    XMLPUBFUN int XMLCALL xmlTextWriterEndDTDEntity(xmlTextWriterPtr
+                                                    writer);
+
+/*
+ * DTD entity definition conveniency functions
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteFormatDTDInternalEntity(xmlTextWriterPtr writer,
+                                                  int pe,
+                                                  const xmlChar * name,
+                                                  const char *format, ...);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteVFormatDTDInternalEntity(xmlTextWriterPtr writer,
+                                                   int pe,
+                                                   const xmlChar * name,
+                                                   const char *format,
+                                                   va_list argptr);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteDTDInternalEntity(xmlTextWriterPtr writer,
+                                            int pe,
+                                            const xmlChar * name,
+                                            const xmlChar * content);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteDTDExternalEntity(xmlTextWriterPtr writer,
+                                            int pe,
+                                            const xmlChar * name,
+                                            const xmlChar * pubid,
+                                            const xmlChar * sysid,
+                                            const xmlChar * ndataid);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteDTDExternalEntityContents(xmlTextWriterPtr
+                                                    writer,
+                                                    const xmlChar * pubid,
+                                                    const xmlChar * sysid,
+                                                    const xmlChar *
+                                                    ndataid);
+    XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDEntity(xmlTextWriterPtr
+                                                      writer, int pe,
+                                                      const xmlChar * name,
+                                                      const xmlChar *
+                                                      pubid,
+                                                      const xmlChar *
+                                                      sysid,
+                                                      const xmlChar *
+                                                      ndataid,
+                                                      const xmlChar *
+                                                      content);
+
+/*
+ * DTD notation definition
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterWriteDTDNotation(xmlTextWriterPtr writer,
+                                      const xmlChar * name,
+                                      const xmlChar * pubid,
+                                      const xmlChar * sysid);
+
+/*
+ * Indentation
+ */
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterSetIndent(xmlTextWriterPtr writer, int indent);
+    XMLPUBFUN int XMLCALL
+        xmlTextWriterSetIndentString(xmlTextWriterPtr writer,
+                                     const xmlChar * str);
+
+/*
+ * misc
+ */
+    XMLPUBFUN int XMLCALL xmlTextWriterFlush(xmlTextWriterPtr writer);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_WRITER_ENABLED */
+
+#endif                          /* __XML_XMLWRITER_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xpath.h ./aperios/include/libxml2/libxml/xpath.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xpath.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xpath.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,513 @@
+/*
+ * Summary: XML Path Language implementation
+ * Description: API for the XML Path Language implementation
+ *
+ * XML Path Language implementation
+ * XPath is a language for addressing parts of an XML document,
+ * designed to be used by both XSLT and XPointer
+ *     http://www.w3.org/TR/xpath
+ *
+ * Implements
+ * W3C Recommendation 16 November 1999
+ *     http://www.w3.org/TR/1999/REC-xpath-19991116
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_XPATH_H__
+#define __XML_XPATH_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_XPATH_ENABLED
+
+#include <libxml/xmlerror.h>
+#include <libxml/tree.h>
+#include <libxml/hash.h>
+#endif /* LIBXML_XPATH_ENABLED */
+
+#if defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
+#ifdef __cplusplus
+extern "C" {
+#endif
+#endif /* LIBXML_XPATH_ENABLED or LIBXML_SCHEMAS_ENABLED */
+	
+#ifdef LIBXML_XPATH_ENABLED
+typedef struct _xmlXPathContext xmlXPathContext;
+typedef xmlXPathContext *xmlXPathContextPtr;
+typedef struct _xmlXPathParserContext xmlXPathParserContext;
+typedef xmlXPathParserContext *xmlXPathParserContextPtr;
+
+/**
+ * The set of XPath error codes.
+ */
+
+typedef enum {
+    XPATH_EXPRESSION_OK = 0,
+    XPATH_NUMBER_ERROR,
+    XPATH_UNFINISHED_LITERAL_ERROR,
+    XPATH_START_LITERAL_ERROR,
+    XPATH_VARIABLE_REF_ERROR,
+    XPATH_UNDEF_VARIABLE_ERROR,
+    XPATH_INVALID_PREDICATE_ERROR,
+    XPATH_EXPR_ERROR,
+    XPATH_UNCLOSED_ERROR,
+    XPATH_UNKNOWN_FUNC_ERROR,
+    XPATH_INVALID_OPERAND,
+    XPATH_INVALID_TYPE,
+    XPATH_INVALID_ARITY,
+    XPATH_INVALID_CTXT_SIZE,
+    XPATH_INVALID_CTXT_POSITION,
+    XPATH_MEMORY_ERROR,
+    XPTR_SYNTAX_ERROR,
+    XPTR_RESOURCE_ERROR,
+    XPTR_SUB_RESOURCE_ERROR,
+    XPATH_UNDEF_PREFIX_ERROR,
+    XPATH_ENCODING_ERROR,
+    XPATH_INVALID_CHAR_ERROR,
+    XPATH_INVALID_CTXT
+} xmlXPathError;
+
+/*
+ * A node-set (an unordered collection of nodes without duplicates).
+ */
+typedef struct _xmlNodeSet xmlNodeSet;
+typedef xmlNodeSet *xmlNodeSetPtr;
+struct _xmlNodeSet {
+    int nodeNr;			/* number of nodes in the set */
+    int nodeMax;		/* size of the array as allocated */
+    xmlNodePtr *nodeTab;	/* array of nodes in no particular order */
+    /* @@ with_ns to check wether namespace nodes should be looked at @@ */
+};
+
+/*
+ * An expression is evaluated to yield an object, which
+ * has one of the following four basic types:
+ *   - node-set
+ *   - boolean
+ *   - number
+ *   - string
+ *
+ * @@ XPointer will add more types !
+ */
+
+typedef enum {
+    XPATH_UNDEFINED = 0,
+    XPATH_NODESET = 1,
+    XPATH_BOOLEAN = 2,
+    XPATH_NUMBER = 3,
+    XPATH_STRING = 4,
+    XPATH_POINT = 5,
+    XPATH_RANGE = 6,
+    XPATH_LOCATIONSET = 7,
+    XPATH_USERS = 8,
+    XPATH_XSLT_TREE = 9  /* An XSLT value tree, non modifiable */
+} xmlXPathObjectType;
+
+typedef struct _xmlXPathObject xmlXPathObject;
+typedef xmlXPathObject *xmlXPathObjectPtr;
+struct _xmlXPathObject {
+    xmlXPathObjectType type;
+    xmlNodeSetPtr nodesetval;
+    int boolval;
+    double floatval;
+    xmlChar *stringval;
+    void *user;
+    int index;
+    void *user2;
+    int index2;
+};
+
+/**
+ * xmlXPathConvertFunc:
+ * @obj:  an XPath object
+ * @type:  the number of the target type
+ *
+ * A conversion function is associated to a type and used to cast
+ * the new type to primitive values.
+ *
+ * Returns -1 in case of error, 0 otherwise
+ */
+typedef int (*xmlXPathConvertFunc) (xmlXPathObjectPtr obj, int type);
+
+/*
+ * Extra type: a name and a conversion function.
+ */
+
+typedef struct _xmlXPathType xmlXPathType;
+typedef xmlXPathType *xmlXPathTypePtr;
+struct _xmlXPathType {
+    const xmlChar         *name;		/* the type name */
+    xmlXPathConvertFunc func;		/* the conversion function */
+};
+
+/*
+ * Extra variable: a name and a value.
+ */
+
+typedef struct _xmlXPathVariable xmlXPathVariable;
+typedef xmlXPathVariable *xmlXPathVariablePtr;
+struct _xmlXPathVariable {
+    const xmlChar       *name;		/* the variable name */
+    xmlXPathObjectPtr value;		/* the value */
+};
+
+/**
+ * xmlXPathEvalFunc:
+ * @ctxt: an XPath parser context
+ * @nargs: the number of arguments passed to the function
+ *
+ * An XPath evaluation function, the parameters are on the XPath context stack.
+ */
+
+typedef void (*xmlXPathEvalFunc)(xmlXPathParserContextPtr ctxt,
+	                         int nargs);
+
+/*
+ * Extra function: a name and a evaluation function.
+ */
+
+typedef struct _xmlXPathFunct xmlXPathFunct;
+typedef xmlXPathFunct *xmlXPathFuncPtr;
+struct _xmlXPathFunct {
+    const xmlChar      *name;		/* the function name */
+    xmlXPathEvalFunc func;		/* the evaluation function */
+};
+
+/**
+ * xmlXPathAxisFunc:
+ * @ctxt:  the XPath interpreter context
+ * @cur:  the previous node being explored on that axis
+ *
+ * An axis traversal function. To traverse an axis, the engine calls
+ * the first time with cur == NULL and repeat until the function returns
+ * NULL indicating the end of the axis traversal.
+ *
+ * Returns the next node in that axis or NULL if at the end of the axis.
+ */
+
+typedef xmlXPathObjectPtr (*xmlXPathAxisFunc) (xmlXPathParserContextPtr ctxt,
+				 xmlXPathObjectPtr cur);
+
+/*
+ * Extra axis: a name and an axis function.
+ */
+
+typedef struct _xmlXPathAxis xmlXPathAxis;
+typedef xmlXPathAxis *xmlXPathAxisPtr;
+struct _xmlXPathAxis {
+    const xmlChar      *name;		/* the axis name */
+    xmlXPathAxisFunc func;		/* the search function */
+};
+
+/**
+ * xmlXPathFunction:
+ * @ctxt:  the XPath interprestation context
+ * @nargs:  the number of arguments
+ *
+ * An XPath function.
+ * The arguments (if any) are popped out from the context stack
+ * and the result is pushed on the stack.
+ */
+
+typedef void (*xmlXPathFunction) (xmlXPathParserContextPtr ctxt, int nargs);
+
+/*
+ * Function and Variable Lookup.
+ */
+
+/**
+ * xmlXPathVariableLookupFunc:
+ * @ctxt:  an XPath context
+ * @name:  name of the variable
+ * @ns_uri:  the namespace name hosting this variable
+ *
+ * Prototype for callbacks used to plug variable lookup in the XPath
+ * engine.
+ *
+ * Returns the XPath object value or NULL if not found.
+ */
+typedef xmlXPathObjectPtr (*xmlXPathVariableLookupFunc) (void *ctxt,
+                                         const xmlChar *name,
+                                         const xmlChar *ns_uri);
+
+/**
+ * xmlXPathFuncLookupFunc:
+ * @ctxt:  an XPath context
+ * @name:  name of the function
+ * @ns_uri:  the namespace name hosting this function
+ *
+ * Prototype for callbacks used to plug function lookup in the XPath
+ * engine.
+ *
+ * Returns the XPath function or NULL if not found.
+ */
+typedef xmlXPathFunction (*xmlXPathFuncLookupFunc) (void *ctxt,
+					 const xmlChar *name,
+					 const xmlChar *ns_uri);
+
+/**
+ * xmlXPathContext:
+ *
+ * Expression evaluation occurs with respect to a context.
+ * he context consists of:
+ *    - a node (the context node) 
+ *    - a node list (the context node list) 
+ *    - a set of variable bindings 
+ *    - a function library 
+ *    - the set of namespace declarations in scope for the expression 
+ * Following the switch to hash tables, this need to be trimmed up at
+ * the next binary incompatible release.
+ */
+
+struct _xmlXPathContext {
+    xmlDocPtr doc;			/* The current document */
+    xmlNodePtr node;			/* The current node */
+
+    int nb_variables_unused;		/* unused (hash table) */
+    int max_variables_unused;		/* unused (hash table) */
+    xmlHashTablePtr varHash;		/* Hash table of defined variables */
+
+    int nb_types;			/* number of defined types */
+    int max_types;			/* max number of types */
+    xmlXPathTypePtr types;		/* Array of defined types */
+
+    int nb_funcs_unused;		/* unused (hash table) */
+    int max_funcs_unused;		/* unused (hash table) */
+    xmlHashTablePtr funcHash;		/* Hash table of defined funcs */
+
+    int nb_axis;			/* number of defined axis */
+    int max_axis;			/* max number of axis */
+    xmlXPathAxisPtr axis;		/* Array of defined axis */
+
+    /* the namespace nodes of the context node */
+    xmlNsPtr *namespaces;		/* Array of namespaces */
+    int nsNr;				/* number of namespace in scope */
+    void *user;				/* function to free */
+
+    /* extra variables */
+    int contextSize;			/* the context size */
+    int proximityPosition;		/* the proximity position */
+
+    /* extra stuff for XPointer */
+    int xptr;				/* it this an XPointer context */
+    xmlNodePtr here;			/* for here() */
+    xmlNodePtr origin;			/* for origin() */
+
+    /* the set of namespace declarations in scope for the expression */
+    xmlHashTablePtr nsHash;		/* The namespaces hash table */
+    xmlXPathVariableLookupFunc varLookupFunc;/* variable lookup func */
+    void *varLookupData;		/* variable lookup data */
+
+    /* Possibility to link in an extra item */
+    void *extra;                        /* needed for XSLT */
+
+    /* The function name and URI when calling a function */
+    const xmlChar *function;
+    const xmlChar *functionURI;
+
+    /* function lookup function and data */
+    xmlXPathFuncLookupFunc funcLookupFunc;/* function lookup func */
+    void *funcLookupData;		/* function lookup data */
+
+    /* temporary namespace lists kept for walking the namespace axis */
+    xmlNsPtr *tmpNsList;		/* Array of namespaces */
+    int tmpNsNr;			/* number of namespace in scope */
+
+    /* error reporting mechanism */
+    void *userData;                     /* user specific data block */
+    xmlStructuredErrorFunc error;       /* the callback in case of errors */
+    xmlError lastError;			/* the last error */
+    xmlNodePtr debugNode;		/* the source node XSLT */
+
+    /* dictionnary */
+    xmlDictPtr dict;			/* dictionnary if any */
+};
+
+/*
+ * The structure of a compiled expression form is not public.
+ */
+
+typedef struct _xmlXPathCompExpr xmlXPathCompExpr;
+typedef xmlXPathCompExpr *xmlXPathCompExprPtr;
+
+/**
+ * xmlXPathParserContext:
+ *
+ * An XPath parser context. It contains pure parsing informations,
+ * an xmlXPathContext, and the stack of objects.
+ */
+struct _xmlXPathParserContext {
+    const xmlChar *cur;			/* the current char being parsed */
+    const xmlChar *base;			/* the full expression */
+
+    int error;				/* error code */
+
+    xmlXPathContextPtr  context;	/* the evaluation context */
+    xmlXPathObjectPtr     value;	/* the current value */
+    int                 valueNr;	/* number of values stacked */
+    int                valueMax;	/* max number of values stacked */
+    xmlXPathObjectPtr *valueTab;	/* stack of values */
+
+    xmlXPathCompExprPtr comp;		/* the precompiled expression */
+    int xptr;				/* it this an XPointer expression */
+    xmlNodePtr         ancestor;	/* used for walking preceding axis */
+};
+
+/************************************************************************
+ *									*
+ *			Public API					*
+ *									*
+ ************************************************************************/
+
+/**
+ * Objects and Nodesets handling
+ */
+
+XMLPUBVAR double xmlXPathNAN;
+XMLPUBVAR double xmlXPathPINF;
+XMLPUBVAR double xmlXPathNINF;
+
+/* These macros may later turn into functions */
+/**
+ * xmlXPathNodeSetGetLength:
+ * @ns:  a node-set
+ *
+ * Implement a functionality similar to the DOM NodeList.length.
+ *
+ * Returns the number of nodes in the node-set.
+ */
+#define xmlXPathNodeSetGetLength(ns) ((ns) ? (ns)->nodeNr : 0)
+/**
+ * xmlXPathNodeSetItem:
+ * @ns:  a node-set
+ * @index:  index of a node in the set
+ *
+ * Implements a functionality similar to the DOM NodeList.item().
+ *
+ * Returns the xmlNodePtr at the given @index in @ns or NULL if
+ *         @index is out of range (0 to length-1)
+ */
+#define xmlXPathNodeSetItem(ns, index)				\
+		((((ns) != NULL) && 				\
+		  ((index) >= 0) && ((index) < (ns)->nodeNr)) ?	\
+		 (ns)->nodeTab[(index)]				\
+		 : NULL)
+/**
+ * xmlXPathNodeSetIsEmpty:
+ * @ns: a node-set
+ *
+ * Checks whether @ns is empty or not.
+ *
+ * Returns %TRUE if @ns is an empty node-set.
+ */
+#define xmlXPathNodeSetIsEmpty(ns)                                      \
+    (((ns) == NULL) || ((ns)->nodeNr == 0) || ((ns)->nodeTab == NULL))
+
+
+XMLPUBFUN void XMLCALL		   
+		    xmlXPathFreeObject		(xmlXPathObjectPtr obj);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	   
+		    xmlXPathNodeSetCreate	(xmlNodePtr val);
+XMLPUBFUN void XMLCALL		   
+		    xmlXPathFreeNodeSetList	(xmlXPathObjectPtr obj);
+XMLPUBFUN void XMLCALL		   
+		    xmlXPathFreeNodeSet		(xmlNodeSetPtr obj);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		    xmlXPathObjectCopy		(xmlXPathObjectPtr val);
+XMLPUBFUN int XMLCALL		   
+		    xmlXPathCmpNodes		(xmlNodePtr node1,
+						 xmlNodePtr node2);
+/**
+ * Conversion functions to basic types.
+ */
+XMLPUBFUN int XMLCALL		   
+		    xmlXPathCastNumberToBoolean	(double val);
+XMLPUBFUN int XMLCALL		   
+		    xmlXPathCastStringToBoolean	(const xmlChar * val);
+XMLPUBFUN int XMLCALL		   
+		    xmlXPathCastNodeSetToBoolean(xmlNodeSetPtr ns);
+XMLPUBFUN int XMLCALL		   
+		    xmlXPathCastToBoolean	(xmlXPathObjectPtr val);
+
+XMLPUBFUN double XMLCALL		   
+		    xmlXPathCastBooleanToNumber	(int val);
+XMLPUBFUN double XMLCALL		   
+		    xmlXPathCastStringToNumber	(const xmlChar * val);
+XMLPUBFUN double XMLCALL		   
+		    xmlXPathCastNodeToNumber	(xmlNodePtr node);
+XMLPUBFUN double XMLCALL		   
+		    xmlXPathCastNodeSetToNumber	(xmlNodeSetPtr ns);
+XMLPUBFUN double XMLCALL		   
+		    xmlXPathCastToNumber	(xmlXPathObjectPtr val);
+
+XMLPUBFUN xmlChar * XMLCALL	   
+		    xmlXPathCastBooleanToString	(int val);
+XMLPUBFUN xmlChar * XMLCALL	   
+		    xmlXPathCastNumberToString	(double val);
+XMLPUBFUN xmlChar * XMLCALL	   
+		    xmlXPathCastNodeToString	(xmlNodePtr node);
+XMLPUBFUN xmlChar * XMLCALL	   
+		    xmlXPathCastNodeSetToString	(xmlNodeSetPtr ns);
+XMLPUBFUN xmlChar * XMLCALL	   
+		    xmlXPathCastToString	(xmlXPathObjectPtr val);
+
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		    xmlXPathConvertBoolean	(xmlXPathObjectPtr val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		    xmlXPathConvertNumber	(xmlXPathObjectPtr val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		    xmlXPathConvertString	(xmlXPathObjectPtr val);
+
+/**
+ * Context handling.
+ */
+XMLPUBFUN xmlXPathContextPtr XMLCALL 
+		    xmlXPathNewContext		(xmlDocPtr doc);
+XMLPUBFUN void XMLCALL		   
+		    xmlXPathFreeContext		(xmlXPathContextPtr ctxt);
+
+/**
+ * Evaluation functions.
+ */
+XMLPUBFUN long XMLCALL               
+		    xmlXPathOrderDocElems	(xmlDocPtr doc);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		    xmlXPathEval		(const xmlChar *str,
+						 xmlXPathContextPtr ctx);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		    xmlXPathEvalExpression	(const xmlChar *str,
+						 xmlXPathContextPtr ctxt);
+XMLPUBFUN int XMLCALL                
+		    xmlXPathEvalPredicate	(xmlXPathContextPtr ctxt,
+						 xmlXPathObjectPtr res);
+/**
+ * Separate compilation/evaluation entry points.
+ */
+XMLPUBFUN xmlXPathCompExprPtr XMLCALL 
+		    xmlXPathCompile		(const xmlChar *str);
+XMLPUBFUN xmlXPathCompExprPtr XMLCALL 
+		    xmlXPathCtxtCompile		(xmlXPathContextPtr ctxt,
+		    				 const xmlChar *str);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL   
+		    xmlXPathCompiledEval	(xmlXPathCompExprPtr comp,
+						 xmlXPathContextPtr ctx);
+XMLPUBFUN void XMLCALL                
+		    xmlXPathFreeCompExpr	(xmlXPathCompExprPtr comp);
+#endif /* LIBXML_XPATH_ENABLED */
+#if defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
+XMLPUBFUN void XMLCALL		   
+		    xmlXPathInit		(void);
+XMLPUBFUN int XMLCALL
+		xmlXPathIsNaN	(double val);
+XMLPUBFUN int XMLCALL
+		xmlXPathIsInf	(double val);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_XPATH_ENABLED or LIBXML_SCHEMAS_ENABLED*/
+#endif /* ! __XML_XPATH_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xpathInternals.h ./aperios/include/libxml2/libxml/xpathInternals.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xpathInternals.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xpathInternals.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,630 @@
+/*
+ * Summary: internal interfaces for XML Path Language implementation
+ * Description: internal interfaces for XML Path Language implementation
+ *              used to build new modules on top of XPath like XPointer and
+ *              XSLT
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_XPATH_INTERNALS_H__
+#define __XML_XPATH_INTERNALS_H__
+
+#include <libxml/xmlversion.h>
+#include <libxml/xpath.h>
+
+#ifdef LIBXML_XPATH_ENABLED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/************************************************************************
+ *									*
+ *			Helpers						*
+ *									*
+ ************************************************************************/
+
+/*
+ * Many of these macros may later turn into functions. They
+ * shouldn't be used in #ifdef's preprocessor instructions.
+ */
+/**
+ * xmlXPathSetError:
+ * @ctxt:  an XPath parser context
+ * @err:  an xmlXPathError code
+ *
+ * Raises an error.
+ */
+#define xmlXPathSetError(ctxt, err)					\
+    { xmlXPatherror((ctxt), __FILE__, __LINE__, (err));			\
+      if ((ctxt) != NULL) (ctxt)->error = (err); }
+
+/**
+ * xmlXPathSetArityError:
+ * @ctxt:  an XPath parser context
+ *
+ * Raises an XPATH_INVALID_ARITY error.
+ */
+#define xmlXPathSetArityError(ctxt)					\
+    xmlXPathSetError((ctxt), XPATH_INVALID_ARITY)
+
+/**
+ * xmlXPathSetTypeError:
+ * @ctxt:  an XPath parser context
+ *
+ * Raises an XPATH_INVALID_TYPE error.
+ */
+#define xmlXPathSetTypeError(ctxt)					\
+    xmlXPathSetError((ctxt), XPATH_INVALID_TYPE)
+
+/**
+ * xmlXPathGetError:
+ * @ctxt:  an XPath parser context
+ *
+ * Get the error code of an XPath context.
+ *
+ * Returns the context error.
+ */
+#define xmlXPathGetError(ctxt)	  ((ctxt)->error)
+
+/**
+ * xmlXPathCheckError:
+ * @ctxt:  an XPath parser context
+ *
+ * Check if an XPath error was raised.
+ *
+ * Returns true if an error has been raised, false otherwise.
+ */
+#define xmlXPathCheckError(ctxt)  ((ctxt)->error != XPATH_EXPRESSION_OK)
+
+/**
+ * xmlXPathGetDocument:
+ * @ctxt:  an XPath parser context
+ *
+ * Get the document of an XPath context.
+ *
+ * Returns the context document.
+ */
+#define xmlXPathGetDocument(ctxt)	((ctxt)->context->doc)
+
+/**
+ * xmlXPathGetContextNode:
+ * @ctxt: an XPath parser context
+ *
+ * Get the context node of an XPath context.
+ *
+ * Returns the context node.
+ */
+#define xmlXPathGetContextNode(ctxt)	((ctxt)->context->node)
+
+XMLPUBFUN int XMLCALL		
+		xmlXPathPopBoolean	(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN double XMLCALL		
+    		xmlXPathPopNumber	(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL	
+    		xmlXPathPopString	(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+    		xmlXPathPopNodeSet	(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN void * XMLCALL		
+    		xmlXPathPopExternal	(xmlXPathParserContextPtr ctxt);
+
+/**
+ * xmlXPathReturnBoolean:
+ * @ctxt:  an XPath parser context
+ * @val:  a boolean
+ *
+ * Pushes the boolean @val on the context stack.
+ */
+#define xmlXPathReturnBoolean(ctxt, val)				\
+    valuePush((ctxt), xmlXPathNewBoolean(val))
+
+/**
+ * xmlXPathReturnTrue:
+ * @ctxt:  an XPath parser context
+ *
+ * Pushes true on the context stack.
+ */
+#define xmlXPathReturnTrue(ctxt)   xmlXPathReturnBoolean((ctxt), 1)
+
+/**
+ * xmlXPathReturnFalse:
+ * @ctxt:  an XPath parser context
+ *
+ * Pushes false on the context stack.
+ */
+#define xmlXPathReturnFalse(ctxt)  xmlXPathReturnBoolean((ctxt), 0)
+
+/**
+ * xmlXPathReturnNumber:
+ * @ctxt:  an XPath parser context
+ * @val:  a double
+ *
+ * Pushes the double @val on the context stack.
+ */
+#define xmlXPathReturnNumber(ctxt, val)					\
+    valuePush((ctxt), xmlXPathNewFloat(val))
+
+/**
+ * xmlXPathReturnString:
+ * @ctxt:  an XPath parser context
+ * @str:  a string
+ *
+ * Pushes the string @str on the context stack.
+ */
+#define xmlXPathReturnString(ctxt, str)					\
+    valuePush((ctxt), xmlXPathWrapString(str))
+
+/**
+ * xmlXPathReturnEmptyString:
+ * @ctxt:  an XPath parser context
+ *
+ * Pushes an empty string on the stack.
+ */
+#define xmlXPathReturnEmptyString(ctxt)					\
+    valuePush((ctxt), xmlXPathNewCString(""))
+
+/**
+ * xmlXPathReturnNodeSet:
+ * @ctxt:  an XPath parser context
+ * @ns:  a node-set
+ *
+ * Pushes the node-set @ns on the context stack.
+ */
+#define xmlXPathReturnNodeSet(ctxt, ns)					\
+    valuePush((ctxt), xmlXPathWrapNodeSet(ns))
+
+/**
+ * xmlXPathReturnEmptyNodeSet:
+ * @ctxt:  an XPath parser context
+ *
+ * Pushes an empty node-set on the context stack.
+ */
+#define xmlXPathReturnEmptyNodeSet(ctxt)				\
+    valuePush((ctxt), xmlXPathNewNodeSet(NULL))
+
+/**
+ * xmlXPathReturnExternal:
+ * @ctxt:  an XPath parser context
+ * @val:  user data
+ *
+ * Pushes user data on the context stack.
+ */
+#define xmlXPathReturnExternal(ctxt, val)				\
+    valuePush((ctxt), xmlXPathWrapExternal(val))
+
+/**
+ * xmlXPathStackIsNodeSet:
+ * @ctxt: an XPath parser context
+ *
+ * Check if the current value on the XPath stack is a node set or
+ * an XSLT value tree.
+ *
+ * Returns true if the current object on the stack is a node-set.
+ */
+#define xmlXPathStackIsNodeSet(ctxt)					\
+    (((ctxt)->value != NULL)						\
+     && (((ctxt)->value->type == XPATH_NODESET)				\
+         || ((ctxt)->value->type == XPATH_XSLT_TREE)))
+
+/**
+ * xmlXPathStackIsExternal:
+ * @ctxt: an XPath parser context
+ *
+ * Checks if the current value on the XPath stack is an external
+ * object.
+ *
+ * Returns true if the current object on the stack is an external
+ * object.
+ */
+#define xmlXPathStackIsExternal(ctxt)					\
+	((ctxt->value != NULL) && (ctxt->value->type == XPATH_USERS))
+
+/**
+ * xmlXPathEmptyNodeSet:
+ * @ns:  a node-set
+ *
+ * Empties a node-set.
+ */
+#define xmlXPathEmptyNodeSet(ns)					\
+    { while ((ns)->nodeNr > 0) (ns)->nodeTab[(ns)->nodeNr--] = NULL; }
+
+/**
+ * CHECK_ERROR:
+ *
+ * Macro to return from the function if an XPath error was detected.
+ */
+#define CHECK_ERROR							\
+    if (ctxt->error != XPATH_EXPRESSION_OK) return
+
+/**
+ * CHECK_ERROR0:
+ *
+ * Macro to return 0 from the function if an XPath error was detected.
+ */
+#define CHECK_ERROR0							\
+    if (ctxt->error != XPATH_EXPRESSION_OK) return(0)
+
+/**
+ * XP_ERROR:
+ * @X:  the error code
+ *
+ * Macro to raise an XPath error and return.
+ */
+#define XP_ERROR(X)							\
+    { xmlXPathErr(ctxt, X); return; }
+
+/**
+ * XP_ERROR0:
+ * @X:  the error code
+ *
+ * Macro to raise an XPath error and return 0.
+ */
+#define XP_ERROR0(X)							\
+    { xmlXPathErr(ctxt, X); return(0); }
+
+/**
+ * CHECK_TYPE:
+ * @typeval:  the XPath type
+ *
+ * Macro to check that the value on top of the XPath stack is of a given
+ * type.
+ */
+#define CHECK_TYPE(typeval)						\
+    if ((ctxt->value == NULL) || (ctxt->value->type != typeval))	\
+        XP_ERROR(XPATH_INVALID_TYPE)
+
+/**
+ * CHECK_TYPE0:
+ * @typeval:  the XPath type
+ *
+ * Macro to check that the value on top of the XPath stack is of a given
+ * type. Return(0) in case of failure
+ */
+#define CHECK_TYPE0(typeval)						\
+    if ((ctxt->value == NULL) || (ctxt->value->type != typeval))	\
+        XP_ERROR0(XPATH_INVALID_TYPE)
+
+/**
+ * CHECK_ARITY:
+ * @x:  the number of expected args
+ *
+ * Macro to check that the number of args passed to an XPath function matches.
+ */
+#define CHECK_ARITY(x)							\
+    if (ctxt == NULL) return;						\
+    if (nargs != (x))							\
+        XP_ERROR(XPATH_INVALID_ARITY);
+
+/**
+ * CAST_TO_STRING:
+ *
+ * Macro to try to cast the value on the top of the XPath stack to a string.
+ */
+#define CAST_TO_STRING							\
+    if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_STRING))	\
+        xmlXPathStringFunction(ctxt, 1);
+
+/**
+ * CAST_TO_NUMBER:
+ *
+ * Macro to try to cast the value on the top of the XPath stack to a number.
+ */
+#define CAST_TO_NUMBER							\
+    if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_NUMBER))	\
+        xmlXPathNumberFunction(ctxt, 1);
+
+/**
+ * CAST_TO_BOOLEAN:
+ *
+ * Macro to try to cast the value on the top of the XPath stack to a boolean.
+ */
+#define CAST_TO_BOOLEAN							\
+    if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_BOOLEAN))	\
+        xmlXPathBooleanFunction(ctxt, 1);
+
+/*
+ * Variable Lookup forwarding.
+ */
+
+XMLPUBFUN void XMLCALL	
+	xmlXPathRegisterVariableLookup	(xmlXPathContextPtr ctxt,
+					 xmlXPathVariableLookupFunc f,
+					 void *data);
+
+/*
+ * Function Lookup forwarding.
+ */
+
+XMLPUBFUN void XMLCALL	
+	    xmlXPathRegisterFuncLookup	(xmlXPathContextPtr ctxt,
+					 xmlXPathFuncLookupFunc f,
+					 void *funcCtxt);
+
+/*
+ * Error reporting.
+ */
+XMLPUBFUN void XMLCALL		
+		xmlXPatherror	(xmlXPathParserContextPtr ctxt,
+				 const char *file,
+				 int line,
+				 int no);
+
+XMLPUBFUN void XMLCALL
+		xmlXPathErr	(xmlXPathParserContextPtr ctxt,
+				 int error);
+
+#ifdef LIBXML_DEBUG_ENABLED
+XMLPUBFUN void XMLCALL		
+		xmlXPathDebugDumpObject	(FILE *output,
+					 xmlXPathObjectPtr cur,
+					 int depth);
+XMLPUBFUN void XMLCALL		
+	    xmlXPathDebugDumpCompExpr(FILE *output,
+					 xmlXPathCompExprPtr comp,
+					 int depth);
+#endif
+/**
+ * NodeSet handling.
+ */
+XMLPUBFUN int XMLCALL		
+		xmlXPathNodeSetContains		(xmlNodeSetPtr cur,
+						 xmlNodePtr val);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathDifference		(xmlNodeSetPtr nodes1,
+						 xmlNodeSetPtr nodes2);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathIntersection		(xmlNodeSetPtr nodes1,
+						 xmlNodeSetPtr nodes2);
+
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathDistinctSorted		(xmlNodeSetPtr nodes);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathDistinct		(xmlNodeSetPtr nodes);
+
+XMLPUBFUN int XMLCALL		
+		xmlXPathHasSameNodes		(xmlNodeSetPtr nodes1,
+						 xmlNodeSetPtr nodes2);
+
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathNodeLeadingSorted	(xmlNodeSetPtr nodes,
+						 xmlNodePtr node);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathLeadingSorted		(xmlNodeSetPtr nodes1,
+						 xmlNodeSetPtr nodes2);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathNodeLeading		(xmlNodeSetPtr nodes,
+						 xmlNodePtr node);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathLeading			(xmlNodeSetPtr nodes1,
+						 xmlNodeSetPtr nodes2);
+
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathNodeTrailingSorted	(xmlNodeSetPtr nodes,
+						 xmlNodePtr node);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathTrailingSorted		(xmlNodeSetPtr nodes1,
+						 xmlNodeSetPtr nodes2);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathNodeTrailing		(xmlNodeSetPtr nodes,
+						 xmlNodePtr node);
+XMLPUBFUN xmlNodeSetPtr XMLCALL	
+		xmlXPathTrailing		(xmlNodeSetPtr nodes1,
+						 xmlNodeSetPtr nodes2);
+
+
+/**
+ * Extending a context.
+ */
+
+XMLPUBFUN int XMLCALL		   
+		xmlXPathRegisterNs		(xmlXPathContextPtr ctxt,
+						 const xmlChar *prefix,
+						 const xmlChar *ns_uri);
+XMLPUBFUN const xmlChar * XMLCALL	   
+		xmlXPathNsLookup		(xmlXPathContextPtr ctxt,
+						 const xmlChar *prefix);
+XMLPUBFUN void XMLCALL		   
+		xmlXPathRegisteredNsCleanup	(xmlXPathContextPtr ctxt);
+
+XMLPUBFUN int XMLCALL		   
+		xmlXPathRegisterFunc		(xmlXPathContextPtr ctxt,
+						 const xmlChar *name,
+						 xmlXPathFunction f);
+XMLPUBFUN int XMLCALL		   
+		xmlXPathRegisterFuncNS		(xmlXPathContextPtr ctxt,
+						 const xmlChar *name,
+						 const xmlChar *ns_uri,
+						 xmlXPathFunction f);
+XMLPUBFUN int XMLCALL		   
+		xmlXPathRegisterVariable	(xmlXPathContextPtr ctxt,
+						 const xmlChar *name,
+						 xmlXPathObjectPtr value);
+XMLPUBFUN int XMLCALL		   
+		xmlXPathRegisterVariableNS	(xmlXPathContextPtr ctxt,
+						 const xmlChar *name,
+						 const xmlChar *ns_uri,
+						 xmlXPathObjectPtr value);
+XMLPUBFUN xmlXPathFunction XMLCALL   
+		xmlXPathFunctionLookup		(xmlXPathContextPtr ctxt,
+						 const xmlChar *name);
+XMLPUBFUN xmlXPathFunction XMLCALL   
+		xmlXPathFunctionLookupNS	(xmlXPathContextPtr ctxt,
+						 const xmlChar *name,
+						 const xmlChar *ns_uri);
+XMLPUBFUN void XMLCALL		   
+		xmlXPathRegisteredFuncsCleanup	(xmlXPathContextPtr ctxt);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		xmlXPathVariableLookup		(xmlXPathContextPtr ctxt,
+						 const xmlChar *name);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL  
+		xmlXPathVariableLookupNS	(xmlXPathContextPtr ctxt,
+						 const xmlChar *name,
+						 const xmlChar *ns_uri);
+XMLPUBFUN void XMLCALL		   
+		xmlXPathRegisteredVariablesCleanup(xmlXPathContextPtr ctxt);
+
+/**
+ * Utilities to extend XPath.
+ */
+XMLPUBFUN xmlXPathParserContextPtr XMLCALL
+		  xmlXPathNewParserContext	(const xmlChar *str,
+			  			 xmlXPathContextPtr ctxt);
+XMLPUBFUN void XMLCALL		  
+		xmlXPathFreeParserContext	(xmlXPathParserContextPtr ctxt);
+
+/* TODO: remap to xmlXPathValuePop and Push. */
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		valuePop			(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN int XMLCALL		  
+		valuePush			(xmlXPathParserContextPtr ctxt,
+					 	 xmlXPathObjectPtr value);
+
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathNewString		(const xmlChar *val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathNewCString		(const char *val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathWrapString		(xmlChar *val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathWrapCString		(char * val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathNewFloat		(double val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathNewBoolean		(int val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathNewNodeSet		(xmlNodePtr val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathNewValueTree		(xmlNodePtr val);
+XMLPUBFUN void XMLCALL		  
+		xmlXPathNodeSetAdd		(xmlNodeSetPtr cur,
+						 xmlNodePtr val);
+XMLPUBFUN void XMLCALL              
+		xmlXPathNodeSetAddUnique	(xmlNodeSetPtr cur,
+						 xmlNodePtr val);
+XMLPUBFUN void XMLCALL		  
+		xmlXPathNodeSetAddNs		(xmlNodeSetPtr cur, 
+						 xmlNodePtr node, 
+						 xmlNsPtr ns);
+XMLPUBFUN void XMLCALL              
+		xmlXPathNodeSetSort		(xmlNodeSetPtr set);
+
+XMLPUBFUN void XMLCALL		  
+		xmlXPathRoot			(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN void XMLCALL		  
+		xmlXPathEvalExpr		(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL	  
+		xmlXPathParseName		(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN xmlChar * XMLCALL	  
+		xmlXPathParseNCName		(xmlXPathParserContextPtr ctxt);
+
+/*
+ * Existing functions.
+ */
+XMLPUBFUN double XMLCALL 
+		xmlXPathStringEvalNumber	(const xmlChar *str);
+XMLPUBFUN int XMLCALL 
+		xmlXPathEvaluatePredicateResult (xmlXPathParserContextPtr ctxt, 
+						 xmlXPathObjectPtr res);
+XMLPUBFUN void XMLCALL 
+		xmlXPathRegisterAllFunctions	(xmlXPathContextPtr ctxt);
+XMLPUBFUN xmlNodeSetPtr XMLCALL 
+		xmlXPathNodeSetMerge		(xmlNodeSetPtr val1, 
+						 xmlNodeSetPtr val2);
+XMLPUBFUN void XMLCALL 
+		xmlXPathNodeSetDel		(xmlNodeSetPtr cur, 
+						 xmlNodePtr val);
+XMLPUBFUN void XMLCALL 
+		xmlXPathNodeSetRemove		(xmlNodeSetPtr cur, 
+						 int val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathNewNodeSetList		(xmlNodeSetPtr val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathWrapNodeSet		(xmlNodeSetPtr val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL 
+		xmlXPathWrapExternal		(void *val);
+
+XMLPUBFUN int XMLCALL xmlXPathEqualValues(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN int XMLCALL xmlXPathNotEqualValues(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN int XMLCALL xmlXPathCompareValues(xmlXPathParserContextPtr ctxt, int inf, int strict);
+XMLPUBFUN void XMLCALL xmlXPathValueFlipSign(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN void XMLCALL xmlXPathAddValues(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN void XMLCALL xmlXPathSubValues(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN void XMLCALL xmlXPathMultValues(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN void XMLCALL xmlXPathDivValues(xmlXPathParserContextPtr ctxt);
+XMLPUBFUN void XMLCALL xmlXPathModValues(xmlXPathParserContextPtr ctxt);
+
+XMLPUBFUN int XMLCALL xmlXPathIsNodeType(const xmlChar *name);
+
+/*
+ * Some of the axis navigation routines.
+ */
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextSelf(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextChild(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextDescendant(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextDescendantOrSelf(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextParent(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextAncestorOrSelf(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextFollowingSibling(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextFollowing(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextNamespace(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextAttribute(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextPreceding(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextAncestor(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+XMLPUBFUN xmlNodePtr XMLCALL xmlXPathNextPrecedingSibling(xmlXPathParserContextPtr ctxt,
+			xmlNodePtr cur);
+/*
+ * The official core of XPath functions.
+ */
+XMLPUBFUN void XMLCALL xmlXPathLastFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathPositionFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathCountFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathIdFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathLocalNameFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathNamespaceURIFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathStringFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathStringLengthFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathConcatFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathContainsFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathStartsWithFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathSubstringFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathSubstringBeforeFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathSubstringAfterFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathNormalizeFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathTranslateFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathNotFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathTrueFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathFalseFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathLangFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathNumberFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathSumFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathFloorFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathCeilingFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathRoundFunction(xmlXPathParserContextPtr ctxt, int nargs);
+XMLPUBFUN void XMLCALL xmlXPathBooleanFunction(xmlXPathParserContextPtr ctxt, int nargs);
+
+/**
+ * Really internal functions
+ */
+XMLPUBFUN void XMLCALL xmlXPathNodeSetFreeNs(xmlNsPtr ns);
+ 
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_XPATH_ENABLED */
+#endif /* ! __XML_XPATH_INTERNALS_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xpointer.h ./aperios/include/libxml2/libxml/xpointer.h
--- ../Tekkotsu_2.3/aperios/include/libxml2/libxml/xpointer.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/libxml2/libxml/xpointer.h	Wed Jun  1 01:48:02 2005
@@ -0,0 +1,114 @@
+/*
+ * Summary: API to handle XML Pointers
+ * Description: API to handle XML Pointers
+ * Base implementation was made accordingly to
+ * W3C Candidate Recommendation 7 June 2000
+ * http://www.w3.org/TR/2000/CR-xptr-20000607
+ *
+ * Added support for the element() scheme described in:
+ * W3C Proposed Recommendation 13 November 2002
+ * http://www.w3.org/TR/2002/PR-xptr-element-20021113/  
+ *
+ * Copy: See Copyright for the status of this software.
+ *
+ * Author: Daniel Veillard
+ */
+
+#ifndef __XML_XPTR_H__
+#define __XML_XPTR_H__
+
+#include <libxml/xmlversion.h>
+
+#ifdef LIBXML_XPTR_ENABLED
+
+#include <libxml/tree.h>
+#include <libxml/xpath.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * A Location Set
+ */
+typedef struct _xmlLocationSet xmlLocationSet;
+typedef xmlLocationSet *xmlLocationSetPtr;
+struct _xmlLocationSet {
+    int locNr;		      /* number of locations in the set */
+    int locMax;		      /* size of the array as allocated */
+    xmlXPathObjectPtr *locTab;/* array of locations */
+};
+
+/*
+ * Handling of location sets.
+ */
+
+XMLPUBFUN xmlLocationSetPtr XMLCALL			
+		    xmlXPtrLocationSetCreate	(xmlXPathObjectPtr val);
+XMLPUBFUN void XMLCALL			
+		    xmlXPtrFreeLocationSet	(xmlLocationSetPtr obj);
+XMLPUBFUN xmlLocationSetPtr XMLCALL	
+		    xmlXPtrLocationSetMerge	(xmlLocationSetPtr val1,
+						 xmlLocationSetPtr val2);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewRange		(xmlNodePtr start,
+						 int startindex,
+						 xmlNodePtr end,
+						 int endindex);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewRangePoints	(xmlXPathObjectPtr start,
+						 xmlXPathObjectPtr end);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewRangeNodePoint	(xmlNodePtr start,
+						 xmlXPathObjectPtr end);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewRangePointNode	(xmlXPathObjectPtr start,
+						 xmlNodePtr end);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL			
+		    xmlXPtrNewRangeNodes	(xmlNodePtr start,
+						 xmlNodePtr end);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewLocationSetNodes	(xmlNodePtr start,
+						 xmlNodePtr end);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewLocationSetNodeSet(xmlNodeSetPtr set);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewRangeNodeObject	(xmlNodePtr start,
+						 xmlXPathObjectPtr end);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrNewCollapsedRange	(xmlNodePtr start);
+XMLPUBFUN void XMLCALL			
+		    xmlXPtrLocationSetAdd	(xmlLocationSetPtr cur,
+						 xmlXPathObjectPtr val);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrWrapLocationSet	(xmlLocationSetPtr val);
+XMLPUBFUN void XMLCALL			
+		    xmlXPtrLocationSetDel	(xmlLocationSetPtr cur,
+						 xmlXPathObjectPtr val);
+XMLPUBFUN void XMLCALL			
+		    xmlXPtrLocationSetRemove	(xmlLocationSetPtr cur,
+						 int val);
+
+/*
+ * Functions.
+ */
+XMLPUBFUN xmlXPathContextPtr XMLCALL	
+		    xmlXPtrNewContext		(xmlDocPtr doc,
+						 xmlNodePtr here,
+						 xmlNodePtr origin);
+XMLPUBFUN xmlXPathObjectPtr XMLCALL	
+		    xmlXPtrEval			(const xmlChar *str,
+						 xmlXPathContextPtr ctx);
+XMLPUBFUN void XMLCALL					    
+		    xmlXPtrRangeToFunction	(xmlXPathParserContextPtr ctxt,
+       						 int nargs);
+XMLPUBFUN xmlNodePtr XMLCALL		
+		    xmlXPtrBuildNodeList	(xmlXPathObjectPtr obj);
+XMLPUBFUN void XMLCALL		
+		    xmlXPtrEvalRangePredicate	(xmlXPathParserContextPtr ctxt);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LIBXML_XPTR_ENABLED */
+#endif /* __XML_XPTR_H__ */
diff -urdN ../Tekkotsu_2.3/aperios/include/png.h ./aperios/include/png.h
--- ../Tekkotsu_2.3/aperios/include/png.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/png.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,3419 @@
+/* png.h - header file for PNG reference library
+ *
+ * libpng version 1.2.8 - December 3, 2004
+ * Copyright (c) 1998-2004 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ *
+ * Authors and maintainers:
+ *  libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
+ *  libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
+ *  libpng versions 0.97, January 1998, through 1.2.8 - December 3, 2004: Glenn
+ *  See also "Contributing Authors", below.
+ *
+ * Note about libpng version numbers:
+ *
+ *    Due to various miscommunications, unforeseen code incompatibilities
+ *    and occasional factors outside the authors' control, version numbering
+ *    on the library has not always been consistent and straightforward.
+ *    The following table summarizes matters since version 0.89c, which was
+ *    the first widely used release:
+ *
+ *    source                 png.h  png.h  shared-lib
+ *    version                string   int  version
+ *    -------                ------ -----  ----------
+ *    0.89c "1.0 beta 3"     0.89      89  1.0.89
+ *    0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
+ *    0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
+ *    0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
+ *    0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
+ *    0.97c                  0.97      97  2.0.97
+ *    0.98                   0.98      98  2.0.98
+ *    0.99                   0.99      98  2.0.99
+ *    0.99a-m                0.99      99  2.0.99
+ *    1.00                   1.00     100  2.1.0 [100 should be 10000]
+ *    1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
+ *    1.0.1       png.h string is   10001  2.1.0
+ *    1.0.1a-e    identical to the  10002  from here on, the shared library
+ *    1.0.2       source version)   10002  is 2.V where V is the source code
+ *    1.0.2a-b                      10003  version, except as noted.
+ *    1.0.3                         10003
+ *    1.0.3a-d                      10004
+ *    1.0.4                         10004
+ *    1.0.4a-f                      10005
+ *    1.0.5 (+ 2 patches)           10005
+ *    1.0.5a-d                      10006
+ *    1.0.5e-r                      10100 (not source compatible)
+ *    1.0.5s-v                      10006 (not binary compatible)
+ *    1.0.6 (+ 3 patches)           10006 (still binary incompatible)
+ *    1.0.6d-f                      10007 (still binary incompatible)
+ *    1.0.6g                        10007
+ *    1.0.6h                        10007  10.6h (testing xy.z so-numbering)
+ *    1.0.6i                        10007  10.6i
+ *    1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)
+ *    1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)
+ *    1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)
+ *    1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
+ *    1.0.7                    1    10007  (still compatible)
+ *    1.0.8beta1-4             1    10008  2.1.0.8beta1-4
+ *    1.0.8rc1                 1    10008  2.1.0.8rc1
+ *    1.0.8                    1    10008  2.1.0.8
+ *    1.0.9beta1-6             1    10009  2.1.0.9beta1-6
+ *    1.0.9rc1                 1    10009  2.1.0.9rc1
+ *    1.0.9beta7-10            1    10009  2.1.0.9beta7-10
+ *    1.0.9rc2                 1    10009  2.1.0.9rc2
+ *    1.0.9                    1    10009  2.1.0.9
+ *    1.0.10beta1              1    10010  2.1.0.10beta1
+ *    1.0.10rc1                1    10010  2.1.0.10rc1
+ *    1.0.10                   1    10010  2.1.0.10
+ *    1.0.11beta1-3            1    10011  2.1.0.11beta1-3
+ *    1.0.11rc1                1    10011  2.1.0.11rc1
+ *    1.0.11                   1    10011  2.1.0.11
+ *    1.0.12beta1-2            2    10012  2.1.0.12beta1-2
+ *    1.0.12rc1                2    10012  2.1.0.12rc1
+ *    1.0.12                   2    10012  2.1.0.12
+ *    1.1.0a-f                 -    10100  2.1.1.0a-f (branch abandoned)
+ *    1.2.0beta1-2             2    10200  2.1.2.0beta1-2
+ *    1.2.0beta3-5             3    10200  3.1.2.0beta3-5
+ *    1.2.0rc1                 3    10200  3.1.2.0rc1
+ *    1.2.0                    3    10200  3.1.2.0
+ *    1.2.1beta1-4             3    10201  3.1.2.1beta1-4
+ *    1.2.1rc1-2               3    10201  3.1.2.1rc1-2
+ *    1.2.1                    3    10201  3.1.2.1
+ *    1.2.2beta1-6            12    10202  12.so.0.1.2.2beta1-6
+ *    1.0.13beta1             10    10013  10.so.0.1.0.13beta1
+ *    1.0.13rc1               10    10013  10.so.0.1.0.13rc1
+ *    1.2.2rc1                12    10202  12.so.0.1.2.2rc1
+ *    1.0.13                  10    10013  10.so.0.1.0.13
+ *    1.2.2                   12    10202  12.so.0.1.2.2
+ *    1.2.3rc1-6              12    10203  12.so.0.1.2.3rc1-6
+ *    1.2.3                   12    10203  12.so.0.1.2.3
+ *    1.2.4beta1-3            13    10204  12.so.0.1.2.4beta1-3
+ *    1.0.14rc1               13    10014  10.so.0.1.0.14rc1
+ *    1.2.4rc1                13    10204  12.so.0.1.2.4rc1
+ *    1.0.14                  10    10014  10.so.0.1.0.14
+ *    1.2.4                   13    10204  12.so.0.1.2.4
+ *    1.2.5beta1-2            13    10205  12.so.0.1.2.5beta1-2
+ *    1.0.15rc1-3             10    10015  10.so.0.1.0.15rc1-3
+ *    1.2.5rc1-3              13    10205  12.so.0.1.2.5rc1-3
+ *    1.0.15                  10    10015  10.so.0.1.0.15
+ *    1.2.5                   13    10205  12.so.0.1.2.5
+ *    1.2.6beta1-4            13    10206  12.so.0.1.2.6beta1-4
+ *    1.0.16                  10    10016  10.so.0.1.0.16
+ *    1.2.6                   13    10206  12.so.0.1.2.6
+ *    1.2.7beta1-2            13    10207  12.so.0.1.2.7beta1-2
+ *    1.0.17rc1               10    10017  12.so.0.1.0.17rc1
+ *    1.2.7rc1                13    10207  12.so.0.1.2.7rc1
+ *    1.0.17                  10    10017  12.so.0.1.0.17
+ *    1.2.7                   13    10207  12.so.0.1.2.7
+ *    1.2.8beta1-5            13    10208  12.so.0.1.2.8beta1-5
+ *    1.0.18rc1-5             10    10018  12.so.0.1.0.18rc1-5
+ *    1.2.8rc1-5              13    10208  12.so.0.1.2.8rc1-5
+ *    1.0.18                  10    10018  12.so.0.1.0.18
+ *    1.2.8                   13    10208  12.so.0.1.2.8
+ *
+ *    Henceforth the source version will match the shared-library major
+ *    and minor numbers; the shared-library major version number will be
+ *    used for changes in backward compatibility, as it is intended.  The
+ *    PNG_LIBPNG_VER macro, which is not used within libpng but is available
+ *    for applications, is an unsigned integer of the form xyyzz corresponding
+ *    to the source version x.y.z (leading zeros in y and z).  Beta versions
+ *    were given the previous public release number plus a letter, until
+ *    version 1.0.6j; from then on they were given the upcoming public
+ *    release number plus "betaNN" or "rcN".
+ *
+ *    Binary incompatibility exists only when applications make direct access
+ *    to the info_ptr or png_ptr members through png.h, and the compiled
+ *    application is loaded with a different version of the library.
+ *
+ *    DLLNUM will change each time there are forward or backward changes
+ *    in binary compatibility (e.g., when a new feature is added).
+ *
+ * See libpng.txt or libpng.3 for more information.  The PNG specification
+ * is available as a W3C Recommendation and as an ISO Specification,
+ * <http://www.w3.org/TR/2003/REC-PNG-20031110/
+ */
+
+/*
+ * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
+ *
+ * If you modify libpng you may insert additional notices immediately following
+ * this sentence.
+ *
+ * libpng versions 1.2.6, August 15, 2004, through 1.2.8, December 3, 2004, are
+ * Copyright (c) 2004 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.2.5
+ * with the following individual added to the list of Contributing Authors:
+ *
+ *    Cosmin Truta
+ *
+ * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
+ * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-1.0.6
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Simon-Pierre Cadieux
+ *    Eric S. Raymond
+ *    Gilles Vollant
+ *
+ * and with the following additions to the disclaimer:
+ *
+ *    There is no warranty against interference with your enjoyment of the
+ *    library or against infringement.  There is no warranty that our
+ *    efforts or the library will fulfill any of your particular purposes
+ *    or needs.  This library is provided with all faults, and the entire
+ *    risk of satisfactory quality, performance, accuracy, and effort is with
+ *    the user.
+ *
+ * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+ * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
+ * distributed according to the same disclaimer and license as libpng-0.96,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    Tom Lane
+ *    Glenn Randers-Pehrson
+ *    Willem van Schaik
+ *
+ * libpng versions 0.89, June 1996, through 0.96, May 1997, are
+ * Copyright (c) 1996, 1997 Andreas Dilger
+ * Distributed according to the same disclaimer and license as libpng-0.88,
+ * with the following individuals added to the list of Contributing Authors:
+ *
+ *    John Bowler
+ *    Kevin Bracey
+ *    Sam Bushell
+ *    Magnus Holmgren
+ *    Greg Roelofs
+ *    Tom Tanner
+ *
+ * libpng versions 0.5, May 1995, through 0.88, January 1996, are
+ * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+ *
+ * For the purposes of this copyright and license, "Contributing Authors"
+ * is defined as the following set of individuals:
+ *
+ *    Andreas Dilger
+ *    Dave Martindale
+ *    Guy Eric Schalnat
+ *    Paul Schmidt
+ *    Tim Wegner
+ *
+ * The PNG Reference Library is supplied "AS IS".  The Contributing Authors
+ * and Group 42, Inc. disclaim all warranties, expressed or implied,
+ * including, without limitation, the warranties of merchantability and of
+ * fitness for any purpose.  The Contributing Authors and Group 42, Inc.
+ * assume no liability for direct, indirect, incidental, special, exemplary,
+ * or consequential damages, which may result from the use of the PNG
+ * Reference Library, even if advised of the possibility of such damage.
+ *
+ * Permission is hereby granted to use, copy, modify, and distribute this
+ * source code, or portions hereof, for any purpose, without fee, subject
+ * to the following restrictions:
+ *
+ * 1. The origin of this source code must not be misrepresented.
+ *
+ * 2. Altered versions must be plainly marked as such and
+ * must not be misrepresented as being the original source.
+ *
+ * 3. This Copyright notice may not be removed or altered from
+ *    any source or altered source distribution.
+ *
+ * The Contributing Authors and Group 42, Inc. specifically permit, without
+ * fee, and encourage the use of this source code as a component to
+ * supporting the PNG file format in commercial products.  If you use this
+ * source code in a product, acknowledgment is not required but would be
+ * appreciated.
+ */
+
+/*
+ * A "png_get_copyright" function is available, for convenient use in "about"
+ * boxes and the like:
+ *
+ * printf("%s",png_get_copyright(NULL));
+ *
+ * Also, the PNG logo (in PNG format, of course) is supplied in the
+ * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
+ */
+
+/*
+ * Libpng is OSI Certified Open Source Software.  OSI Certified is a
+ * certification mark of the Open Source Initiative.
+ */
+
+/*
+ * The contributing authors would like to thank all those who helped
+ * with testing, bug fixes, and patience.  This wouldn't have been
+ * possible without all of you.
+ *
+ * Thanks to Frank J. T. Wojcik for helping with the documentation.
+ */
+
+/*
+ * Y2K compliance in libpng:
+ * =========================
+ *
+ *    December 3, 2004
+ *
+ *    Since the PNG Development group is an ad-hoc body, we can't make
+ *    an official declaration.
+ *
+ *    This is your unofficial assurance that libpng from version 0.71 and
+ *    upward through 1.2.8 are Y2K compliant.  It is my belief that earlier
+ *    versions were also Y2K compliant.
+ *
+ *    Libpng only has three year fields.  One is a 2-byte unsigned integer
+ *    that will hold years up to 65535.  The other two hold the date in text
+ *    format, and will hold years up to 9999.
+ *
+ *    The integer is
+ *        "png_uint_16 year" in png_time_struct.
+ *
+ *    The strings are
+ *        "png_charp time_buffer" in png_struct and
+ *        "near_time_buffer", which is a local character string in png.c.
+ *
+ *    There are seven time-related functions:
+ *        png.c: png_convert_to_rfc_1123() in png.c
+ *          (formerly png_convert_to_rfc_1152() in error)
+ *        png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
+ *        png_convert_from_time_t() in pngwrite.c
+ *        png_get_tIME() in pngget.c
+ *        png_handle_tIME() in pngrutil.c, called in pngread.c
+ *        png_set_tIME() in pngset.c
+ *        png_write_tIME() in pngwutil.c, called in pngwrite.c
+ *
+ *    All handle dates properly in a Y2K environment.  The
+ *    png_convert_from_time_t() function calls gmtime() to convert from system
+ *    clock time, which returns (year - 1900), which we properly convert to
+ *    the full 4-digit year.  There is a possibility that applications using
+ *    libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
+ *    function, or that they are incorrectly passing only a 2-digit year
+ *    instead of "year - 1900" into the png_convert_from_struct_tm() function,
+ *    but this is not under our control.  The libpng documentation has always
+ *    stated that it works with 4-digit years, and the APIs have been
+ *    documented as such.
+ *
+ *    The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
+ *    integer to hold the year, and can hold years as large as 65535.
+ *
+ *    zlib, upon which libpng depends, is also Y2K compliant.  It contains
+ *    no date-related code.
+ *
+ *       Glenn Randers-Pehrson
+ *       libpng maintainer
+ *       PNG Development Group
+ */
+
+#ifndef PNG_H
+#define PNG_H
+
+/* This is not the place to learn how to use libpng.  The file libpng.txt
+ * describes how to use libpng, and the file example.c summarizes it
+ * with some code on which to build.  This file is useful for looking
+ * at the actual function definitions and structure components.
+ */
+
+/* Version information for png.h - this should match the version in png.c */
+#define PNG_LIBPNG_VER_STRING "1.2.8"
+#define PNG_HEADER_VERSION_STRING \
+   " libpng version 1.2.8 - December 3, 2004 (header)\n"
+
+#define PNG_LIBPNG_VER_SONUM   0
+#define PNG_LIBPNG_VER_DLLNUM  13
+
+/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
+#define PNG_LIBPNG_VER_MAJOR   1
+#define PNG_LIBPNG_VER_MINOR   2
+#define PNG_LIBPNG_VER_RELEASE 8
+/* This should match the numeric part of the final component of
+ * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
+
+#define PNG_LIBPNG_VER_BUILD  0
+
+/* Release Status */
+#define PNG_LIBPNG_BUILD_ALPHA    1
+#define PNG_LIBPNG_BUILD_BETA     2
+#define PNG_LIBPNG_BUILD_RC       3
+#define PNG_LIBPNG_BUILD_STABLE   4
+#define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
+  
+/* Release-Specific Flags */
+#define PNG_LIBPNG_BUILD_PATCH    8 /* Can be OR'ed with
+                                       PNG_LIBPNG_BUILD_STABLE only */
+#define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_SPECIAL */
+#define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
+                                       PNG_LIBPNG_BUILD_PRIVATE */
+
+#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
+
+/* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
+ * We must not include leading zeros.
+ * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
+ * version 1.0.0 was mis-numbered 100 instead of 10000).  From
+ * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release */
+#define PNG_LIBPNG_VER 10208 /* 1.2.8 */
+
+#ifndef PNG_VERSION_INFO_ONLY
+/* include the compression library's header */
+#include "zlib.h"
+#endif
+
+/* include all user configurable info, including optional assembler routines */
+#include "pngconf.h"
+
+/*
+ * Added at libpng-1.2.8 */
+/* Ref MSDN: Private as priority over Special
+ * VS_FF_PRIVATEBUILD File *was not* built using standard release
+ * procedures. If this value is given, the StringFileInfo block must
+ * contain a PrivateBuild string. 
+ *
+ * VS_FF_SPECIALBUILD File *was* built by the original company using
+ * standard release procedures but is a variation of the standard
+ * file of the same version number. If this value is given, the
+ * StringFileInfo block must contain a SpecialBuild string. 
+ */
+
+#if defined(PNG_USER_PRIVATEBUILD)
+#  define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE | \
+          PNG_LIBPNG_BUILD_PRIVATE
+#else
+#  if defined(PNG_LIBPNG_SPECIALBUILD)
+#    define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE | \
+            PNG_LIBPNG_BUILD_SPECIAL
+#  else
+#    define PNG_LIBPNG_BUILD_TYPE PNG_LIBPNG_BUILD_BASE_TYPE
+#  endif
+#endif
+
+#ifndef PNG_VERSION_INFO_ONLY
+
+/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* This file is arranged in several sections.  The first section contains
+ * structure and type definitions.  The second section contains the external
+ * library functions, while the third has the internal library functions,
+ * which applications aren't expected to use directly.
+ */
+
+#ifndef PNG_NO_TYPECAST_NULL
+#define int_p_NULL                (int *)NULL
+#define png_bytep_NULL            (png_bytep)NULL
+#define png_bytepp_NULL           (png_bytepp)NULL
+#define png_doublep_NULL          (png_doublep)NULL
+#define png_error_ptr_NULL        (png_error_ptr)NULL
+#define png_flush_ptr_NULL        (png_flush_ptr)NULL
+#define png_free_ptr_NULL         (png_free_ptr)NULL
+#define png_infopp_NULL           (png_infopp)NULL
+#define png_malloc_ptr_NULL       (png_malloc_ptr)NULL
+#define png_read_status_ptr_NULL  (png_read_status_ptr)NULL
+#define png_rw_ptr_NULL           (png_rw_ptr)NULL
+#define png_structp_NULL          (png_structp)NULL
+#define png_uint_16p_NULL         (png_uint_16p)NULL
+#define png_voidp_NULL            (png_voidp)NULL
+#define png_write_status_ptr_NULL (png_write_status_ptr)NULL
+#else
+#define int_p_NULL                NULL
+#define png_bytep_NULL            NULL
+#define png_bytepp_NULL           NULL
+#define png_doublep_NULL          NULL
+#define png_error_ptr_NULL        NULL
+#define png_flush_ptr_NULL        NULL
+#define png_free_ptr_NULL         NULL
+#define png_infopp_NULL           NULL
+#define png_malloc_ptr_NULL       NULL
+#define png_read_status_ptr_NULL  NULL
+#define png_rw_ptr_NULL           NULL
+#define png_structp_NULL          NULL
+#define png_uint_16p_NULL         NULL
+#define png_voidp_NULL            NULL
+#define png_write_status_ptr_NULL NULL
+#endif
+
+/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
+#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
+/* Version information for C files, stored in png.c.  This had better match
+ * the version above.
+ */
+#ifdef PNG_USE_GLOBAL_ARRAYS
+PNG_EXPORT_VAR (const char) png_libpng_ver[18];
+  /* need room for 99.99.99beta99z */
+#else
+#define png_libpng_ver png_get_header_ver(NULL)
+#endif
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+/* This was removed in version 1.0.5c */
+/* Structures to facilitate easy interlacing.  See png.c for more details */
+PNG_EXPORT_VAR (const int FARDATA) png_pass_start[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_inc[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_ystart[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_yinc[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_mask[7];
+PNG_EXPORT_VAR (const int FARDATA) png_pass_dsp_mask[7];
+#ifdef PNG_HAVE_ASSEMBLER_COMBINE_ROW
+PNG_EXPORT_VAR (const int FARDATA) png_pass_width[7];
+#endif
+/* This isn't currently used.  If you need it, see png.c for more details.
+PNG_EXPORT_VAR (const int FARDATA) png_pass_height[7];
+*/
+#endif
+
+#endif /* PNG_NO_EXTERN */
+
+/* Three color definitions.  The order of the red, green, and blue, (and the
+ * exact size) is not important, although the size of the fields need to
+ * be png_byte or png_uint_16 (as defined below).
+ */
+typedef struct png_color_struct
+{
+   png_byte red;
+   png_byte green;
+   png_byte blue;
+} png_color;
+typedef png_color FAR * png_colorp;
+typedef png_color FAR * FAR * png_colorpp;
+
+typedef struct png_color_16_struct
+{
+   png_byte index;    /* used for palette files */
+   png_uint_16 red;   /* for use in red green blue files */
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 gray;  /* for use in grayscale files */
+} png_color_16;
+typedef png_color_16 FAR * png_color_16p;
+typedef png_color_16 FAR * FAR * png_color_16pp;
+
+typedef struct png_color_8_struct
+{
+   png_byte red;   /* for use in red green blue files */
+   png_byte green;
+   png_byte blue;
+   png_byte gray;  /* for use in grayscale files */
+   png_byte alpha; /* for alpha channel files */
+} png_color_8;
+typedef png_color_8 FAR * png_color_8p;
+typedef png_color_8 FAR * FAR * png_color_8pp;
+
+/*
+ * The following two structures are used for the in-core representation
+ * of sPLT chunks.
+ */
+typedef struct png_sPLT_entry_struct
+{
+   png_uint_16 red;
+   png_uint_16 green;
+   png_uint_16 blue;
+   png_uint_16 alpha;
+   png_uint_16 frequency;
+} png_sPLT_entry;
+typedef png_sPLT_entry FAR * png_sPLT_entryp;
+typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
+
+/*  When the depth of the sPLT palette is 8 bits, the color and alpha samples
+ *  occupy the LSB of their respective members, and the MSB of each member
+ *  is zero-filled.  The frequency member always occupies the full 16 bits.
+ */
+
+typedef struct png_sPLT_struct
+{
+   png_charp name;           /* palette name */
+   png_byte depth;           /* depth of palette samples */
+   png_sPLT_entryp entries;  /* palette entries */
+   png_int_32 nentries;      /* number of palette entries */
+} png_sPLT_t;
+typedef png_sPLT_t FAR * png_sPLT_tp;
+typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
+
+#ifdef PNG_TEXT_SUPPORTED
+/* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
+ * and whether that contents is compressed or not.  The "key" field
+ * points to a regular zero-terminated C string.  The "text", "lang", and
+ * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
+ * However, the * structure returned by png_get_text() will always contain
+ * regular zero-terminated C strings (possibly empty), never NULL pointers,
+ * so they can be safely used in printf() and other string-handling functions.
+ */
+typedef struct png_text_struct
+{
+   int  compression;       /* compression value:
+                             -1: tEXt, none
+                              0: zTXt, deflate
+                              1: iTXt, none
+                              2: iTXt, deflate  */
+   png_charp key;          /* keyword, 1-79 character description of "text" */
+   png_charp text;         /* comment, may be an empty string (ie "")
+                              or a NULL pointer */
+   png_size_t text_length; /* length of the text string */
+#ifdef PNG_iTXt_SUPPORTED
+   png_size_t itxt_length; /* length of the itxt string */
+   png_charp lang;         /* language code, 0-79 characters
+                              or a NULL pointer */
+   png_charp lang_key;     /* keyword translated UTF-8 string, 0 or more
+                              chars or a NULL pointer */
+#endif
+} png_text;
+typedef png_text FAR * png_textp;
+typedef png_text FAR * FAR * png_textpp;
+#endif
+
+/* Supported compression types for text in PNG files (tEXt, and zTXt).
+ * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
+#define PNG_TEXT_COMPRESSION_NONE_WR -3
+#define PNG_TEXT_COMPRESSION_zTXt_WR -2
+#define PNG_TEXT_COMPRESSION_NONE    -1
+#define PNG_TEXT_COMPRESSION_zTXt     0
+#define PNG_ITXT_COMPRESSION_NONE     1
+#define PNG_ITXT_COMPRESSION_zTXt     2
+#define PNG_TEXT_COMPRESSION_LAST     3  /* Not a valid value */
+
+/* png_time is a way to hold the time in an machine independent way.
+ * Two conversions are provided, both from time_t and struct tm.  There
+ * is no portable way to convert to either of these structures, as far
+ * as I know.  If you know of a portable way, send it to me.  As a side
+ * note - PNG has always been Year 2000 compliant!
+ */
+typedef struct png_time_struct
+{
+   png_uint_16 year; /* full year, as in, 1995 */
+   png_byte month;   /* month of year, 1 - 12 */
+   png_byte day;     /* day of month, 1 - 31 */
+   png_byte hour;    /* hour of day, 0 - 23 */
+   png_byte minute;  /* minute of hour, 0 - 59 */
+   png_byte second;  /* second of minute, 0 - 60 (for leap seconds) */
+} png_time;
+typedef png_time FAR * png_timep;
+typedef png_time FAR * FAR * png_timepp;
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+/* png_unknown_chunk is a structure to hold queued chunks for which there is
+ * no specific support.  The idea is that we can use this to queue
+ * up private chunks for output even though the library doesn't actually
+ * know about their semantics.
+ */
+typedef struct png_unknown_chunk_t
+{
+    png_byte name[5];
+    png_byte *data;
+    png_size_t size;
+
+    /* libpng-using applications should NOT directly modify this byte. */
+    png_byte location; /* mode of operation at read time */
+}
+png_unknown_chunk;
+typedef png_unknown_chunk FAR * png_unknown_chunkp;
+typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
+#endif
+
+/* png_info is a structure that holds the information in a PNG file so
+ * that the application can find out the characteristics of the image.
+ * If you are reading the file, this structure will tell you what is
+ * in the PNG file.  If you are writing the file, fill in the information
+ * you want to put into the PNG file, then call png_write_info().
+ * The names chosen should be very close to the PNG specification, so
+ * consult that document for information about the meaning of each field.
+ *
+ * With libpng < 0.95, it was only possible to directly set and read the
+ * the values in the png_info_struct, which meant that the contents and
+ * order of the values had to remain fixed.  With libpng 0.95 and later,
+ * however, there are now functions that abstract the contents of
+ * png_info_struct from the application, so this makes it easier to use
+ * libpng with dynamic libraries, and even makes it possible to use
+ * libraries that don't have all of the libpng ancillary chunk-handing
+ * functionality.
+ *
+ * In any case, the order of the parameters in png_info_struct should NOT
+ * be changed for as long as possible to keep compatibility with applications
+ * that use the old direct-access method with png_info_struct.
+ *
+ * The following members may have allocated storage attached that should be
+ * cleaned up before the structure is discarded: palette, trans, text,
+ * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
+ * splt_palettes, scal_unit, row_pointers, and unknowns.   By default, these
+ * are automatically freed when the info structure is deallocated, if they were
+ * allocated internally by libpng.  This behavior can be changed by means
+ * of the png_data_freer() function.
+ *
+ * More allocation details: all the chunk-reading functions that
+ * change these members go through the corresponding png_set_*
+ * functions.  A function to clear these members is available: see
+ * png_free_data().  The png_set_* functions do not depend on being
+ * able to point info structure members to any of the storage they are
+ * passed (they make their own copies), EXCEPT that the png_set_text
+ * functions use the same storage passed to them in the text_ptr or
+ * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
+ * functions do not make their own copies.
+ */
+typedef struct png_info_struct
+{
+   /* the following are necessary for every PNG file */
+   png_uint_32 width;       /* width of image in pixels (from IHDR) */
+   png_uint_32 height;      /* height of image in pixels (from IHDR) */
+   png_uint_32 valid;       /* valid chunk data (see PNG_INFO_ below) */
+   png_uint_32 rowbytes;    /* bytes needed to hold an untransformed row */
+   png_colorp palette;      /* array of color values (valid & PNG_INFO_PLTE) */
+   png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
+   png_uint_16 num_trans;   /* number of transparent palette color (tRNS) */
+   png_byte bit_depth;      /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
+   png_byte color_type;     /* see PNG_COLOR_TYPE_ below (from IHDR) */
+   /* The following three should have been named *_method not *_type */
+   png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
+   png_byte filter_type;    /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
+   png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+
+   /* The following is informational only on read, and not used on writes. */
+   png_byte channels;       /* number of data channels per pixel (1, 2, 3, 4) */
+   png_byte pixel_depth;    /* number of bits per pixel */
+   png_byte spare_byte;     /* to align the data, and for future use */
+   png_byte signature[8];   /* magic bytes read by libpng from start of file */
+
+   /* The rest of the data is optional.  If you are reading, check the
+    * valid field to see if the information in these are valid.  If you
+    * are writing, set the valid field to those chunks you want written,
+    * and initialize the appropriate fields below.
+    */
+
+#if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
+   /* The gAMA chunk describes the gamma characteristics of the system
+    * on which the image was created, normally in the range [1.0, 2.5].
+    * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
+    */
+   float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+    /* GR-P, 0.96a */
+    /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
+   png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)
+   /* The tEXt, and zTXt chunks contain human-readable textual data in
+    * uncompressed, compressed, and optionally compressed forms, respectively.
+    * The data in "text" is an array of pointers to uncompressed,
+    * null-terminated C strings. Each chunk has a keyword that describes the
+    * textual data contained in that chunk.  Keywords are not required to be
+    * unique, and the text string may be empty.  Any number of text chunks may
+    * be in an image.
+    */
+   int num_text; /* number of comments read/to write */
+   int max_text; /* current size of text array */
+   png_textp text; /* array of comments read/to write */
+#endif /* PNG_TEXT_SUPPORTED */
+
+#if defined(PNG_tIME_SUPPORTED)
+   /* The tIME chunk holds the last time the displayed image data was
+    * modified.  See the png_time struct for the contents of this struct.
+    */
+   png_time mod_time;
+#endif
+
+#if defined(PNG_sBIT_SUPPORTED)
+   /* The sBIT chunk specifies the number of significant high-order bits
+    * in the pixel data.  Values are in the range [1, bit_depth], and are
+    * only specified for the channels in the pixel data.  The contents of
+    * the low-order bits is not specified.  Data is valid if
+    * (valid & PNG_INFO_sBIT) is non-zero.
+    */
+   png_color_8 sig_bit; /* significant bits in color channels */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
+defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The tRNS chunk supplies transparency data for paletted images and
+    * other image types that don't need a full alpha channel.  There are
+    * "num_trans" transparency values for a paletted image, stored in the
+    * same order as the palette colors, starting from index 0.  Values
+    * for the data are in the range [0, 255], ranging from fully transparent
+    * to fully opaque, respectively.  For non-paletted images, there is a
+    * single color specified that should be treated as fully transparent.
+    * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
+    */
+   png_bytep trans; /* transparent values for paletted image */
+   png_color_16 trans_values; /* transparent color for non-palette image */
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   /* The bKGD chunk gives the suggested image background color if the
+    * display program does not have its own background color and the image
+    * is needs to composited onto a background before display.  The colors
+    * in "background" are normally in the same color space/depth as the
+    * pixel data.  Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
+    */
+   png_color_16 background;
+#endif
+
+#if defined(PNG_oFFs_SUPPORTED)
+   /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
+    * and downwards from the top-left corner of the display, page, or other
+    * application-specific co-ordinate space.  See the PNG_OFFSET_ defines
+    * below for the unit types.  Valid if (valid & PNG_INFO_oFFs) non-zero.
+    */
+   png_int_32 x_offset; /* x offset on page */
+   png_int_32 y_offset; /* y offset on page */
+   png_byte offset_unit_type; /* offset units type */
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+   /* The pHYs chunk gives the physical pixel density of the image for
+    * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
+    * defines below).  Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
+    */
+   png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
+   png_uint_32 y_pixels_per_unit; /* vertical pixel density */
+   png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+   /* The hIST chunk contains the relative frequency or importance of the
+    * various palette entries, so that a viewer can intelligently select a
+    * reduced-color palette, if required.  Data is an array of "num_palette"
+    * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
+    * is non-zero.
+    */
+   png_uint_16p hist;
+#endif
+
+#ifdef PNG_cHRM_SUPPORTED
+   /* The cHRM chunk describes the CIE color characteristics of the monitor
+    * on which the PNG was created.  This data allows the viewer to do gamut
+    * mapping of the input image to ensure that the viewer sees the same
+    * colors in the image as the creator.  Values are in the range
+    * [0.0, 0.8].  Data valid if (valid & PNG_INFO_cHRM) non-zero.
+    */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   float x_white;
+   float y_white;
+   float x_red;
+   float y_red;
+   float x_green;
+   float y_green;
+   float x_blue;
+   float y_blue;
+#endif
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+   /* The pCAL chunk describes a transformation between the stored pixel
+    * values and original physical data values used to create the image.
+    * The integer range [0, 2^bit_depth - 1] maps to the floating-point
+    * range given by [pcal_X0, pcal_X1], and are further transformed by a
+    * (possibly non-linear) transformation function given by "pcal_type"
+    * and "pcal_params" into "pcal_units".  Please see the PNG_EQUATION_
+    * defines below, and the PNG-Group's PNG extensions document for a
+    * complete description of the transformations and how they should be
+    * implemented, and for a description of the ASCII parameter strings.
+    * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
+    */
+   png_charp pcal_purpose;  /* pCAL chunk description string */
+   png_int_32 pcal_X0;      /* minimum value */
+   png_int_32 pcal_X1;      /* maximum value */
+   png_charp pcal_units;    /* Latin-1 string giving physical units */
+   png_charpp pcal_params;  /* ASCII strings containing parameter values */
+   png_byte pcal_type;      /* equation type (see PNG_EQUATION_ below) */
+   png_byte pcal_nparams;   /* number of parameters given in pcal_params */
+#endif
+
+/* New members added in libpng-1.0.6 */
+#ifdef PNG_FREE_ME_SUPPORTED
+   png_uint_32 free_me;     /* flags items libpng is responsible for freeing */
+#endif
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+   /* storage for unknown chunks that the library doesn't recognize. */
+   png_unknown_chunkp unknown_chunks;
+   png_size_t unknown_chunks_num;
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+   /* iCCP chunk data. */
+   png_charp iccp_name;     /* profile name */
+   png_charp iccp_profile;  /* International Color Consortium profile data */
+                            /* Note to maintainer: should be png_bytep */
+   png_uint_32 iccp_proflen;  /* ICC profile data length */
+   png_byte iccp_compression; /* Always zero */
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+   /* data on sPLT chunks (there may be more than one). */
+   png_sPLT_tp splt_palettes;
+   png_uint_32 splt_palettes_num;
+#endif
+
+#if defined(PNG_sCAL_SUPPORTED)
+   /* The sCAL chunk describes the actual physical dimensions of the
+    * subject matter of the graphic.  The chunk contains a unit specification
+    * a byte value, and two ASCII strings representing floating-point
+    * values.  The values are width and height corresponsing to one pixel
+    * in the image.  This external representation is converted to double
+    * here.  Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
+    */
+   png_byte scal_unit;         /* unit of physical scale */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   double scal_pixel_width;    /* width of one pixel */
+   double scal_pixel_height;   /* height of one pixel */
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+   png_charp scal_s_width;     /* string containing height */
+   png_charp scal_s_height;    /* string containing width */
+#endif
+#endif
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+   /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
+   /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
+   png_bytepp row_pointers;        /* the image bits */
+#endif
+
+#if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
+   png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
+   png_fixed_point int_x_white;
+   png_fixed_point int_y_white;
+   png_fixed_point int_x_red;
+   png_fixed_point int_y_red;
+   png_fixed_point int_x_green;
+   png_fixed_point int_y_green;
+   png_fixed_point int_x_blue;
+   png_fixed_point int_y_blue;
+#endif
+
+} png_info;
+
+typedef png_info FAR * png_infop;
+typedef png_info FAR * FAR * png_infopp;
+
+/* Maximum positive integer used in PNG is (2^31)-1 */
+#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
+#define PNG_UINT_32_MAX ((png_uint_32)(-1))
+#define PNG_SIZE_MAX ((png_size_t)(-1))
+/* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
+#define PNG_MAX_UINT PNG_UINT_31_MAX
+
+/* These describe the color_type field in png_info. */
+/* color type masks */
+#define PNG_COLOR_MASK_PALETTE    1
+#define PNG_COLOR_MASK_COLOR      2
+#define PNG_COLOR_MASK_ALPHA      4
+
+/* color types.  Note that not all combinations are legal */
+#define PNG_COLOR_TYPE_GRAY 0
+#define PNG_COLOR_TYPE_PALETTE  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
+#define PNG_COLOR_TYPE_RGB        (PNG_COLOR_MASK_COLOR)
+#define PNG_COLOR_TYPE_RGB_ALPHA  (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
+#define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
+/* aliases */
+#define PNG_COLOR_TYPE_RGBA  PNG_COLOR_TYPE_RGB_ALPHA
+#define PNG_COLOR_TYPE_GA  PNG_COLOR_TYPE_GRAY_ALPHA
+
+/* This is for compression type. PNG 1.0-1.2 only define the single type. */
+#define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
+#define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
+
+/* This is for filter type. PNG 1.0-1.2 only define the single type. */
+#define PNG_FILTER_TYPE_BASE      0 /* Single row per-byte filtering */
+#define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
+#define PNG_FILTER_TYPE_DEFAULT   PNG_FILTER_TYPE_BASE
+
+/* These are for the interlacing type.  These values should NOT be changed. */
+#define PNG_INTERLACE_NONE        0 /* Non-interlaced image */
+#define PNG_INTERLACE_ADAM7       1 /* Adam7 interlacing */
+#define PNG_INTERLACE_LAST        2 /* Not a valid value */
+
+/* These are for the oFFs chunk.  These values should NOT be changed. */
+#define PNG_OFFSET_PIXEL          0 /* Offset in pixels */
+#define PNG_OFFSET_MICROMETER     1 /* Offset in micrometers (1/10^6 meter) */
+#define PNG_OFFSET_LAST           2 /* Not a valid value */
+
+/* These are for the pCAL chunk.  These values should NOT be changed. */
+#define PNG_EQUATION_LINEAR       0 /* Linear transformation */
+#define PNG_EQUATION_BASE_E       1 /* Exponential base e transform */
+#define PNG_EQUATION_ARBITRARY    2 /* Arbitrary base exponential transform */
+#define PNG_EQUATION_HYPERBOLIC   3 /* Hyperbolic sine transformation */
+#define PNG_EQUATION_LAST         4 /* Not a valid value */
+
+/* These are for the sCAL chunk.  These values should NOT be changed. */
+#define PNG_SCALE_UNKNOWN         0 /* unknown unit (image scale) */
+#define PNG_SCALE_METER           1 /* meters per pixel */
+#define PNG_SCALE_RADIAN          2 /* radians per pixel */
+#define PNG_SCALE_LAST            3 /* Not a valid value */
+
+/* These are for the pHYs chunk.  These values should NOT be changed. */
+#define PNG_RESOLUTION_UNKNOWN    0 /* pixels/unknown unit (aspect ratio) */
+#define PNG_RESOLUTION_METER      1 /* pixels/meter */
+#define PNG_RESOLUTION_LAST       2 /* Not a valid value */
+
+/* These are for the sRGB chunk.  These values should NOT be changed. */
+#define PNG_sRGB_INTENT_PERCEPTUAL 0
+#define PNG_sRGB_INTENT_RELATIVE   1
+#define PNG_sRGB_INTENT_SATURATION 2
+#define PNG_sRGB_INTENT_ABSOLUTE   3
+#define PNG_sRGB_INTENT_LAST       4 /* Not a valid value */
+
+/* This is for text chunks */
+#define PNG_KEYWORD_MAX_LENGTH     79
+
+/* Maximum number of entries in PLTE/sPLT/tRNS arrays */
+#define PNG_MAX_PALETTE_LENGTH    256
+
+/* These determine if an ancillary chunk's data has been successfully read
+ * from the PNG header, or if the application has filled in the corresponding
+ * data in the info_struct to be written into the output file.  The values
+ * of the PNG_INFO_<chunk> defines should NOT be changed.
+ */
+#define PNG_INFO_gAMA 0x0001
+#define PNG_INFO_sBIT 0x0002
+#define PNG_INFO_cHRM 0x0004
+#define PNG_INFO_PLTE 0x0008
+#define PNG_INFO_tRNS 0x0010
+#define PNG_INFO_bKGD 0x0020
+#define PNG_INFO_hIST 0x0040
+#define PNG_INFO_pHYs 0x0080
+#define PNG_INFO_oFFs 0x0100
+#define PNG_INFO_tIME 0x0200
+#define PNG_INFO_pCAL 0x0400
+#define PNG_INFO_sRGB 0x0800   /* GR-P, 0.96a */
+#define PNG_INFO_iCCP 0x1000   /* ESR, 1.0.6 */
+#define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
+#define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
+#define PNG_INFO_IDAT 0x8000L  /* ESR, 1.0.6 */
+
+/* This is used for the transformation routines, as some of them
+ * change these values for the row.  It also should enable using
+ * the routines for other purposes.
+ */
+typedef struct png_row_info_struct
+{
+   png_uint_32 width; /* width of row */
+   png_uint_32 rowbytes; /* number of bytes in row */
+   png_byte color_type; /* color type of row */
+   png_byte bit_depth; /* bit depth of row */
+   png_byte channels; /* number of channels (1, 2, 3, or 4) */
+   png_byte pixel_depth; /* bits per pixel (depth * channels) */
+} png_row_info;
+
+typedef png_row_info FAR * png_row_infop;
+typedef png_row_info FAR * FAR * png_row_infopp;
+
+/* These are the function types for the I/O functions and for the functions
+ * that allow the user to override the default I/O functions with his or her
+ * own.  The png_error_ptr type should match that of user-supplied warning
+ * and error functions, while the png_rw_ptr type should match that of the
+ * user read/write data functions.
+ */
+typedef struct png_struct_def png_struct;
+typedef png_struct FAR * png_structp;
+
+typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
+typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
+typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
+typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
+   int));
+typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
+   int));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
+typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
+typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
+   png_uint_32, int));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
+    png_row_infop, png_bytep));
+#endif
+
+#if defined(PNG_USER_CHUNKS_SUPPORTED)
+typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
+#endif
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
+#endif
+
+/* Transform masks for the high-level interface */
+#define PNG_TRANSFORM_IDENTITY       0x0000    /* read and write */
+#define PNG_TRANSFORM_STRIP_16       0x0001    /* read only */
+#define PNG_TRANSFORM_STRIP_ALPHA    0x0002    /* read only */
+#define PNG_TRANSFORM_PACKING        0x0004    /* read and write */
+#define PNG_TRANSFORM_PACKSWAP       0x0008    /* read and write */
+#define PNG_TRANSFORM_EXPAND         0x0010    /* read only */
+#define PNG_TRANSFORM_INVERT_MONO    0x0020    /* read and write */
+#define PNG_TRANSFORM_SHIFT          0x0040    /* read and write */
+#define PNG_TRANSFORM_BGR            0x0080    /* read and write */
+#define PNG_TRANSFORM_SWAP_ALPHA     0x0100    /* read and write */
+#define PNG_TRANSFORM_SWAP_ENDIAN    0x0200    /* read and write */
+#define PNG_TRANSFORM_INVERT_ALPHA   0x0400    /* read and write */
+#define PNG_TRANSFORM_STRIP_FILLER   0x0800    /* WRITE only */
+
+/* Flags for MNG supported features */
+#define PNG_FLAG_MNG_EMPTY_PLTE     0x01
+#define PNG_FLAG_MNG_FILTER_64      0x04
+#define PNG_ALL_MNG_FEATURES        0x05
+
+typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
+typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
+
+/* The structure that holds the information to read and write PNG files.
+ * The only people who need to care about what is inside of this are the
+ * people who will be modifying the library for their own special needs.
+ * It should NOT be accessed directly by an application, except to store
+ * the jmp_buf.
+ */
+
+struct png_struct_def
+{
+#ifdef PNG_SETJMP_SUPPORTED
+   jmp_buf jmpbuf;            /* used in png_error */
+#endif
+   png_error_ptr error_fn;    /* function for printing errors and aborting */
+   png_error_ptr warning_fn;  /* function for printing warnings */
+   png_voidp error_ptr;       /* user supplied struct for error functions */
+   png_rw_ptr write_data_fn;  /* function for writing output data */
+   png_rw_ptr read_data_fn;   /* function for reading input data */
+   png_voidp io_ptr;          /* ptr to application struct for I/O functions */
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
+   png_user_transform_ptr read_user_transform_fn; /* user read transform */
+#endif
+
+#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+   png_user_transform_ptr write_user_transform_fn; /* user write transform */
+#endif
+
+/* These were added in libpng-1.0.2 */
+#if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+   png_voidp user_transform_ptr; /* user supplied struct for user transform */
+   png_byte user_transform_depth;    /* bit depth of user transformed pixels */
+   png_byte user_transform_channels; /* channels in user transformed pixels */
+#endif
+#endif
+
+   png_uint_32 mode;          /* tells us where we are in the PNG file */
+   png_uint_32 flags;         /* flags indicating various things to libpng */
+   png_uint_32 transformations; /* which transformations to perform */
+
+   z_stream zstream;          /* pointer to decompression structure (below) */
+   png_bytep zbuf;            /* buffer for zlib */
+   png_size_t zbuf_size;      /* size of zbuf */
+   int zlib_level;            /* holds zlib compression level */
+   int zlib_method;           /* holds zlib compression method */
+   int zlib_window_bits;      /* holds zlib compression window bits */
+   int zlib_mem_level;        /* holds zlib compression memory level */
+   int zlib_strategy;         /* holds zlib compression strategy */
+
+   png_uint_32 width;         /* width of image in pixels */
+   png_uint_32 height;        /* height of image in pixels */
+   png_uint_32 num_rows;      /* number of rows in current pass */
+   png_uint_32 usr_width;     /* width of row at start of write */
+   png_uint_32 rowbytes;      /* size of row in bytes */
+   png_uint_32 irowbytes;     /* size of current interlaced row in bytes */
+   png_uint_32 iwidth;        /* width of current interlaced row in pixels */
+   png_uint_32 row_number;    /* current row in interlace pass */
+   png_bytep prev_row;        /* buffer to save previous (unfiltered) row */
+   png_bytep row_buf;         /* buffer to save current (unfiltered) row */
+   png_bytep sub_row;         /* buffer to save "sub" row when filtering */
+   png_bytep up_row;          /* buffer to save "up" row when filtering */
+   png_bytep avg_row;         /* buffer to save "avg" row when filtering */
+   png_bytep paeth_row;       /* buffer to save "Paeth" row when filtering */
+   png_row_info row_info;     /* used for transformation routines */
+
+   png_uint_32 idat_size;     /* current IDAT size for read */
+   png_uint_32 crc;           /* current chunk CRC value */
+   png_colorp palette;        /* palette from the input file */
+   png_uint_16 num_palette;   /* number of color entries in palette */
+   png_uint_16 num_trans;     /* number of transparency values */
+   png_byte chunk_name[5];    /* null-terminated name of current chunk */
+   png_byte compression;      /* file compression type (always 0) */
+   png_byte filter;           /* file filter type (always 0) */
+   png_byte interlaced;       /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
+   png_byte pass;             /* current interlace pass (0 - 6) */
+   png_byte do_filter;        /* row filter flags (see PNG_FILTER_ below ) */
+   png_byte color_type;       /* color type of file */
+   png_byte bit_depth;        /* bit depth of file */
+   png_byte usr_bit_depth;    /* bit depth of users row */
+   png_byte pixel_depth;      /* number of bits per pixel */
+   png_byte channels;         /* number of channels in file */
+   png_byte usr_channels;     /* channels at start of write */
+   png_byte sig_bytes;        /* magic bytes read/written from start of file */
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+#ifdef PNG_LEGACY_SUPPORTED
+   png_byte filler;           /* filler byte for pixel expansion */
+#else
+   png_uint_16 filler;           /* filler bytes for pixel expansion */
+#endif
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED)
+   png_byte background_gamma_type;
+#  ifdef PNG_FLOATING_POINT_SUPPORTED
+   float background_gamma;
+#  endif
+   png_color_16 background;   /* background color in screen gamma space */
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+   png_color_16 background_1; /* background normalized to gamma 1.0 */
+#endif
+#endif /* PNG_bKGD_SUPPORTED */
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+   png_flush_ptr output_flush_fn;/* Function for flushing output */
+   png_uint_32 flush_dist;    /* how many rows apart to flush, 0 - no flush */
+   png_uint_32 flush_rows;    /* number of rows written since last flush */
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   int gamma_shift;      /* number of "insignificant" bits 16-bit gamma */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+   float gamma;          /* file gamma value */
+   float screen_gamma;   /* screen gamma value (display_exponent) */
+#endif
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_bytep gamma_table;     /* gamma table for 8-bit depth files */
+   png_bytep gamma_from_1;    /* converts from 1.0 to screen */
+   png_bytep gamma_to_1;      /* converts from file to 1.0 */
+   png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
+   png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
+   png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
+   png_color_8 sig_bit;       /* significant bits in each available channel */
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+   png_color_8 shift;         /* shift for significant bit tranformation */
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
+ || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_bytep trans;           /* transparency values for paletted files */
+   png_color_16 trans_values; /* transparency values for non-paletted files */
+#endif
+
+   png_read_status_ptr read_row_fn;   /* called after each row is decoded */
+   png_write_status_ptr write_row_fn; /* called after each row is encoded */
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+   png_progressive_info_ptr info_fn; /* called after header data fully read */
+   png_progressive_row_ptr row_fn;   /* called after each prog. row is decoded */
+   png_progressive_end_ptr end_fn;   /* called after image is complete */
+   png_bytep save_buffer_ptr;        /* current location in save_buffer */
+   png_bytep save_buffer;            /* buffer for previously read data */
+   png_bytep current_buffer_ptr;     /* current location in current_buffer */
+   png_bytep current_buffer;         /* buffer for recently used data */
+   png_uint_32 push_length;          /* size of current input chunk */
+   png_uint_32 skip_length;          /* bytes to skip in input data */
+   png_size_t save_buffer_size;      /* amount of data now in save_buffer */
+   png_size_t save_buffer_max;       /* total size of save_buffer */
+   png_size_t buffer_size;           /* total amount of available input data */
+   png_size_t current_buffer_size;   /* amount of data now in current_buffer */
+   int process_mode;                 /* what push library is currently doing */
+   int cur_palette;                  /* current push library palette index */
+
+#  if defined(PNG_TEXT_SUPPORTED)
+     png_size_t current_text_size;   /* current size of text input data */
+     png_size_t current_text_left;   /* how much text left to read in input */
+     png_charp current_text;         /* current text chunk buffer */
+     png_charp current_text_ptr;     /* current location in current_text */
+#  endif /* PNG_PROGRESSIVE_READ_SUPPORTED && PNG_TEXT_SUPPORTED */
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
+/* for the Borland special 64K segment handler */
+   png_bytepp offset_table_ptr;
+   png_bytep offset_table;
+   png_uint_16 offset_table_number;
+   png_uint_16 offset_table_count;
+   png_uint_16 offset_table_count_free;
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+   png_bytep palette_lookup;         /* lookup table for dithering */
+   png_bytep dither_index;           /* index translation for palette files */
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
+   png_uint_16p hist;                /* histogram */
+#endif
+
+#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
+   png_byte heuristic_method;        /* heuristic for row filter selection */
+   png_byte num_prev_filters;        /* number of weights for previous rows */
+   png_bytep prev_filters;           /* filter type(s) of previous row(s) */
+   png_uint_16p filter_weights;      /* weight(s) for previous line(s) */
+   png_uint_16p inv_filter_weights;  /* 1/weight(s) for previous line(s) */
+   png_uint_16p filter_costs;        /* relative filter calculation cost */
+   png_uint_16p inv_filter_costs;    /* 1/relative filter calculation cost */
+#endif
+
+#if defined(PNG_TIME_RFC1123_SUPPORTED)
+   png_charp time_buffer;            /* String to hold RFC 1123 time text */
+#endif
+
+/* New members added in libpng-1.0.6 */
+
+#ifdef PNG_FREE_ME_SUPPORTED
+   png_uint_32 free_me;       /* flags items libpng is responsible for freeing */
+#endif
+
+#if defined(PNG_USER_CHUNKS_SUPPORTED)
+   png_voidp user_chunk_ptr;
+   png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
+#endif
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+   int num_chunk_list;
+   png_bytep chunk_list;
+#endif
+
+/* New members added in libpng-1.0.3 */
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+   png_byte rgb_to_gray_status;
+   /* These were changed from png_byte in libpng-1.0.6 */
+   png_uint_16 rgb_to_gray_red_coeff;
+   png_uint_16 rgb_to_gray_green_coeff;
+   png_uint_16 rgb_to_gray_blue_coeff;
+#endif
+
+/* New member added in libpng-1.0.4 (renamed in 1.0.9) */
+#if defined(PNG_MNG_FEATURES_SUPPORTED) || \
+    defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
+    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
+/* changed from png_byte to png_uint_32 at version 1.2.0 */
+#ifdef PNG_1_0_X
+   png_byte mng_features_permitted;
+#else
+   png_uint_32 mng_features_permitted;
+#endif /* PNG_1_0_X */
+#endif
+
+/* New member added in libpng-1.0.7 */
+#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
+   png_fixed_point int_gamma;
+#endif
+
+/* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
+#if defined(PNG_MNG_FEATURES_SUPPORTED)
+   png_byte filter_type;
+#endif
+
+#if defined(PNG_1_0_X) || (defined(PNG_DEBUG) && defined(PNG_USE_PNGGCCRD))
+/* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
+   png_uint_32 row_buf_size;
+#endif
+
+/* New members added in libpng-1.2.0 */
+#if !defined(PNG_1_0_X) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+   png_byte     mmx_bitdepth_threshold;
+   png_uint_32  mmx_rowbytes_threshold;
+   png_uint_32  asm_flags;
+#endif
+
+/* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
+#ifdef PNG_USER_MEM_SUPPORTED
+   png_voidp mem_ptr;                /* user supplied struct for mem functions */
+   png_malloc_ptr malloc_fn;         /* function for allocating memory */
+   png_free_ptr free_fn;             /* function for freeing memory */
+#endif
+
+/* New member added in libpng-1.0.13 and 1.2.0 */
+   png_bytep big_row_buf;         /* buffer to save current (unfiltered) row */
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+/* The following three members were added at version 1.0.14 and 1.2.4 */
+   png_bytep dither_sort;            /* working sort array */
+   png_bytep index_to_palette;       /* where the original index currently is */
+                                     /* in the palette */
+   png_bytep palette_to_index;       /* which original index points to this */
+                                     /* palette color */
+#endif
+
+/* New members added in libpng-1.0.16 and 1.2.6 */
+   png_byte compression_type;
+
+#ifdef PNG_SET_USER_LIMITS_SUPPORTED
+   png_uint_32 user_width_max;
+   png_uint_32 user_height_max;
+#endif
+
+};
+
+
+/* This triggers a compiler error in png.c, if png.c and png.h
+ * do not agree upon the version number.
+ */
+typedef png_structp version_1_2_8;
+
+typedef png_struct FAR * FAR * png_structpp;
+
+/* Here are the function definitions most commonly used.  This is not
+ * the place to find out how to use libpng.  See libpng.txt for the
+ * full explanation, see example.c for the summary.  This just provides
+ * a simple one line description of the use of each function.
+ */
+
+/* Returns the version number of the library */
+extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
+
+/* Tell lib we have already handled the first <num_bytes> magic bytes.
+ * Handling more than 8 bytes from the beginning of the file is an error.
+ */
+extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
+   int num_bytes));
+
+/* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
+ * PNG file.  Returns zero if the supplied bytes match the 8-byte PNG
+ * signature, and non-zero otherwise.  Having num_to_check == 0 or
+ * start > 7 will always fail (ie return non-zero).
+ */
+extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
+   png_size_t num_to_check));
+
+/* Simple signature checking function.  This is the same as calling
+ * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
+ */
+extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
+
+/* Allocate and initialize png_ptr struct for reading, and any other memory. */
+extern PNG_EXPORT(png_structp,png_create_read_struct)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn));
+
+/* Allocate and initialize png_ptr struct for writing, and any other memory */
+extern PNG_EXPORT(png_structp,png_create_write_struct)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn));
+
+#ifdef PNG_WRITE_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
+   PNGARG((png_structp png_ptr));
+#endif
+
+#ifdef PNG_WRITE_SUPPORTED
+extern PNG_EXPORT(void,png_set_compression_buffer_size)
+   PNGARG((png_structp png_ptr, png_uint_32 size));
+#endif
+
+/* Reset the compression stream */
+extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
+
+/* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
+#ifdef PNG_USER_MEM_SUPPORTED
+extern PNG_EXPORT(png_structp,png_create_read_struct_2)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
+   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+extern PNG_EXPORT(png_structp,png_create_write_struct_2)
+   PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
+   png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
+   png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+#endif
+
+/* Write a PNG chunk - size, type, (optional) data, CRC. */
+extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
+   png_bytep chunk_name, png_bytep data, png_size_t length));
+
+/* Write the start of a PNG chunk - length and chunk name. */
+extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
+   png_bytep chunk_name, png_uint_32 length));
+
+/* Write the data of a PNG chunk started with png_write_chunk_start(). */
+extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+/* Finish a chunk started with png_write_chunk_start() (includes CRC). */
+extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
+
+/* Allocate and initialize the info structure */
+extern PNG_EXPORT(png_infop,png_create_info_struct)
+   PNGARG((png_structp png_ptr));
+
+/* Initialize the info structure (old interface - DEPRECATED) */
+extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
+#undef png_info_init
+#define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
+    png_sizeof(png_info));
+extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
+    png_size_t png_info_struct_size));
+
+/* Writes all the PNG information before the image. */
+extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the information before the actual image data. */
+extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+#if defined(PNG_TIME_RFC1123_SUPPORTED)
+extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
+   PNGARG((png_structp png_ptr, png_timep ptime));
+#endif
+
+#if !defined(_WIN32_WCE)
+/* "time.h" functions are not supported on WindowsCE */
+#if defined(PNG_WRITE_tIME_SUPPORTED)
+/* convert from a struct tm to png_time */
+extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
+   struct tm FAR * ttime));
+
+/* convert from time_t to png_time.  Uses gmtime() */
+extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
+   time_t ttime));
+#endif /* PNG_WRITE_tIME_SUPPORTED */
+#endif /* _WIN32_WCE */
+
+#if defined(PNG_READ_EXPAND_SUPPORTED)
+/* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
+extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+/* Use blue, green, red order for pixels. */
+extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
+/* Expand the grayscale to 24-bit RGB if necessary. */
+extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+/* Reduce RGB to grayscale. */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
+   int error_action, double red, double green ));
+#endif
+extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
+   int error_action, png_fixed_point red, png_fixed_point green ));
+extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
+   png_ptr));
+#endif
+
+extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
+   png_colorp palette));
+
+#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
+    defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
+extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
+/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
+extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
+   png_uint_32 filler, int flags));
+/* The values of the PNG_FILLER_ defines should NOT be changed */
+#define PNG_FILLER_BEFORE 0
+#define PNG_FILLER_AFTER 1
+/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
+#if !defined(PNG_1_0_X)
+extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
+   png_uint_32 filler, int flags));
+#endif
+#endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
+
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+/* Swap bytes in 16-bit depth files. */
+extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
+/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
+extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+/* Swap packing order of pixels in bytes. */
+extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
+/* Converts files to legal bit depths. */
+extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
+   png_color_8p true_bits));
+#endif
+
+#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
+    defined(PNG_WRITE_INTERLACING_SUPPORTED)
+/* Have the code handle the interlacing.  Returns the number of passes. */
+extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+/* Invert monochrome files */
+extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_BACKGROUND_SUPPORTED)
+/* Handle alpha and tRNS by replacing with a background color. */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
+   png_color_16p background_color, int background_gamma_code,
+   int need_expand, double background_gamma));
+#endif
+#define PNG_BACKGROUND_GAMMA_UNKNOWN 0
+#define PNG_BACKGROUND_GAMMA_SCREEN  1
+#define PNG_BACKGROUND_GAMMA_FILE    2
+#define PNG_BACKGROUND_GAMMA_UNIQUE  3
+#endif
+
+#if defined(PNG_READ_16_TO_8_SUPPORTED)
+/* strip the second byte of information from a 16-bit depth file. */
+extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+/* Turn on dithering, and reduce the palette to the number of colors available. */
+extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
+   png_colorp palette, int num_palette, int maximum_colors,
+   png_uint_16p histogram, int full_dither));
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+/* Handle gamma correction. Screen_gamma=(display_exponent) */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
+   double screen_gamma, double default_file_gamma));
+#endif
+#endif
+
+#if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
+    defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
+/* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
+/* Deprecated and will be removed.  Use png_permit_mng_features() instead. */
+extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
+   int empty_plte_permitted));
+#endif
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+/* Set how many lines between output flushes - 0 for no flushing */
+extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
+/* Flush the current PNG output buffer */
+extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
+#endif
+
+/* optional update palette with requested transformations */
+extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
+
+/* optional call to update the users info structure */
+extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read one or more rows of image data. */
+extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
+   png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
+#endif
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read a row of data. */
+extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
+   png_bytep row,
+   png_bytep display_row));
+#endif
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the whole image into memory at once. */
+extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
+   png_bytepp image));
+#endif
+
+/* write a row of image data */
+extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
+   png_bytep row));
+
+/* write a few rows of image data */
+extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
+   png_bytepp row, png_uint_32 num_rows));
+
+/* write the image data */
+extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
+   png_bytepp image));
+
+/* writes the end of the PNG file. */
+extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
+/* read the end of the PNG file. */
+extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+/* free any memory associated with the png_info_struct */
+extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
+   png_infopp info_ptr_ptr));
+
+/* free any memory associated with the png_struct and the png_info_structs */
+extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
+   png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
+
+/* free all memory used by the read (old method - NOT DLL EXPORTED) */
+extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_infop end_info_ptr));
+
+/* free any memory associated with the png_struct and the png_info_structs */
+extern PNG_EXPORT(void,png_destroy_write_struct)
+   PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
+
+/* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
+extern void png_write_destroy PNGARG((png_structp png_ptr));
+
+/* set the libpng method of handling chunk CRC errors */
+extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
+   int crit_action, int ancil_action));
+
+/* Values for png_set_crc_action() to say how to handle CRC errors in
+ * ancillary and critical chunks, and whether to use the data contained
+ * therein.  Note that it is impossible to "discard" data in a critical
+ * chunk.  For versions prior to 0.90, the action was always error/quit,
+ * whereas in version 0.90 and later, the action for CRC errors in ancillary
+ * chunks is warn/discard.  These values should NOT be changed.
+ *
+ *      value                       action:critical     action:ancillary
+ */
+#define PNG_CRC_DEFAULT       0  /* error/quit          warn/discard data */
+#define PNG_CRC_ERROR_QUIT    1  /* error/quit          error/quit        */
+#define PNG_CRC_WARN_DISCARD  2  /* (INVALID)           warn/discard data */
+#define PNG_CRC_WARN_USE      3  /* warn/use data       warn/use data     */
+#define PNG_CRC_QUIET_USE     4  /* quiet/use data      quiet/use data    */
+#define PNG_CRC_NO_CHANGE     5  /* use current value   use current value */
+
+/* These functions give the user control over the scan-line filtering in
+ * libpng and the compression methods used by zlib.  These functions are
+ * mainly useful for testing, as the defaults should work with most users.
+ * Those users who are tight on memory or want faster performance at the
+ * expense of compression can modify them.  See the compression library
+ * header file (zlib.h) for an explination of the compression functions.
+ */
+
+/* set the filtering method(s) used by libpng.  Currently, the only valid
+ * value for "method" is 0.
+ */
+extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
+   int filters));
+
+/* Flags for png_set_filter() to say which filters to use.  The flags
+ * are chosen so that they don't conflict with real filter types
+ * below, in case they are supplied instead of the #defined constants.
+ * These values should NOT be changed.
+ */
+#define PNG_NO_FILTERS     0x00
+#define PNG_FILTER_NONE    0x08
+#define PNG_FILTER_SUB     0x10
+#define PNG_FILTER_UP      0x20
+#define PNG_FILTER_AVG     0x40
+#define PNG_FILTER_PAETH   0x80
+#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
+                         PNG_FILTER_AVG | PNG_FILTER_PAETH)
+
+/* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
+ * These defines should NOT be changed.
+ */
+#define PNG_FILTER_VALUE_NONE  0
+#define PNG_FILTER_VALUE_SUB   1
+#define PNG_FILTER_VALUE_UP    2
+#define PNG_FILTER_VALUE_AVG   3
+#define PNG_FILTER_VALUE_PAETH 4
+#define PNG_FILTER_VALUE_LAST  5
+
+#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
+/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
+ * defines, either the default (minimum-sum-of-absolute-differences), or
+ * the experimental method (weighted-minimum-sum-of-absolute-differences).
+ *
+ * Weights are factors >= 1.0, indicating how important it is to keep the
+ * filter type consistent between rows.  Larger numbers mean the current
+ * filter is that many times as likely to be the same as the "num_weights"
+ * previous filters.  This is cumulative for each previous row with a weight.
+ * There needs to be "num_weights" values in "filter_weights", or it can be
+ * NULL if the weights aren't being specified.  Weights have no influence on
+ * the selection of the first row filter.  Well chosen weights can (in theory)
+ * improve the compression for a given image.
+ *
+ * Costs are factors >= 1.0 indicating the relative decoding costs of a
+ * filter type.  Higher costs indicate more decoding expense, and are
+ * therefore less likely to be selected over a filter with lower computational
+ * costs.  There needs to be a value in "filter_costs" for each valid filter
+ * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
+ * setting the costs.  Costs try to improve the speed of decompression without
+ * unduly increasing the compressed image size.
+ *
+ * A negative weight or cost indicates the default value is to be used, and
+ * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
+ * The default values for both weights and costs are currently 1.0, but may
+ * change if good general weighting/cost heuristics can be found.  If both
+ * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
+ * to the UNWEIGHTED method, but with added encoding time/computation.
+ */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
+   int heuristic_method, int num_weights, png_doublep filter_weights,
+   png_doublep filter_costs));
+#endif
+#endif /*  PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
+
+/* Heuristic used for row filter selection.  These defines should NOT be
+ * changed.
+ */
+#define PNG_FILTER_HEURISTIC_DEFAULT    0  /* Currently "UNWEIGHTED" */
+#define PNG_FILTER_HEURISTIC_UNWEIGHTED 1  /* Used by libpng < 0.95 */
+#define PNG_FILTER_HEURISTIC_WEIGHTED   2  /* Experimental feature */
+#define PNG_FILTER_HEURISTIC_LAST       3  /* Not a valid value */
+
+/* Set the library compression level.  Currently, valid values range from
+ * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
+ * (0 - no compression, 9 - "maximal" compression).  Note that tests have
+ * shown that zlib compression levels 3-6 usually perform as well as level 9
+ * for PNG images, and do considerably fewer caclulations.  In the future,
+ * these values may not correspond directly to the zlib compression levels.
+ */
+extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
+   int level));
+
+extern PNG_EXPORT(void,png_set_compression_mem_level)
+   PNGARG((png_structp png_ptr, int mem_level));
+
+extern PNG_EXPORT(void,png_set_compression_strategy)
+   PNGARG((png_structp png_ptr, int strategy));
+
+extern PNG_EXPORT(void,png_set_compression_window_bits)
+   PNGARG((png_structp png_ptr, int window_bits));
+
+extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
+   int method));
+
+/* These next functions are called for input/output, memory, and error
+ * handling.  They are in the file pngrio.c, pngwio.c, and pngerror.c,
+ * and call standard C I/O routines such as fread(), fwrite(), and
+ * fprintf().  These functions can be made to use other I/O routines
+ * at run time for those applications that need to handle I/O in a
+ * different manner by calling png_set_???_fn().  See libpng.txt for
+ * more information.
+ */
+
+#if !defined(PNG_NO_STDIO)
+/* Initialize the input/output for the PNG file to the default functions. */
+extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
+#endif
+
+/* Replace the (error and abort), and warning functions with user
+ * supplied functions.  If no messages are to be printed you must still
+ * write and use replacement functions. The replacement error_fn should
+ * still do a longjmp to the last setjmp location if you are using this
+ * method of error handling.  If error_fn or warning_fn is NULL, the
+ * default function will be used.
+ */
+
+extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
+   png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
+
+/* Return the user pointer associated with the error functions */
+extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
+
+/* Replace the default data output functions with a user supplied one(s).
+ * If buffered output is not used, then output_flush_fn can be set to NULL.
+ * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
+ * output_flush_fn will be ignored (and thus can be NULL).
+ */
+extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
+   png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
+
+/* Replace the default data input function with a user supplied one. */
+extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
+   png_voidp io_ptr, png_rw_ptr read_data_fn));
+
+/* Return the user pointer associated with the I/O functions */
+extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
+
+extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
+   png_read_status_ptr read_row_fn));
+
+extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
+   png_write_status_ptr write_row_fn));
+
+#ifdef PNG_USER_MEM_SUPPORTED
+/* Replace the default memory allocation functions with user supplied one(s). */
+extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
+   png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
+/* Return the user pointer associated with the memory functions */
+extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
+   png_ptr, png_user_transform_ptr read_user_transform_fn));
+#endif
+
+#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
+   png_ptr, png_user_transform_ptr write_user_transform_fn));
+#endif
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_LEGACY_SUPPORTED)
+extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
+   png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
+   int user_transform_channels));
+/* Return the user pointer associated with the user transform functions */
+extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
+   PNGARG((png_structp png_ptr));
+#endif
+
+#ifdef PNG_USER_CHUNKS_SUPPORTED
+extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
+   png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
+extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
+   png_ptr));
+#endif
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+/* Sets the function callbacks for the push reader, and a pointer to a
+ * user-defined structure available to the callback functions.
+ */
+extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
+   png_voidp progressive_ptr,
+   png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
+   png_progressive_end_ptr end_fn));
+
+/* returns the user pointer associated with the push read functions */
+extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
+   PNGARG((png_structp png_ptr));
+
+/* function to be called when data becomes available */
+extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
+
+/* function that combines rows.  Not very much different than the
+ * png_combine_row() call.  Is this even used?????
+ */
+extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
+   png_bytep old_row, png_bytep new_row));
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+
+#if defined(PNG_1_0_X)
+#  define png_malloc_warn png_malloc
+#else
+/* Added at libpng version 1.2.4 */
+extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+#endif
+
+/* frees a pointer allocated by png_malloc() */
+extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
+
+#if defined(PNG_1_0_X)
+/* Function to allocate memory for zlib. */
+extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
+   uInt size));
+
+/* Function to free memory for zlib */
+extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
+#endif
+
+/* Free data that was allocated internally */
+extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 free_me, int num));
+#ifdef PNG_FREE_ME_SUPPORTED
+/* Reassign responsibility for freeing existing data, whether allocated
+ * by libpng or by the application */
+extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int freer, png_uint_32 mask));
+#endif
+/* assignments for png_data_freer */
+#define PNG_DESTROY_WILL_FREE_DATA 1
+#define PNG_SET_WILL_FREE_DATA 1
+#define PNG_USER_WILL_FREE_DATA 2
+/* Flags for png_ptr->free_me and info_ptr->free_me */
+#define PNG_FREE_HIST 0x0008
+#define PNG_FREE_ICCP 0x0010
+#define PNG_FREE_SPLT 0x0020
+#define PNG_FREE_ROWS 0x0040
+#define PNG_FREE_PCAL 0x0080
+#define PNG_FREE_SCAL 0x0100
+#define PNG_FREE_UNKN 0x0200
+#define PNG_FREE_LIST 0x0400
+#define PNG_FREE_PLTE 0x1000
+#define PNG_FREE_TRNS 0x2000
+#define PNG_FREE_TEXT 0x4000
+#define PNG_FREE_ALL  0x7fff
+#define PNG_FREE_MUL  0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
+
+#ifdef PNG_USER_MEM_SUPPORTED
+extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
+   png_uint_32 size));
+extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
+   png_voidp ptr));
+#endif
+
+extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
+   png_voidp s1, png_voidp s2, png_uint_32 size));
+
+extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
+   png_voidp s1, int value, png_uint_32 size));
+
+#if defined(USE_FAR_KEYWORD)  /* memory model conversion function */
+extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
+   int check));
+#endif /* USE_FAR_KEYWORD */
+
+/* Fatal error in PNG image of libpng - can't continue */
+extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
+   png_const_charp error_message));
+
+/* The same, but the chunk name is prepended to the error string. */
+extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
+   png_const_charp error_message));
+
+/* Non-fatal error in libpng.  Can continue, but may have a problem. */
+extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
+   png_const_charp warning_message));
+
+/* Non-fatal error in libpng, chunk name is prepended to message. */
+extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
+   png_const_charp warning_message));
+
+/* The png_set_<chunk> functions are for storing values in the png_info_struct.
+ * Similarly, the png_get_<chunk> calls are used to read values from the
+ * png_info_struct, either storing the parameters in the passed variables, or
+ * setting pointers into the png_info_struct where the data is stored.  The
+ * png_get_<chunk> functions return a non-zero value if the data was available
+ * in info_ptr, or return zero and do not change any of the parameters if the
+ * data was not available.
+ *
+ * These functions should be used instead of directly accessing png_info
+ * to avoid problems with future changes in the size and internal layout of
+ * png_info_struct.
+ */
+/* Returns "flag" if chunk data is valid in info_ptr. */
+extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
+png_infop info_ptr, png_uint_32 flag));
+
+/* Returns number of bytes needed to hold a transformed row. */
+extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+/* Returns row_pointers, which is an array of pointers to scanlines that was
+returned from png_read_png(). */
+extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+/* Set row_pointers, which is an array of pointers to scanlines for use
+by png_write_png(). */
+extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytepp row_pointers));
+#endif
+
+/* Returns number of color channels in image. */
+extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#ifdef PNG_EASY_ACCESS_SUPPORTED
+/* Returns image width in pixels. */
+extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image height in pixels. */
+extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image bit_depth. */
+extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image color_type. */
+extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image filter_type. */
+extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image interlace_type. */
+extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image compression_type. */
+extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns image resolution in pixels per meter, from pHYs chunk data. */
+extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+/* Returns pixel aspect ratio, computed from pHYs chunk data.  */
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+#endif
+
+/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
+extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
+png_ptr, png_infop info_ptr));
+
+#endif /* PNG_EASY_ACCESS_SUPPORTED */
+
+/* Returns pointer to signature string read from PNG header */
+extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
+png_infop info_ptr));
+
+#if defined(PNG_bKGD_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_16p *background));
+#endif
+
+#if defined(PNG_bKGD_SUPPORTED)
+extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_16p background));
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double *white_x, double *white_y, double *red_x,
+   double *red_y, double *green_x, double *green_y, double *blue_x,
+   double *blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
+   *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
+   png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
+   *int_blue_x, png_fixed_point *int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double white_x, double white_y, double red_x,
+   double red_y, double green_x, double green_y, double blue_x, double blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
+   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+   png_fixed_point int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double *file_gamma));
+#endif
+extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point *int_file_gamma));
+#endif
+
+#if defined(PNG_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, double file_gamma));
+#endif
+extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_fixed_point int_file_gamma));
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_16p *hist));
+#endif
+
+#if defined(PNG_hIST_SUPPORTED)
+extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_16p hist));
+#endif
+
+extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
+   int *bit_depth, int *color_type, int *interlace_method,
+   int *compression_method, int *filter_method));
+
+extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
+   int color_type, int interlace_method, int compression_method,
+   int filter_method));
+
+#if defined(PNG_oFFs_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
+   int *unit_type));
+#endif
+
+#if defined(PNG_oFFs_SUPPORTED)
+extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
+   int unit_type));
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
+   int *type, int *nparams, png_charp *units, png_charpp *params));
+#endif
+
+#if defined(PNG_pCAL_SUPPORTED)
+extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
+   int type, int nparams, png_charp units, png_charpp params));
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
+#endif
+
+#if defined(PNG_pHYs_SUPPORTED)
+extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
+#endif
+
+extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_colorp *palette, int *num_palette));
+
+extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_colorp palette, int num_palette));
+
+#if defined(PNG_sBIT_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_8p *sig_bit));
+#endif
+
+#if defined(PNG_sBIT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_color_8p sig_bit));
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *intent));
+#endif
+
+#if defined(PNG_sRGB_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int intent));
+extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int intent));
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charpp name, int *compression_type,
+   png_charpp profile, png_uint_32 *proflen));
+   /* Note to maintainer: profile should be png_bytepp */
+#endif
+
+#if defined(PNG_iCCP_SUPPORTED)
+extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_charp name, int compression_type,
+   png_charp profile, png_uint_32 proflen));
+   /* Note to maintainer: profile should be png_bytep */
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_sPLT_tpp entries));
+#endif
+
+#if defined(PNG_sPLT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_sPLT_tp entries, int nentries));
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)
+/* png_get_text also returns the number of text chunks in *num_text */
+extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp *text_ptr, int *num_text));
+#endif
+
+/*
+ *  Note while png_set_text() will accept a structure whose text,
+ *  language, and  translated keywords are NULL pointers, the structure
+ *  returned by png_get_text will always contain regular
+ *  zero-terminated C strings.  They might be empty strings but
+ *  they will never be NULL pointers.
+ */
+
+#if defined(PNG_TEXT_SUPPORTED)
+extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp text_ptr, int num_text));
+#endif
+
+#if defined(PNG_tIME_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_timep *mod_time));
+#endif
+
+#if defined(PNG_tIME_SUPPORTED)
+extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_timep mod_time));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep *trans, int *num_trans,
+   png_color_16p *trans_values));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_bytep trans, int num_trans,
+   png_color_16p trans_values));
+#endif
+
+#if defined(PNG_tRNS_SUPPORTED)
+#endif
+
+#if defined(PNG_sCAL_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *unit, double *width, double *height));
+#else
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
+#endif
+#endif
+#endif /* PNG_sCAL_SUPPORTED */
+
+#if defined(PNG_sCAL_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int unit, double width, double height));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
+#endif
+#endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
+
+#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
+/* provide a list of chunks and how they are to be handled, if the built-in
+   handling or default unknown chunk handling is not desired.  Any chunks not
+   listed will be handled in the default manner.  The IHDR and IEND chunks
+   must not be listed.
+      keep = 0: follow default behavour
+           = 1: do not keep
+           = 2: keep only if safe-to-copy
+           = 3: keep even if unsafe-to-copy
+*/
+extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
+   png_ptr, int keep, png_bytep chunk_list, int num_chunks));
+extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
+extern PNG_EXPORT(void, png_set_unknown_chunk_location)
+   PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
+extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
+   png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
+#endif
+#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
+   chunk_name));
+#endif
+
+/* Png_free_data() will turn off the "valid" flag for anything it frees.
+   If you need to turn it off for a chunk that your application has freed,
+   you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
+extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
+   png_infop info_ptr, int mask));
+
+#if defined(PNG_INFO_IMAGE_SUPPORTED)
+/* The "params" pointer is currently not used and is for future expansion. */
+extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
+                        png_infop info_ptr,
+                        int transforms,
+                        png_voidp params));
+extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
+                        png_infop info_ptr,
+                        int transforms,
+                        png_voidp params));
+#endif
+
+/* Define PNG_DEBUG at compile time for debugging information.  Higher
+ * numbers for PNG_DEBUG mean more debugging information.  This has
+ * only been added since version 0.95 so it is not implemented throughout
+ * libpng yet, but more support will be added as needed.
+ */
+#ifdef PNG_DEBUG
+#if (PNG_DEBUG > 0)
+#if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
+#include <crtdbg.h>
+#if (PNG_DEBUG > 1)
+#define png_debug(l,m)  _RPT0(_CRT_WARN,m)
+#define png_debug1(l,m,p1)  _RPT1(_CRT_WARN,m,p1)
+#define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
+#endif
+#else /* PNG_DEBUG_FILE || !_MSC_VER */
+#ifndef PNG_DEBUG_FILE
+#define PNG_DEBUG_FILE stderr
+#endif /* PNG_DEBUG_FILE */
+#if (PNG_DEBUG > 1)
+#define png_debug(l,m) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
+}
+#define png_debug1(l,m,p1) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
+}
+#define png_debug2(l,m,p1,p2) \
+{ \
+     int num_tabs=l; \
+     fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
+       (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
+}
+#endif /* (PNG_DEBUG > 1) */
+#endif /* _MSC_VER */
+#endif /* (PNG_DEBUG > 0) */
+#endif /* PNG_DEBUG */
+#ifndef png_debug
+#define png_debug(l, m)
+#endif
+#ifndef png_debug1
+#define png_debug1(l, m, p1)
+#endif
+#ifndef png_debug2
+#define png_debug2(l, m, p1, p2)
+#endif
+
+extern PNG_EXPORT(png_bytep,png_sig_bytes) PNGARG((void));
+
+extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
+extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
+   png_ptr, png_uint_32 mng_features_permitted));
+#endif
+
+/* For use in png_set_keep_unknown, added to version 1.2.6 */
+#define PNG_HANDLE_CHUNK_AS_DEFAULT   0
+#define PNG_HANDLE_CHUNK_NEVER        1
+#define PNG_HANDLE_CHUNK_IF_SAFE      2
+#define PNG_HANDLE_CHUNK_ALWAYS       3
+
+/* Added to version 1.2.0 */
+#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+#define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED  0x01  /* not user-settable */
+#define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU    0x02  /* not user-settable */
+#define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  0x04
+#define PNG_ASM_FLAG_MMX_READ_INTERLACE    0x08
+#define PNG_ASM_FLAG_MMX_READ_FILTER_SUB   0x10
+#define PNG_ASM_FLAG_MMX_READ_FILTER_UP    0x20
+#define PNG_ASM_FLAG_MMX_READ_FILTER_AVG   0x40
+#define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
+#define PNG_ASM_FLAGS_INITIALIZED          0x80000000  /* not user-settable */
+
+#define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW  \
+                           | PNG_ASM_FLAG_MMX_READ_INTERLACE    \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_SUB   \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_UP    \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_AVG   \
+                           | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
+#define PNG_MMX_WRITE_FLAGS ( 0 )
+
+#define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
+                      | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU   \
+                      | PNG_MMX_READ_FLAGS                \
+                      | PNG_MMX_WRITE_FLAGS )
+
+#define PNG_SELECT_READ   1
+#define PNG_SELECT_WRITE  2
+
+#if !defined(PNG_1_0_X)
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
+   PNGARG((int flag_select, int *compilerID));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
+   PNGARG((int flag_select));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
+   PNGARG((png_structp png_ptr));
+
+/* pngget.c */
+extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
+   PNGARG((png_structp png_ptr));
+
+/* pngget.c */
+extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
+   PNGARG((png_structp png_ptr));
+
+/* pngset.c */
+extern PNG_EXPORT(void,png_set_asm_flags)
+   PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
+
+/* pngset.c */
+extern PNG_EXPORT(void,png_set_mmx_thresholds)
+   PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
+   png_uint_32 mmx_rowbytes_threshold));
+
+#endif /* PNG_1_0_X */
+#endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
+
+#if !defined(PNG_1_0_X)
+/* png.c, pnggccrd.c, or pngvcrd.c */
+extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
+
+/* Strip the prepended error numbers ("#nnn ") from error and warning
+ * messages before passing them to the error or warning handler. */
+#ifdef PNG_ERROR_NUMBERS_SUPPORTED
+extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
+   png_ptr, png_uint_32 strip_mode));
+#endif
+
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.2.6 */
+#ifdef PNG_SET_USER_LIMITS_SUPPORTED
+extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
+   png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
+extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
+   png_ptr));
+extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
+   png_ptr));
+#endif
+
+/* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
+
+#ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
+/* With these routines we avoid an integer divide, which will be slower on
+ * most machines.  However, it does take more operations than the corresponding
+ * divide method, so it may be slower on a few RISC systems.  There are two
+ * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
+ *
+ * Note that the rounding factors are NOT supposed to be the same!  128 and
+ * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
+ * standard method.
+ *
+ * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
+ */
+
+ /* fg and bg should be in `gamma 1.0' space; alpha is the opacity          */
+
+#  define png_composite(composite, fg, alpha, bg)                            \
+     { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
+                        +        (png_uint_16)(bg)*(png_uint_16)(255 -       \
+                        (png_uint_16)(alpha)) + (png_uint_16)128);           \
+       (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
+
+#  define png_composite_16(composite, fg, alpha, bg)                         \
+     { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
+                        + (png_uint_32)(bg)*(png_uint_32)(65535L -           \
+                        (png_uint_32)(alpha)) + (png_uint_32)32768L);        \
+       (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
+
+#else  /* standard method using integer division */
+
+#  define png_composite(composite, fg, alpha, bg)                            \
+     (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) +    \
+       (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) +       \
+       (png_uint_16)127) / 255)
+
+#  define png_composite_16(composite, fg, alpha, bg)                         \
+     (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
+       (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) +      \
+       (png_uint_32)32767) / (png_uint_32)65535L)
+
+#endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
+
+/* These next functions are used internally in the code.  They generally
+ * shouldn't be used unless you are writing code to add or replace some
+ * functionality in libpng.  More information about most functions can
+ * be found in the files where the functions are located.
+ */
+
+#if defined(PNG_INTERNAL)
+
+/* Various modes of operation.  Note that after an init, mode is set to
+ * zero automatically when the structure is created.
+ */
+#define PNG_HAVE_IHDR               0x01
+#define PNG_HAVE_PLTE               0x02
+#define PNG_HAVE_IDAT               0x04
+#define PNG_AFTER_IDAT              0x08
+#define PNG_HAVE_IEND               0x10
+#define PNG_HAVE_gAMA               0x20
+#define PNG_HAVE_cHRM               0x40
+#define PNG_HAVE_sRGB               0x80
+#define PNG_HAVE_CHUNK_HEADER      0x100
+#define PNG_WROTE_tIME             0x200
+#define PNG_WROTE_INFO_BEFORE_PLTE 0x400
+#define PNG_BACKGROUND_IS_GRAY     0x800
+#define PNG_HAVE_PNG_SIGNATURE    0x1000
+
+/* flags for the transformations the PNG library does on the image data */
+#define PNG_BGR                0x0001
+#define PNG_INTERLACE          0x0002
+#define PNG_PACK               0x0004
+#define PNG_SHIFT              0x0008
+#define PNG_SWAP_BYTES         0x0010
+#define PNG_INVERT_MONO        0x0020
+#define PNG_DITHER             0x0040
+#define PNG_BACKGROUND         0x0080
+#define PNG_BACKGROUND_EXPAND  0x0100
+                          /*   0x0200 unused */
+#define PNG_16_TO_8            0x0400
+#define PNG_RGBA               0x0800
+#define PNG_EXPAND             0x1000
+#define PNG_GAMMA              0x2000
+#define PNG_GRAY_TO_RGB        0x4000
+#define PNG_FILLER             0x8000L
+#define PNG_PACKSWAP          0x10000L
+#define PNG_SWAP_ALPHA        0x20000L
+#define PNG_STRIP_ALPHA       0x40000L
+#define PNG_INVERT_ALPHA      0x80000L
+#define PNG_USER_TRANSFORM   0x100000L
+#define PNG_RGB_TO_GRAY_ERR  0x200000L
+#define PNG_RGB_TO_GRAY_WARN 0x400000L
+#define PNG_RGB_TO_GRAY      0x600000L  /* two bits, RGB_TO_GRAY_ERR|WARN */
+                       /*    0x800000L     Unused */
+#define PNG_ADD_ALPHA       0x1000000L  /* Added to libpng-1.2.7 */
+                       /*   0x2000000L  unused */
+                       /*   0x4000000L  unused */
+                       /*   0x8000000L  unused */
+                       /*  0x10000000L  unused */
+                       /*  0x20000000L  unused */
+                       /*  0x40000000L  unused */
+
+/* flags for png_create_struct */
+#define PNG_STRUCT_PNG   0x0001
+#define PNG_STRUCT_INFO  0x0002
+
+/* Scaling factor for filter heuristic weighting calculations */
+#define PNG_WEIGHT_SHIFT 8
+#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
+#define PNG_COST_SHIFT 3
+#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
+
+/* flags for the png_ptr->flags rather than declaring a byte for each one */
+#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY     0x0001
+#define PNG_FLAG_ZLIB_CUSTOM_LEVEL        0x0002
+#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL    0x0004
+#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS  0x0008
+#define PNG_FLAG_ZLIB_CUSTOM_METHOD       0x0010
+#define PNG_FLAG_ZLIB_FINISHED            0x0020
+#define PNG_FLAG_ROW_INIT                 0x0040
+#define PNG_FLAG_FILLER_AFTER             0x0080
+#define PNG_FLAG_CRC_ANCILLARY_USE        0x0100
+#define PNG_FLAG_CRC_ANCILLARY_NOWARN     0x0200
+#define PNG_FLAG_CRC_CRITICAL_USE         0x0400
+#define PNG_FLAG_CRC_CRITICAL_IGNORE      0x0800
+#define PNG_FLAG_FREE_PLTE                0x1000
+#define PNG_FLAG_FREE_TRNS                0x2000
+#define PNG_FLAG_FREE_HIST                0x4000
+#define PNG_FLAG_KEEP_UNKNOWN_CHUNKS      0x8000L
+#define PNG_FLAG_KEEP_UNSAFE_CHUNKS       0x10000L
+#define PNG_FLAG_LIBRARY_MISMATCH         0x20000L
+#define PNG_FLAG_STRIP_ERROR_NUMBERS      0x40000L
+#define PNG_FLAG_STRIP_ERROR_TEXT         0x80000L
+#define PNG_FLAG_MALLOC_NULL_MEM_OK       0x100000L
+#define PNG_FLAG_ADD_ALPHA                0x200000L  /* Added to libpng-1.2.8 */
+#define PNG_FLAG_STRIP_ALPHA              0x400000L  /* Added to libpng-1.2.8 */
+                                  /*      0x800000L  unused */
+                                  /*     0x1000000L  unused */
+                                  /*     0x2000000L  unused */
+                                  /*     0x4000000L  unused */
+                                  /*     0x8000000L  unused */
+                                  /*    0x10000000L  unused */
+                                  /*    0x20000000L  unused */
+                                  /*    0x40000000L  unused */
+
+#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
+                                     PNG_FLAG_CRC_ANCILLARY_NOWARN)
+
+#define PNG_FLAG_CRC_CRITICAL_MASK  (PNG_FLAG_CRC_CRITICAL_USE | \
+                                     PNG_FLAG_CRC_CRITICAL_IGNORE)
+
+#define PNG_FLAG_CRC_MASK           (PNG_FLAG_CRC_ANCILLARY_MASK | \
+                                     PNG_FLAG_CRC_CRITICAL_MASK)
+
+/* save typing and make code easier to understand */
+
+#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
+   abs((int)((c1).green) - (int)((c2).green)) + \
+   abs((int)((c1).blue) - (int)((c2).blue)))
+
+/* Added to libpng-1.2.6 JB */
+#define PNG_ROWBYTES(pixel_bits, width) \
+    ((pixel_bits) >= 8 ? \
+    ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
+    (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
+
+/* PNG_OUT_OF_RANGE returns true if value is outside the range
+   ideal-delta..ideal+delta.  Each argument is evaluated twice.
+   "ideal" and "delta" should be constants, normally simple
+   integers, "value" a variable. Added to libpng-1.2.6 JB */
+#define PNG_OUT_OF_RANGE(value, ideal, delta) \
+        ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
+
+/* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
+#if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
+/* place to hold the signature string for a PNG file. */
+#ifdef PNG_USE_GLOBAL_ARRAYS
+   PNG_EXPORT_VAR (const png_byte FARDATA) png_sig[8];
+#else
+#define png_sig png_sig_bytes(NULL)
+#endif
+#endif /* PNG_NO_EXTERN */
+
+/* Constant strings for known chunk types.  If you need to add a chunk,
+ * define the name here, and add an invocation of the macro in png.c and
+ * wherever it's needed.
+ */
+#define PNG_IHDR const png_byte png_IHDR[5] = { 73,  72,  68,  82, '\0'}
+#define PNG_IDAT const png_byte png_IDAT[5] = { 73,  68,  65,  84, '\0'}
+#define PNG_IEND const png_byte png_IEND[5] = { 73,  69,  78,  68, '\0'}
+#define PNG_PLTE const png_byte png_PLTE[5] = { 80,  76,  84,  69, '\0'}
+#define PNG_bKGD const png_byte png_bKGD[5] = { 98,  75,  71,  68, '\0'}
+#define PNG_cHRM const png_byte png_cHRM[5] = { 99,  72,  82,  77, '\0'}
+#define PNG_gAMA const png_byte png_gAMA[5] = {103,  65,  77,  65, '\0'}
+#define PNG_hIST const png_byte png_hIST[5] = {104,  73,  83,  84, '\0'}
+#define PNG_iCCP const png_byte png_iCCP[5] = {105,  67,  67,  80, '\0'}
+#define PNG_iTXt const png_byte png_iTXt[5] = {105,  84,  88, 116, '\0'}
+#define PNG_oFFs const png_byte png_oFFs[5] = {111,  70,  70, 115, '\0'}
+#define PNG_pCAL const png_byte png_pCAL[5] = {112,  67,  65,  76, '\0'}
+#define PNG_sCAL const png_byte png_sCAL[5] = {115,  67,  65,  76, '\0'}
+#define PNG_pHYs const png_byte png_pHYs[5] = {112,  72,  89, 115, '\0'}
+#define PNG_sBIT const png_byte png_sBIT[5] = {115,  66,  73,  84, '\0'}
+#define PNG_sPLT const png_byte png_sPLT[5] = {115,  80,  76,  84, '\0'}
+#define PNG_sRGB const png_byte png_sRGB[5] = {115,  82,  71,  66, '\0'}
+#define PNG_tEXt const png_byte png_tEXt[5] = {116,  69,  88, 116, '\0'}
+#define PNG_tIME const png_byte png_tIME[5] = {116,  73,  77,  69, '\0'}
+#define PNG_tRNS const png_byte png_tRNS[5] = {116,  82,  78,  83, '\0'}
+#define PNG_zTXt const png_byte png_zTXt[5] = {122,  84,  88, 116, '\0'}
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IHDR[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IDAT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_IEND[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_PLTE[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_bKGD[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_cHRM[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_gAMA[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_hIST[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_iCCP[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_iTXt[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_oFFs[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_pCAL[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sCAL[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_pHYs[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sBIT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sPLT[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_sRGB[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tEXt[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tIME[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_tRNS[5];
+PNG_EXPORT_VAR (const png_byte FARDATA) png_zTXt[5];
+#endif /* PNG_USE_GLOBAL_ARRAYS */
+
+
+/* Inline macros to do direct reads of bytes from the input buffer.  These
+ * require that you are using an architecture that uses PNG byte ordering
+ * (MSB first) and supports unaligned data storage.  I think that PowerPC
+ * in big-endian mode and 680x0 are the only ones that will support this.
+ * The x86 line of processors definitely do not.  The png_get_int_32()
+ * routine also assumes we are using two's complement format for negative
+ * values, which is almost certainly true.
+ */
+#if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
+#  if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED)
+#    define png_get_int_32(buf) ( *((png_int_32p) (buf)))
+#  endif
+#  define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
+#  define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
+#else
+#  if defined(PNG_pCAL_SUPPORTED) || defined(PNG_oFFs_SUPPORTED)
+PNG_EXTERN png_int_32 png_get_int_32 PNGARG((png_bytep buf));
+#  endif
+PNG_EXTERN png_uint_32 png_get_uint_32 PNGARG((png_bytep buf));
+PNG_EXTERN png_uint_16 png_get_uint_16 PNGARG((png_bytep buf));
+#endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
+PNG_EXTERN png_uint_32 png_get_uint_31 PNGARG((png_structp png_ptr,
+  png_bytep buf));
+
+/* Initialize png_ptr struct for reading, and allocate any other memory.
+ * (old interface - DEPRECATED - use png_create_read_struct instead).
+ */
+extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
+#undef png_read_init
+#define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
+    PNG_LIBPNG_VER_STRING,  png_sizeof(png_struct));
+extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size));
+extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
+    png_info_size));
+
+/* Initialize png_ptr struct for writing, and allocate any other memory.
+ * (old interface - DEPRECATED - use png_create_write_struct instead).
+ */
+extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
+#undef png_write_init
+#define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
+    PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
+extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size));
+extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
+    png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
+    png_info_size));
+
+/* Allocate memory for an internal libpng struct */
+PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
+
+/* Free memory from internal libpng struct */
+PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
+
+PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
+  malloc_fn, png_voidp mem_ptr));
+PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
+   png_free_ptr free_fn, png_voidp mem_ptr));
+
+/* Free any memory that info_ptr points to and reset struct. */
+PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+#ifndef PNG_1_0_X
+/* Function to allocate memory for zlib. */
+PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
+
+/* Function to free memory for zlib */
+PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
+
+#ifdef PNG_SIZE_T
+/* Function to convert a sizeof an item to png_sizeof item */
+   PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
+#endif
+
+/* Next four functions are used internally as callbacks.  PNGAPI is required
+ * but not PNG_EXPORT.  PNGAPI added at libpng version 1.2.3. */
+
+PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t length));
+#endif
+
+PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
+   png_bytep data, png_size_t length));
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+#if !defined(PNG_NO_STDIO)
+PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
+#endif
+#endif
+#else /* PNG_1_0_X */
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t length));
+#endif
+#endif /* PNG_1_0_X */
+
+/* Reset the CRC variable */
+PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
+
+/* Write the "data" buffer to whatever output you are using. */
+PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+/* Read data from whatever input you are using into the "data" buffer */
+PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+/* Read bytes into buf, and update png_ptr->crc */
+PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
+   png_size_t length));
+
+/* Decompress data in a chunk that uses compression */
+#if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
+    defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
+PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
+   int comp_type, png_charp chunkdata, png_size_t chunklength,
+   png_size_t prefix_length, png_size_t *data_length));
+#endif
+
+/* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
+PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
+
+/* Read the CRC from the file and compare it to the libpng calculated CRC */
+PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
+
+/* Calculate the CRC over a section of data.  Note that we are only
+ * passing a maximum of 64K on systems that have this as a memory limit,
+ * since this is the maximum buffer size we can specify.
+ */
+PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
+   png_size_t length));
+
+#if defined(PNG_WRITE_FLUSH_SUPPORTED)
+PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
+#endif
+
+
+/* Place a 32-bit number into a buffer in PNG byte order (big-endian).
+ * The only currently known PNG chunks that use signed numbers are
+ * the ancillary extension chunks, oFFs and pCAL.
+ */
+PNG_EXTERN void png_save_uint_32 PNGARG((png_bytep buf, png_uint_32 i));
+
+#if defined(PNG_WRITE_pCAL_SUPPORTED) || defined(PNG_WRITE_oFFs_SUPPORTED)
+PNG_EXTERN void png_save_int_32 PNGARG((png_bytep buf, png_int_32 i));
+#endif
+
+/* Place a 16-bit number into a buffer in PNG byte order.
+ * The parameter is declared unsigned int, not png_uint_16,
+ * just to avoid potential problems on pre-ANSI C compilers.
+ */
+PNG_EXTERN void png_save_uint_16 PNGARG((png_bytep buf, unsigned int i));
+
+/* simple function to write the signature */
+PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
+
+/* write various chunks */
+
+/* Write the IHDR chunk, and update the png_struct with the necessary
+ * information.
+ */
+PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
+   png_uint_32 height,
+   int bit_depth, int color_type, int compression_method, int filter_method,
+   int interlace_method));
+
+PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
+   png_uint_32 num_pal));
+
+PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
+   png_size_t length));
+
+PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
+
+#if defined(PNG_WRITE_gAMA_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
+    file_gamma));
+#endif
+#endif
+
+#if defined(PNG_WRITE_sBIT_SUPPORTED)
+PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
+   int color_type));
+#endif
+
+#if defined(PNG_WRITE_cHRM_SUPPORTED)
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
+   double white_x, double white_y,
+   double red_x, double red_y, double green_x, double green_y,
+   double blue_x, double blue_y));
+#endif
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
+   png_fixed_point int_white_x, png_fixed_point int_white_y,
+   png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
+   int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
+   png_fixed_point int_blue_y));
+#endif
+#endif
+
+#if defined(PNG_WRITE_sRGB_SUPPORTED)
+PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
+   int intent));
+#endif
+
+#if defined(PNG_WRITE_iCCP_SUPPORTED)
+PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
+   png_charp name, int compression_type,
+   png_charp profile, int proflen));
+   /* Note to maintainer: profile should be png_bytep */
+#endif
+
+#if defined(PNG_WRITE_sPLT_SUPPORTED)
+PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
+   png_sPLT_tp palette));
+#endif
+
+#if defined(PNG_WRITE_tRNS_SUPPORTED)
+PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
+   png_color_16p values, int number, int color_type));
+#endif
+
+#if defined(PNG_WRITE_bKGD_SUPPORTED)
+PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
+   png_color_16p values, int color_type));
+#endif
+
+#if defined(PNG_WRITE_hIST_SUPPORTED)
+PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
+   int num_hist));
+#endif
+
+#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
+    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
+PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
+   png_charp key, png_charpp new_key));
+#endif
+
+#if defined(PNG_WRITE_tEXt_SUPPORTED)
+PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
+   png_charp text, png_size_t text_len));
+#endif
+
+#if defined(PNG_WRITE_zTXt_SUPPORTED)
+PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
+   png_charp text, png_size_t text_len, int compression));
+#endif
+
+#if defined(PNG_WRITE_iTXt_SUPPORTED)
+PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
+   int compression, png_charp key, png_charp lang, png_charp lang_key,
+   png_charp text));
+#endif
+
+#if defined(PNG_TEXT_SUPPORTED)  /* Added at version 1.0.14 and 1.2.4 */
+PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_textp text_ptr, int num_text));
+#endif
+
+#if defined(PNG_WRITE_oFFs_SUPPORTED)
+PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
+   png_int_32 x_offset, png_int_32 y_offset, int unit_type));
+#endif
+
+#if defined(PNG_WRITE_pCAL_SUPPORTED)
+PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
+   png_int_32 X0, png_int_32 X1, int type, int nparams,
+   png_charp units, png_charpp params));
+#endif
+
+#if defined(PNG_WRITE_pHYs_SUPPORTED)
+PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
+   png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
+   int unit_type));
+#endif
+
+#if defined(PNG_WRITE_tIME_SUPPORTED)
+PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
+   png_timep mod_time));
+#endif
+
+#if defined(PNG_WRITE_sCAL_SUPPORTED)
+#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
+PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
+   int unit, double width, double height));
+#else
+#ifdef PNG_FIXED_POINT_SUPPORTED
+PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
+   int unit, png_charp width, png_charp height));
+#endif
+#endif
+#endif
+
+/* Called when finished processing a row of data */
+PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
+
+/* Internal use only.   Called before first row of data */
+PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
+#endif
+
+/* combine a row of data, dealing with alpha, etc. if requested */
+PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
+   int mask));
+
+#if defined(PNG_READ_INTERLACING_SUPPORTED)
+/* expand an interlaced row */
+/* OLD pre-1.0.9 interface:
+PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
+   png_bytep row, int pass, png_uint_32 transformations));
+ */
+PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
+#endif
+
+/* GRR TO DO (2.0 or whenever):  simplify other internal calling interfaces */
+
+#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
+/* grab pixels out of a row for an interlaced pass */
+PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
+   png_bytep row, int pass));
+#endif
+
+/* unfilter a row */
+PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
+   png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
+
+/* Choose the best filter to use and filter the row data */
+PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
+   png_row_infop row_info));
+
+/* Write out the filtered row. */
+PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
+   png_bytep filtered_row));
+/* finish a row while reading, dealing with interlacing passes, etc. */
+PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
+
+/* initialize the row buffers, etc. */
+PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
+/* optional call to update the users info structure */
+PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+
+/* these are the functions that do the transformations */
+#if defined(PNG_READ_FILLER_SUPPORTED)
+PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 filler, png_uint_32 flags));
+#endif
+
+#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
+    defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
+PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 flags));
+#endif
+
+#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
+PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
+PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
+PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
+   row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
+PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_READ_PACK_SUPPORTED)
+PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_SHIFT_SUPPORTED)
+PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_8p sig_bits));
+#endif
+
+#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
+PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_16_TO_8_SUPPORTED)
+PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_READ_DITHER_SUPPORTED)
+PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
+   png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
+
+#  if defined(PNG_CORRECT_PALETTE_SUPPORTED)
+PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
+   png_colorp palette, int num_palette));
+#  endif
+#endif
+
+#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
+PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
+#endif
+
+#if defined(PNG_WRITE_PACK_SUPPORTED)
+PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
+   png_bytep row, png_uint_32 bit_depth));
+#endif
+
+#if defined(PNG_WRITE_SHIFT_SUPPORTED)
+PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_8p bit_depth));
+#endif
+
+#if defined(PNG_READ_BACKGROUND_SUPPORTED)
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_16p trans_values, png_color_16p background,
+   png_color_16p background_1,
+   png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
+   png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
+   png_uint_16pp gamma_16_to_1, int gamma_shift));
+#else
+PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
+   png_color_16p trans_values, png_color_16p background));
+#endif
+#endif
+
+#if defined(PNG_READ_GAMMA_SUPPORTED)
+PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
+   png_bytep gamma_table, png_uint_16pp gamma_16_table,
+   int gamma_shift));
+#endif
+
+#if defined(PNG_READ_EXPAND_SUPPORTED)
+PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
+   png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
+PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
+   png_bytep row, png_color_16p trans_value));
+#endif
+
+/* The following decodes the appropriate chunks, and does error correction,
+ * then calls the appropriate callback for the chunk if it is valid.
+ */
+
+/* decode the IHDR chunk */
+PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+
+#if defined(PNG_READ_bKGD_SUPPORTED)
+PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_cHRM_SUPPORTED)
+PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_gAMA_SUPPORTED)
+PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_hIST_SUPPORTED)
+PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_iCCP_SUPPORTED)
+extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif /* PNG_READ_iCCP_SUPPORTED */
+
+#if defined(PNG_READ_iTXt_SUPPORTED)
+PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_oFFs_SUPPORTED)
+PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_pCAL_SUPPORTED)
+PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_pHYs_SUPPORTED)
+PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sBIT_SUPPORTED)
+PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sCAL_SUPPORTED)
+PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_sPLT_SUPPORTED)
+extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif /* PNG_READ_sPLT_SUPPORTED */
+
+#if defined(PNG_READ_sRGB_SUPPORTED)
+PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tEXt_SUPPORTED)
+PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tIME_SUPPORTED)
+PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_tRNS_SUPPORTED)
+PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+#if defined(PNG_READ_zTXt_SUPPORTED)
+PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
+   png_uint_32 length));
+#endif
+
+PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+
+PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
+   png_bytep chunk_name));
+
+/* handle the transformations for reading and writing */
+PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
+
+PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
+
+#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
+PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
+   png_uint_32 length));
+PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
+   png_bytep buffer, png_size_t buffer_length));
+PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
+PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
+PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
+#if defined(PNG_READ_tEXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+#if defined(PNG_READ_zTXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+#if defined(PNG_READ_iTXt_SUPPORTED)
+PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr, png_uint_32 length));
+PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
+   png_infop info_ptr));
+#endif
+
+#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
+
+#ifdef PNG_MNG_FEATURES_SUPPORTED
+PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
+   png_bytep row));
+PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
+   png_bytep row));
+#endif
+
+#if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
+/* png.c */ /* PRIVATE */
+PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
+#endif
+/* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
+
+#endif /* PNG_INTERNAL */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PNG_VERSION_INFO_ONLY */
+/* do not put anything past this line */
+#endif /* PNG_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/pngconf.h ./aperios/include/pngconf.h
--- ../Tekkotsu_2.3/aperios/include/pngconf.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/pngconf.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,1437 @@
+
+/* pngconf.h - machine configurable file for libpng
+ *
+ * libpng version 1.2.8 - December 3, 2004
+ * For conditions of distribution and use, see copyright notice in png.h
+ * Copyright (c) 1998-2004 Glenn Randers-Pehrson
+ * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
+ * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
+ */
+
+/* Any machine specific code is near the front of this file, so if you
+ * are configuring libpng for a machine, you may want to read the section
+ * starting here down to where it starts to typedef png_color, png_text,
+ * and png_info.
+ */
+
+#ifndef PNGCONF_H
+#define PNGCONF_H
+
+#define PNG_1_2_X
+
+/* 
+ * PNG_USER_CONFIG has to be defined on the compiler command line. This
+ * includes the resource compiler for Windows DLL configurations.
+ */
+#ifdef PNG_USER_CONFIG
+#include "pngusr.h"
+#endif
+
+/*
+ * Added at libpng-1.2.8
+ *  
+ * If you create a private DLL you need to define in "pngusr.h" the followings:
+ * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
+ *        the DLL was built>
+ *  e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
+ * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
+ *        distinguish your DLL from those of the official release. These
+ *        correspond to the trailing letters that come after the version
+ *        number and must match your private DLL name>
+ *  e.g. // private DLL "libpng13gx.dll"
+ *       #define PNG_USER_DLLFNAME_POSTFIX "gx"
+ * 
+ * The following macros are also at your disposal if you want to complete the 
+ * DLL VERSIONINFO structure.
+ * - PNG_USER_VERSIONINFO_COMMENTS
+ * - PNG_USER_VERSIONINFO_COMPANYNAME
+ * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
+ */
+
+#ifdef __STDC__
+#ifdef SPECIALBUILD
+#  pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
+ are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
+#endif
+
+#ifdef PRIVATEBUILD
+# pragma message("PRIVATEBUILD is deprecated. Use\
+ PNG_USER_PRIVATEBUILD instead.")
+# define PNG_USER_PRIVATEBUILD PRIVATEBUILD
+#endif
+#endif /* __STDC__ */
+
+#ifndef PNG_VERSION_INFO_ONLY
+
+/* End of material added to libpng-1.2.8 */
+
+/* This is the size of the compression buffer, and thus the size of
+ * an IDAT chunk.  Make this whatever size you feel is best for your
+ * machine.  One of these will be allocated per png_struct.  When this
+ * is full, it writes the data to the disk, and does some other
+ * calculations.  Making this an extremely small size will slow
+ * the library down, but you may want to experiment to determine
+ * where it becomes significant, if you are concerned with memory
+ * usage.  Note that zlib allocates at least 32Kb also.  For readers,
+ * this describes the size of the buffer available to read the data in.
+ * Unless this gets smaller than the size of a row (compressed),
+ * it should not make much difference how big this is.
+ */
+
+#ifndef PNG_ZBUF_SIZE
+#  define PNG_ZBUF_SIZE 8192
+#endif
+
+/* Enable if you want a write-only libpng */
+
+#ifndef PNG_NO_READ_SUPPORTED
+#  define PNG_READ_SUPPORTED
+#endif
+
+/* Enable if you want a read-only libpng */
+
+#ifndef PNG_NO_WRITE_SUPPORTED
+#  define PNG_WRITE_SUPPORTED
+#endif
+
+/* Enabled by default in 1.2.0.  You can disable this if you don't need to
+   support PNGs that are embedded in MNG datastreams */
+#if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
+#  ifndef PNG_MNG_FEATURES_SUPPORTED
+#    define PNG_MNG_FEATURES_SUPPORTED
+#  endif
+#endif
+
+#ifndef PNG_NO_FLOATING_POINT_SUPPORTED
+#  ifndef PNG_FLOATING_POINT_SUPPORTED
+#    define PNG_FLOATING_POINT_SUPPORTED
+#  endif
+#endif
+
+/* If you are running on a machine where you cannot allocate more
+ * than 64K of memory at once, uncomment this.  While libpng will not
+ * normally need that much memory in a chunk (unless you load up a very
+ * large file), zlib needs to know how big of a chunk it can use, and
+ * libpng thus makes sure to check any memory allocation to verify it
+ * will fit into memory.
+#define PNG_MAX_MALLOC_64K
+ */
+#if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
+#  define PNG_MAX_MALLOC_64K
+#endif
+
+/* Special munging to support doing things the 'cygwin' way:
+ * 'Normal' png-on-win32 defines/defaults:
+ *   PNG_BUILD_DLL -- building dll
+ *   PNG_USE_DLL   -- building an application, linking to dll
+ *   (no define)   -- building static library, or building an
+ *                    application and linking to the static lib
+ * 'Cygwin' defines/defaults:
+ *   PNG_BUILD_DLL -- (ignored) building the dll
+ *   (no define)   -- (ignored) building an application, linking to the dll
+ *   PNG_STATIC    -- (ignored) building the static lib, or building an 
+ *                    application that links to the static lib.
+ *   ALL_STATIC    -- (ignored) building various static libs, or building an 
+ *                    application that links to the static libs.
+ * Thus,
+ * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
+ * this bit of #ifdefs will define the 'correct' config variables based on
+ * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
+ * unnecessary.
+ *
+ * Also, the precedence order is:
+ *   ALL_STATIC (since we can't #undef something outside our namespace)
+ *   PNG_BUILD_DLL
+ *   PNG_STATIC
+ *   (nothing) == PNG_USE_DLL
+ * 
+ * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
+ *   of auto-import in binutils, we no longer need to worry about 
+ *   __declspec(dllexport) / __declspec(dllimport) and friends.  Therefore,
+ *   we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
+ *   to __declspec() stuff.  However, we DO need to worry about 
+ *   PNG_BUILD_DLL and PNG_STATIC because those change some defaults
+ *   such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
+ */
+#if defined(__CYGWIN__)
+#  if defined(ALL_STATIC)
+#    if defined(PNG_BUILD_DLL)
+#      undef PNG_BUILD_DLL
+#    endif
+#    if defined(PNG_USE_DLL)
+#      undef PNG_USE_DLL
+#    endif
+#    if defined(PNG_DLL)
+#      undef PNG_DLL
+#    endif
+#    if !defined(PNG_STATIC)
+#      define PNG_STATIC
+#    endif
+#  else
+#    if defined (PNG_BUILD_DLL)
+#      if defined(PNG_STATIC)
+#        undef PNG_STATIC
+#      endif
+#      if defined(PNG_USE_DLL)
+#        undef PNG_USE_DLL
+#      endif
+#      if !defined(PNG_DLL)
+#        define PNG_DLL
+#      endif
+#    else
+#      if defined(PNG_STATIC)
+#        if defined(PNG_USE_DLL)
+#          undef PNG_USE_DLL
+#        endif
+#        if defined(PNG_DLL)
+#          undef PNG_DLL
+#        endif
+#      else
+#        if !defined(PNG_USE_DLL)
+#          define PNG_USE_DLL
+#        endif
+#        if !defined(PNG_DLL)
+#          define PNG_DLL
+#        endif
+#      endif  
+#    endif  
+#  endif
+#endif
+
+/* This protects us against compilers that run on a windowing system
+ * and thus don't have or would rather us not use the stdio types:
+ * stdin, stdout, and stderr.  The only one currently used is stderr
+ * in png_error() and png_warning().  #defining PNG_NO_CONSOLE_IO will
+ * prevent these from being compiled and used. #defining PNG_NO_STDIO
+ * will also prevent these, plus will prevent the entire set of stdio
+ * macros and functions (FILE *, printf, etc.) from being compiled and used,
+ * unless (PNG_DEBUG > 0) has been #defined.
+ *
+ * #define PNG_NO_CONSOLE_IO
+ * #define PNG_NO_STDIO
+ */
+
+#if defined(_WIN32_WCE)
+#  include <windows.h>
+   /* Console I/O functions are not supported on WindowsCE */
+#  define PNG_NO_CONSOLE_IO
+#  ifdef PNG_DEBUG
+#    undef PNG_DEBUG
+#  endif
+#endif
+
+#ifdef PNG_BUILD_DLL
+#  ifndef PNG_CONSOLE_IO_SUPPORTED
+#    ifndef PNG_NO_CONSOLE_IO
+#      define PNG_NO_CONSOLE_IO
+#    endif
+#  endif
+#endif
+
+#  ifdef PNG_NO_STDIO
+#    ifndef PNG_NO_CONSOLE_IO
+#      define PNG_NO_CONSOLE_IO
+#    endif
+#    ifdef PNG_DEBUG
+#      if (PNG_DEBUG > 0)
+#        include <stdio.h>
+#      endif
+#    endif
+#  else
+#    if !defined(_WIN32_WCE)
+/* "stdio.h" functions are not supported on WindowsCE */
+#      include <stdio.h>
+#    endif
+#  endif
+
+/* This macro protects us against machines that don't have function
+ * prototypes (ie K&R style headers).  If your compiler does not handle
+ * function prototypes, define this macro and use the included ansi2knr.
+ * I've always been able to use _NO_PROTO as the indicator, but you may
+ * need to drag the empty declaration out in front of here, or change the
+ * ifdef to suit your own needs.
+ */
+#ifndef PNGARG
+
+#ifdef OF /* zlib prototype munger */
+#  define PNGARG(arglist) OF(arglist)
+#else
+
+#ifdef _NO_PROTO
+#  define PNGARG(arglist) ()
+#  ifndef PNG_TYPECAST_NULL
+#     define PNG_TYPECAST_NULL
+#  endif
+#else
+#  define PNGARG(arglist) arglist
+#endif /* _NO_PROTO */
+
+#endif /* OF */
+
+#endif /* PNGARG */
+
+/* Try to determine if we are compiling on a Mac.  Note that testing for
+ * just __MWERKS__ is not good enough, because the Codewarrior is now used
+ * on non-Mac platforms.
+ */
+#ifndef MACOS
+#  if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
+      defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
+#    define MACOS
+#  endif
+#endif
+
+/* enough people need this for various reasons to include it here */
+#if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
+#  include <sys/types.h>
+#endif
+
+#if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
+#  define PNG_SETJMP_SUPPORTED
+#endif
+
+#ifdef PNG_SETJMP_SUPPORTED
+/* This is an attempt to force a single setjmp behaviour on Linux.  If
+ * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
+ */
+
+#  ifdef __linux__
+#    ifdef _BSD_SOURCE
+#      define PNG_SAVE_BSD_SOURCE
+#      undef _BSD_SOURCE
+#    endif
+#    ifdef _SETJMP_H
+     /* If you encounter a compiler error here, see the explanation
+      * near the end of INSTALL.
+      */
+         __png.h__ already includes setjmp.h;
+         __dont__ include it again.;
+#    endif
+#  endif /* __linux__ */
+
+   /* include setjmp.h for error handling */
+#  include <setjmp.h>
+
+#  ifdef __linux__
+#    ifdef PNG_SAVE_BSD_SOURCE
+#      define _BSD_SOURCE
+#      undef PNG_SAVE_BSD_SOURCE
+#    endif
+#  endif /* __linux__ */
+#endif /* PNG_SETJMP_SUPPORTED */
+
+#ifdef BSD
+#  include <strings.h>
+#else
+#  include <string.h>
+#endif
+
+/* Other defines for things like memory and the like can go here.  */
+#ifdef PNG_INTERNAL
+
+#include <stdlib.h>
+
+/* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
+ * aren't usually used outside the library (as far as I know), so it is
+ * debatable if they should be exported at all.  In the future, when it is
+ * possible to have run-time registry of chunk-handling functions, some of
+ * these will be made available again.
+#define PNG_EXTERN extern
+ */
+#define PNG_EXTERN
+
+/* Other defines specific to compilers can go here.  Try to keep
+ * them inside an appropriate ifdef/endif pair for portability.
+ */
+
+#if defined(PNG_FLOATING_POINT_SUPPORTED)
+#  if defined(MACOS)
+     /* We need to check that <math.h> hasn't already been included earlier
+      * as it seems it doesn't agree with <fp.h>, yet we should really use
+      * <fp.h> if possible.
+      */
+#    if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
+#      include <fp.h>
+#    endif
+#  else
+#    include <math.h>
+#  endif
+#  if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
+     /* Amiga SAS/C: We must include builtin FPU functions when compiling using
+      * MATH=68881
+      */
+#    include <m68881.h>
+#  endif
+#endif
+
+/* Codewarrior on NT has linking problems without this. */
+#if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
+#  define PNG_ALWAYS_EXTERN
+#endif
+
+/* This provides the non-ANSI (far) memory allocation routines. */
+#if defined(__TURBOC__) && defined(__MSDOS__)
+#  include <mem.h>
+#  include <alloc.h>
+#endif
+
+/* I have no idea why is this necessary... */
+#if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
+    defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
+#  include <malloc.h>
+#endif
+
+/* This controls how fine the dithering gets.  As this allocates
+ * a largish chunk of memory (32K), those who are not as concerned
+ * with dithering quality can decrease some or all of these.
+ */
+#ifndef PNG_DITHER_RED_BITS
+#  define PNG_DITHER_RED_BITS 5
+#endif
+#ifndef PNG_DITHER_GREEN_BITS
+#  define PNG_DITHER_GREEN_BITS 5
+#endif
+#ifndef PNG_DITHER_BLUE_BITS
+#  define PNG_DITHER_BLUE_BITS 5
+#endif
+
+/* This controls how fine the gamma correction becomes when you
+ * are only interested in 8 bits anyway.  Increasing this value
+ * results in more memory being used, and more pow() functions
+ * being called to fill in the gamma tables.  Don't set this value
+ * less then 8, and even that may not work (I haven't tested it).
+ */
+
+#ifndef PNG_MAX_GAMMA_8
+#  define PNG_MAX_GAMMA_8 11
+#endif
+
+/* This controls how much a difference in gamma we can tolerate before
+ * we actually start doing gamma conversion.
+ */
+#ifndef PNG_GAMMA_THRESHOLD
+#  define PNG_GAMMA_THRESHOLD 0.05
+#endif
+
+#endif /* PNG_INTERNAL */
+
+/* The following uses const char * instead of char * for error
+ * and warning message functions, so some compilers won't complain.
+ * If you do not want to use const, define PNG_NO_CONST here.
+ */
+
+#ifndef PNG_NO_CONST
+#  define PNG_CONST const
+#else
+#  define PNG_CONST
+#endif
+
+/* The following defines give you the ability to remove code from the
+ * library that you will not be using.  I wish I could figure out how to
+ * automate this, but I can't do that without making it seriously hard
+ * on the users.  So if you are not using an ability, change the #define
+ * to and #undef, and that part of the library will not be compiled.  If
+ * your linker can't find a function, you may want to make sure the
+ * ability is defined here.  Some of these depend upon some others being
+ * defined.  I haven't figured out all the interactions here, so you may
+ * have to experiment awhile to get everything to compile.  If you are
+ * creating or using a shared library, you probably shouldn't touch this,
+ * as it will affect the size of the structures, and this will cause bad
+ * things to happen if the library and/or application ever change.
+ */
+
+/* Any features you will not be using can be undef'ed here */
+
+/* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
+ * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
+ * on the compile line, then pick and choose which ones to define without
+ * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
+ * if you only want to have a png-compliant reader/writer but don't need
+ * any of the extra transformations.  This saves about 80 kbytes in a
+ * typical installation of the library. (PNG_NO_* form added in version
+ * 1.0.1c, for consistency)
+ */
+
+/* The size of the png_text structure changed in libpng-1.0.6 when
+ * iTXt is supported.  It is turned off by default, to support old apps
+ * that malloc the png_text structure instead of calling png_set_text()
+ * and letting libpng malloc it.  It will be turned on by default in
+ * libpng-1.3.0.
+ */
+
+#ifndef PNG_iTXt_SUPPORTED
+#  if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
+#    define PNG_NO_READ_iTXt
+#  endif
+#  if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
+#    define PNG_NO_WRITE_iTXt
+#  endif
+#endif
+
+/* The following support, added after version 1.0.0, can be turned off here en
+ * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
+ * with old applications that require the length of png_struct and png_info
+ * to remain unchanged.
+ */
+
+#ifdef PNG_LEGACY_SUPPORTED
+#  define PNG_NO_FREE_ME
+#  define PNG_NO_READ_UNKNOWN_CHUNKS
+#  define PNG_NO_WRITE_UNKNOWN_CHUNKS
+#  define PNG_NO_READ_USER_CHUNKS
+#  define PNG_NO_READ_iCCP
+#  define PNG_NO_WRITE_iCCP
+#  define PNG_NO_READ_iTXt
+#  define PNG_NO_WRITE_iTXt
+#  define PNG_NO_READ_sCAL
+#  define PNG_NO_WRITE_sCAL
+#  define PNG_NO_READ_sPLT
+#  define PNG_NO_WRITE_sPLT
+#  define PNG_NO_INFO_IMAGE
+#  define PNG_NO_READ_RGB_TO_GRAY
+#  define PNG_NO_READ_USER_TRANSFORM
+#  define PNG_NO_WRITE_USER_TRANSFORM
+#  define PNG_NO_USER_MEM
+#  define PNG_NO_READ_EMPTY_PLTE
+#  define PNG_NO_MNG_FEATURES
+#  define PNG_NO_FIXED_POINT_SUPPORTED
+#endif
+
+/* Ignore attempt to turn off both floating and fixed point support */
+#if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
+    !defined(PNG_NO_FIXED_POINT_SUPPORTED)
+#  define PNG_FIXED_POINT_SUPPORTED
+#endif
+
+#ifndef PNG_NO_FREE_ME
+#  define PNG_FREE_ME_SUPPORTED
+#endif
+
+#if defined(PNG_READ_SUPPORTED)
+
+#if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
+      !defined(PNG_NO_READ_TRANSFORMS)
+#  define PNG_READ_TRANSFORMS_SUPPORTED
+#endif
+
+#ifdef PNG_READ_TRANSFORMS_SUPPORTED
+#  ifndef PNG_NO_READ_EXPAND
+#    define PNG_READ_EXPAND_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SHIFT
+#    define PNG_READ_SHIFT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_PACK
+#    define PNG_READ_PACK_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_BGR
+#    define PNG_READ_BGR_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SWAP
+#    define PNG_READ_SWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_PACKSWAP
+#    define PNG_READ_PACKSWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_INVERT
+#    define PNG_READ_INVERT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_DITHER
+#    define PNG_READ_DITHER_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_BACKGROUND
+#    define PNG_READ_BACKGROUND_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_16_TO_8
+#    define PNG_READ_16_TO_8_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_FILLER
+#    define PNG_READ_FILLER_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_GAMMA
+#    define PNG_READ_GAMMA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_GRAY_TO_RGB
+#    define PNG_READ_GRAY_TO_RGB_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_SWAP_ALPHA
+#    define PNG_READ_SWAP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_INVERT_ALPHA
+#    define PNG_READ_INVERT_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_STRIP_ALPHA
+#    define PNG_READ_STRIP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_USER_TRANSFORM
+#    define PNG_READ_USER_TRANSFORM_SUPPORTED
+#  endif
+#  ifndef PNG_NO_READ_RGB_TO_GRAY
+#    define PNG_READ_RGB_TO_GRAY_SUPPORTED
+#  endif
+#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
+
+#if !defined(PNG_NO_PROGRESSIVE_READ) && \
+ !defined(PNG_PROGRESSIVE_READ_NOT_SUPPORTED)  /* if you don't do progressive */
+#  define PNG_PROGRESSIVE_READ_SUPPORTED     /* reading.  This is not talking */
+#endif                               /* about interlacing capability!  You'll */
+              /* still have interlacing unless you change the following line: */
+
+#define PNG_READ_INTERLACING_SUPPORTED /* required for PNG-compliant decoders */
+
+#ifndef PNG_NO_READ_COMPOSITE_NODIV
+#  ifndef PNG_NO_READ_COMPOSITED_NODIV  /* libpng-1.0.x misspelling */
+#    define PNG_READ_COMPOSITE_NODIV_SUPPORTED   /* well tested on Intel, SGI */
+#  endif
+#endif
+
+/* Deprecated, will be removed from version 2.0.0.
+   Use PNG_MNG_FEATURES_SUPPORTED instead. */
+#ifndef PNG_NO_READ_EMPTY_PLTE
+#  define PNG_READ_EMPTY_PLTE_SUPPORTED
+#endif
+
+#endif /* PNG_READ_SUPPORTED */
+
+#if defined(PNG_WRITE_SUPPORTED)
+
+# if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_WRITE_TRANSFORMS)
+#  define PNG_WRITE_TRANSFORMS_SUPPORTED
+#endif
+
+#ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
+#  ifndef PNG_NO_WRITE_SHIFT
+#    define PNG_WRITE_SHIFT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_PACK
+#    define PNG_WRITE_PACK_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_BGR
+#    define PNG_WRITE_BGR_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_SWAP
+#    define PNG_WRITE_SWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_PACKSWAP
+#    define PNG_WRITE_PACKSWAP_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_INVERT
+#    define PNG_WRITE_INVERT_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_FILLER
+#    define PNG_WRITE_FILLER_SUPPORTED   /* same as WRITE_STRIP_ALPHA */
+#  endif
+#  ifndef PNG_NO_WRITE_SWAP_ALPHA
+#    define PNG_WRITE_SWAP_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_INVERT_ALPHA
+#    define PNG_WRITE_INVERT_ALPHA_SUPPORTED
+#  endif
+#  ifndef PNG_NO_WRITE_USER_TRANSFORM
+#    define PNG_WRITE_USER_TRANSFORM_SUPPORTED
+#  endif
+#endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
+
+#define PNG_WRITE_INTERLACING_SUPPORTED  /* not required for PNG-compliant
+                                            encoders, but can cause trouble
+                                            if left undefined */
+
+#if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
+     defined(PNG_FLOATING_POINT_SUPPORTED)
+#  define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
+#endif
+
+#ifndef PNG_NO_WRITE_FLUSH
+#  define PNG_WRITE_FLUSH_SUPPORTED
+#endif
+
+/* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
+#ifndef PNG_NO_WRITE_EMPTY_PLTE
+#  define PNG_WRITE_EMPTY_PLTE_SUPPORTED
+#endif
+
+#endif /* PNG_WRITE_SUPPORTED */
+
+#ifndef PNG_1_0_X
+#  ifndef PNG_NO_ERROR_NUMBERS
+#    define PNG_ERROR_NUMBERS_SUPPORTED
+#  endif
+#endif /* PNG_1_0_X */
+
+#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
+    defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
+#  ifndef PNG_NO_USER_TRANSFORM_PTR
+#    define PNG_USER_TRANSFORM_PTR_SUPPORTED
+#  endif
+#endif
+
+#ifndef PNG_NO_STDIO
+#  define PNG_TIME_RFC1123_SUPPORTED
+#endif
+
+/* This adds extra functions in pngget.c for accessing data from the
+ * info pointer (added in version 0.99)
+ * png_get_image_width()
+ * png_get_image_height()
+ * png_get_bit_depth()
+ * png_get_color_type()
+ * png_get_compression_type()
+ * png_get_filter_type()
+ * png_get_interlace_type()
+ * png_get_pixel_aspect_ratio()
+ * png_get_pixels_per_meter()
+ * png_get_x_offset_pixels()
+ * png_get_y_offset_pixels()
+ * png_get_x_offset_microns()
+ * png_get_y_offset_microns()
+ */
+#if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
+#  define PNG_EASY_ACCESS_SUPPORTED
+#endif
+
+/* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0 
+   even when PNG_USE_PNGVCRD or PNG_USE_PNGGCCRD is not defined */
+#if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
+#  ifndef PNG_ASSEMBLER_CODE_SUPPORTED
+#    define PNG_ASSEMBLER_CODE_SUPPORTED
+#  endif
+#  if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
+#    define PNG_MMX_CODE_SUPPORTED
+#  endif
+#endif
+
+/* If you are sure that you don't need thread safety and you are compiling
+   with PNG_USE_PNGCCRD for an MMX application, you can define this for
+   faster execution.  See pnggccrd.c.
+#define PNG_THREAD_UNSAFE_OK
+*/
+
+#if !defined(PNG_1_0_X)
+#if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
+#  define PNG_USER_MEM_SUPPORTED
+#endif
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.2.6 */
+#if !defined(PNG_1_0_X)
+#ifndef PNG_SET_USER_LIMITS_SUPPORTED
+#if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
+#  define PNG_SET_USER_LIMITS_SUPPORTED
+#endif
+#endif
+#endif /* PNG_1_0_X */
+
+/* Added at libpng-1.0.16 and 1.2.6.  To accept all valid PNGS no matter
+ * how large, set these limits to 0x7fffffffL
+ */
+#ifndef PNG_USER_WIDTH_MAX
+#  define PNG_USER_WIDTH_MAX 1000000L
+#endif
+#ifndef PNG_USER_HEIGHT_MAX
+#  define PNG_USER_HEIGHT_MAX 1000000L
+#endif
+
+/* These are currently experimental features, define them if you want */
+
+/* very little testing */
+/*
+#ifdef PNG_READ_SUPPORTED
+#  ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
+#    define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
+#  endif
+#endif
+*/
+
+/* This is only for PowerPC big-endian and 680x0 systems */
+/* some testing */
+/*
+#ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
+#  define PNG_READ_BIG_ENDIAN_SUPPORTED
+#endif
+*/
+
+/* Buggy compilers (e.g., gcc 2.7.2.2) need this */
+/*
+#define PNG_NO_POINTER_INDEXING
+*/
+
+/* These functions are turned off by default, as they will be phased out. */
+/*
+#define  PNG_USELESS_TESTS_SUPPORTED
+#define  PNG_CORRECT_PALETTE_SUPPORTED
+*/
+
+/* Any chunks you are not interested in, you can undef here.  The
+ * ones that allocate memory may be expecially important (hIST,
+ * tEXt, zTXt, tRNS, pCAL).  Others will just save time and make png_info
+ * a bit smaller.
+ */
+
+#if defined(PNG_READ_SUPPORTED) && \
+    !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
+#  define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
+#endif
+
+#if defined(PNG_WRITE_SUPPORTED) && \
+    !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
+    !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
+#  define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
+#endif
+
+#ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
+
+#ifdef PNG_NO_READ_TEXT
+#  define PNG_NO_READ_iTXt
+#  define PNG_NO_READ_tEXt
+#  define PNG_NO_READ_zTXt
+#endif
+#ifndef PNG_NO_READ_bKGD
+#  define PNG_READ_bKGD_SUPPORTED
+#  define PNG_bKGD_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_cHRM
+#  define PNG_READ_cHRM_SUPPORTED
+#  define PNG_cHRM_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_gAMA
+#  define PNG_READ_gAMA_SUPPORTED
+#  define PNG_gAMA_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_hIST
+#  define PNG_READ_hIST_SUPPORTED
+#  define PNG_hIST_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_iCCP
+#  define PNG_READ_iCCP_SUPPORTED
+#  define PNG_iCCP_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_iTXt
+#  ifndef PNG_READ_iTXt_SUPPORTED
+#    define PNG_READ_iTXt_SUPPORTED
+#  endif
+#  ifndef PNG_iTXt_SUPPORTED
+#    define PNG_iTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_READ_oFFs
+#  define PNG_READ_oFFs_SUPPORTED
+#  define PNG_oFFs_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_pCAL
+#  define PNG_READ_pCAL_SUPPORTED
+#  define PNG_pCAL_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sCAL
+#  define PNG_READ_sCAL_SUPPORTED
+#  define PNG_sCAL_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_pHYs
+#  define PNG_READ_pHYs_SUPPORTED
+#  define PNG_pHYs_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sBIT
+#  define PNG_READ_sBIT_SUPPORTED
+#  define PNG_sBIT_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sPLT
+#  define PNG_READ_sPLT_SUPPORTED
+#  define PNG_sPLT_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_sRGB
+#  define PNG_READ_sRGB_SUPPORTED
+#  define PNG_sRGB_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tEXt
+#  define PNG_READ_tEXt_SUPPORTED
+#  define PNG_tEXt_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tIME
+#  define PNG_READ_tIME_SUPPORTED
+#  define PNG_tIME_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_tRNS
+#  define PNG_READ_tRNS_SUPPORTED
+#  define PNG_tRNS_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_zTXt
+#  define PNG_READ_zTXt_SUPPORTED
+#  define PNG_zTXt_SUPPORTED
+#endif
+#ifndef PNG_NO_READ_UNKNOWN_CHUNKS
+#  define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
+#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
+#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
+#  endif
+#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
+#    define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#  endif
+#endif
+#if !defined(PNG_NO_READ_USER_CHUNKS) && \
+     defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
+#  define PNG_READ_USER_CHUNKS_SUPPORTED
+#  define PNG_USER_CHUNKS_SUPPORTED
+#  ifdef PNG_NO_READ_UNKNOWN_CHUNKS
+#    undef PNG_NO_READ_UNKNOWN_CHUNKS
+#  endif
+#  ifdef PNG_NO_HANDLE_AS_UNKNOWN
+#    undef PNG_NO_HANDLE_AS_UNKNOWN
+#  endif
+#endif
+#ifndef PNG_NO_READ_OPT_PLTE
+#  define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
+#endif                      /* optional PLTE chunk in RGB and RGBA images */
+#if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
+    defined(PNG_READ_zTXt_SUPPORTED)
+#  define PNG_READ_TEXT_SUPPORTED
+#  define PNG_TEXT_SUPPORTED
+#endif
+
+#endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
+
+#ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
+
+#ifdef PNG_NO_WRITE_TEXT
+#  define PNG_NO_WRITE_iTXt
+#  define PNG_NO_WRITE_tEXt
+#  define PNG_NO_WRITE_zTXt
+#endif
+#ifndef PNG_NO_WRITE_bKGD
+#  define PNG_WRITE_bKGD_SUPPORTED
+#  ifndef PNG_bKGD_SUPPORTED
+#    define PNG_bKGD_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_cHRM
+#  define PNG_WRITE_cHRM_SUPPORTED
+#  ifndef PNG_cHRM_SUPPORTED
+#    define PNG_cHRM_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_gAMA
+#  define PNG_WRITE_gAMA_SUPPORTED
+#  ifndef PNG_gAMA_SUPPORTED
+#    define PNG_gAMA_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_hIST
+#  define PNG_WRITE_hIST_SUPPORTED
+#  ifndef PNG_hIST_SUPPORTED
+#    define PNG_hIST_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_iCCP
+#  define PNG_WRITE_iCCP_SUPPORTED
+#  ifndef PNG_iCCP_SUPPORTED
+#    define PNG_iCCP_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_iTXt
+#  ifndef PNG_WRITE_iTXt_SUPPORTED
+#    define PNG_WRITE_iTXt_SUPPORTED
+#  endif
+#  ifndef PNG_iTXt_SUPPORTED
+#    define PNG_iTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_oFFs
+#  define PNG_WRITE_oFFs_SUPPORTED
+#  ifndef PNG_oFFs_SUPPORTED
+#    define PNG_oFFs_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_pCAL
+#  define PNG_WRITE_pCAL_SUPPORTED
+#  ifndef PNG_pCAL_SUPPORTED
+#    define PNG_pCAL_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sCAL
+#  define PNG_WRITE_sCAL_SUPPORTED
+#  ifndef PNG_sCAL_SUPPORTED
+#    define PNG_sCAL_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_pHYs
+#  define PNG_WRITE_pHYs_SUPPORTED
+#  ifndef PNG_pHYs_SUPPORTED
+#    define PNG_pHYs_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sBIT
+#  define PNG_WRITE_sBIT_SUPPORTED
+#  ifndef PNG_sBIT_SUPPORTED
+#    define PNG_sBIT_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sPLT
+#  define PNG_WRITE_sPLT_SUPPORTED
+#  ifndef PNG_sPLT_SUPPORTED
+#    define PNG_sPLT_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_sRGB
+#  define PNG_WRITE_sRGB_SUPPORTED
+#  ifndef PNG_sRGB_SUPPORTED
+#    define PNG_sRGB_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tEXt
+#  define PNG_WRITE_tEXt_SUPPORTED
+#  ifndef PNG_tEXt_SUPPORTED
+#    define PNG_tEXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tIME
+#  define PNG_WRITE_tIME_SUPPORTED
+#  ifndef PNG_tIME_SUPPORTED
+#    define PNG_tIME_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_tRNS
+#  define PNG_WRITE_tRNS_SUPPORTED
+#  ifndef PNG_tRNS_SUPPORTED
+#    define PNG_tRNS_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_zTXt
+#  define PNG_WRITE_zTXt_SUPPORTED
+#  ifndef PNG_zTXt_SUPPORTED
+#    define PNG_zTXt_SUPPORTED
+#  endif
+#endif
+#ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
+#  define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
+#  ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
+#    define PNG_UNKNOWN_CHUNKS_SUPPORTED
+#  endif
+#  ifndef PNG_NO_HANDLE_AS_UNKNOWN
+#     ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#       define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#     endif
+#  endif
+#endif
+#if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
+    defined(PNG_WRITE_zTXt_SUPPORTED)
+#  define PNG_WRITE_TEXT_SUPPORTED
+#  ifndef PNG_TEXT_SUPPORTED
+#    define PNG_TEXT_SUPPORTED
+#  endif
+#endif
+
+#endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
+
+/* Turn this off to disable png_read_png() and
+ * png_write_png() and leave the row_pointers member
+ * out of the info structure.
+ */
+#ifndef PNG_NO_INFO_IMAGE
+#  define PNG_INFO_IMAGE_SUPPORTED
+#endif
+
+/* need the time information for reading tIME chunks */
+#if defined(PNG_tIME_SUPPORTED)
+#  if !defined(_WIN32_WCE)
+     /* "time.h" functions are not supported on WindowsCE */
+#    include <time.h>
+#  endif
+#endif
+
+/* Some typedefs to get us started.  These should be safe on most of the
+ * common platforms.  The typedefs should be at least as large as the
+ * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
+ * don't have to be exactly that size.  Some compilers dislike passing
+ * unsigned shorts as function parameters, so you may be better off using
+ * unsigned int for png_uint_16.  Likewise, for 64-bit systems, you may
+ * want to have unsigned int for png_uint_32 instead of unsigned long.
+ */
+
+typedef unsigned long png_uint_32;
+typedef long png_int_32;
+typedef unsigned short png_uint_16;
+typedef short png_int_16;
+typedef unsigned char png_byte;
+
+/* This is usually size_t.  It is typedef'ed just in case you need it to
+   change (I'm not sure if you will or not, so I thought I'd be safe) */
+#ifdef PNG_SIZE_T
+   typedef PNG_SIZE_T png_size_t;
+#  define png_sizeof(x) png_convert_size(sizeof (x))
+#else
+   typedef size_t png_size_t;
+#  define png_sizeof(x) sizeof (x)
+#endif
+
+/* The following is needed for medium model support.  It cannot be in the
+ * PNG_INTERNAL section.  Needs modification for other compilers besides
+ * MSC.  Model independent support declares all arrays and pointers to be
+ * large using the far keyword.  The zlib version used must also support
+ * model independent data.  As of version zlib 1.0.4, the necessary changes
+ * have been made in zlib.  The USE_FAR_KEYWORD define triggers other
+ * changes that are needed. (Tim Wegner)
+ */
+
+/* Separate compiler dependencies (problem here is that zlib.h always
+   defines FAR. (SJT) */
+#ifdef __BORLANDC__
+#  if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
+#    define LDATA 1
+#  else
+#    define LDATA 0
+#  endif
+   /* GRR:  why is Cygwin in here?  Cygwin is not Borland C... */
+#  if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
+#    define PNG_MAX_MALLOC_64K
+#    if (LDATA != 1)
+#      ifndef FAR
+#        define FAR __far
+#      endif
+#      define USE_FAR_KEYWORD
+#    endif   /* LDATA != 1 */
+     /* Possibly useful for moving data out of default segment.
+      * Uncomment it if you want. Could also define FARDATA as
+      * const if your compiler supports it. (SJT)
+#    define FARDATA FAR
+      */
+#  endif  /* __WIN32__, __FLAT__, __CYGWIN__ */
+#endif   /* __BORLANDC__ */
+
+
+/* Suggest testing for specific compiler first before testing for
+ * FAR.  The Watcom compiler defines both __MEDIUM__ and M_I86MM,
+ * making reliance oncertain keywords suspect. (SJT)
+ */
+
+/* MSC Medium model */
+#if defined(FAR)
+#  if defined(M_I86MM)
+#    define USE_FAR_KEYWORD
+#    define FARDATA FAR
+#    include <dos.h>
+#  endif
+#endif
+
+/* SJT: default case */
+#ifndef FAR
+#  define FAR
+#endif
+
+/* At this point FAR is always defined */
+#ifndef FARDATA
+#  define FARDATA
+#endif
+
+/* Typedef for floating-point numbers that are converted
+   to fixed-point with a multiple of 100,000, e.g., int_gamma */
+typedef png_int_32 png_fixed_point;
+
+/* Add typedefs for pointers */
+typedef void            FAR * png_voidp;
+typedef png_byte        FAR * png_bytep;
+typedef png_uint_32     FAR * png_uint_32p;
+typedef png_int_32      FAR * png_int_32p;
+typedef png_uint_16     FAR * png_uint_16p;
+typedef png_int_16      FAR * png_int_16p;
+typedef PNG_CONST char  FAR * png_const_charp;
+typedef char            FAR * png_charp;
+typedef png_fixed_point FAR * png_fixed_point_p;
+
+#ifndef PNG_NO_STDIO
+#if defined(_WIN32_WCE)
+typedef HANDLE                png_FILE_p;
+#else
+typedef FILE                * png_FILE_p;
+#endif
+#endif
+
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double          FAR * png_doublep;
+#endif
+
+/* Pointers to pointers; i.e. arrays */
+typedef png_byte        FAR * FAR * png_bytepp;
+typedef png_uint_32     FAR * FAR * png_uint_32pp;
+typedef png_int_32      FAR * FAR * png_int_32pp;
+typedef png_uint_16     FAR * FAR * png_uint_16pp;
+typedef png_int_16      FAR * FAR * png_int_16pp;
+typedef PNG_CONST char  FAR * FAR * png_const_charpp;
+typedef char            FAR * FAR * png_charpp;
+typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
+#ifdef PNG_FLOATING_POINT_SUPPORTED
+typedef double          FAR * FAR * png_doublepp;
+#endif
+
+/* Pointers to pointers to pointers; i.e., pointer to array */
+typedef char            FAR * FAR * FAR * png_charppp;
+
+#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
+/* SPC -  Is this stuff deprecated? */
+/* It'll be removed as of libpng-1.3.0 - GR-P */
+/* libpng typedefs for types in zlib. If zlib changes
+ * or another compression library is used, then change these.
+ * Eliminates need to change all the source files.
+ */
+typedef charf *         png_zcharp;
+typedef charf * FAR *   png_zcharpp;
+typedef z_stream FAR *  png_zstreamp;
+#endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
+
+/*
+ * Define PNG_BUILD_DLL if the module being built is a Windows
+ * LIBPNG DLL.
+ *
+ * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
+ * It is equivalent to Microsoft predefined macro _DLL that is
+ * automatically defined when you compile using the share
+ * version of the CRT (C Run-Time library)
+ *
+ * The cygwin mods make this behavior a little different:
+ * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
+ * Define PNG_STATIC if you are building a static library for use with cygwin,
+ *   -or- if you are building an application that you want to link to the
+ *   static library.
+ * PNG_USE_DLL is defined by default (no user action needed) unless one of
+ *   the other flags is defined.
+ */
+
+#if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
+#  define PNG_DLL
+#endif
+/* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
+ * When building a static lib, default to no GLOBAL ARRAYS, but allow
+ * command-line override
+ */
+#if defined(__CYGWIN__)
+#  if !defined(PNG_STATIC)
+#    if defined(PNG_USE_GLOBAL_ARRAYS)
+#      undef PNG_USE_GLOBAL_ARRAYS
+#    endif
+#    if !defined(PNG_USE_LOCAL_ARRAYS)
+#      define PNG_USE_LOCAL_ARRAYS
+#    endif
+#  else
+#    if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
+#      if defined(PNG_USE_GLOBAL_ARRAYS)
+#        undef PNG_USE_GLOBAL_ARRAYS
+#      endif
+#    endif
+#  endif
+#  if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
+#    define PNG_USE_LOCAL_ARRAYS
+#  endif
+#endif
+
+/* Do not use global arrays (helps with building DLL's)
+ * They are no longer used in libpng itself, since version 1.0.5c,
+ * but might be required for some pre-1.0.5c applications.
+ */
+#if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
+#  if defined(PNG_NO_GLOBAL_ARRAYS) || (defined(__GNUC__) && defined(PNG_DLL))
+#    define PNG_USE_LOCAL_ARRAYS
+#  else
+#    define PNG_USE_GLOBAL_ARRAYS
+#  endif
+#endif
+
+#if defined(__CYGWIN__)
+#  undef PNGAPI
+#  define PNGAPI __cdecl
+#  undef PNG_IMPEXP
+#  define PNG_IMPEXP
+#endif  
+
+/* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
+ * you may get warnings regarding the linkage of png_zalloc and png_zfree.
+ * Don't ignore those warnings; you must also reset the default calling
+ * convention in your compiler to match your PNGAPI, and you must build
+ * zlib and your applications the same way you build libpng.
+ */
+
+#if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
+#  ifndef PNG_NO_MODULEDEF
+#    define PNG_NO_MODULEDEF
+#  endif
+#endif
+
+#if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
+#  define PNG_IMPEXP
+#endif
+
+#if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
+    (( defined(_Windows) || defined(_WINDOWS) || \
+       defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
+
+#  ifndef PNGAPI
+#     if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
+#        define PNGAPI __cdecl
+#     else
+#        define PNGAPI _cdecl
+#     endif
+#  endif
+
+#  if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
+       0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
+#     define PNG_IMPEXP
+#  endif
+
+#  if !defined(PNG_IMPEXP)
+
+#     define PNG_EXPORT_TYPE1(type,symbol)  PNG_IMPEXP type PNGAPI symbol
+#     define PNG_EXPORT_TYPE2(type,symbol)  type PNG_IMPEXP PNGAPI symbol
+
+      /* Borland/Microsoft */
+#     if defined(_MSC_VER) || defined(__BORLANDC__)
+#        if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
+#           define PNG_EXPORT PNG_EXPORT_TYPE1
+#        else
+#           define PNG_EXPORT PNG_EXPORT_TYPE2
+#           if defined(PNG_BUILD_DLL)
+#              define PNG_IMPEXP __export
+#           else
+#              define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
+                                                 VC++ */
+#           endif                             /* Exists in Borland C++ for
+                                                 C++ classes (== huge) */
+#        endif
+#     endif
+
+#     if !defined(PNG_IMPEXP)
+#        if defined(PNG_BUILD_DLL)
+#           define PNG_IMPEXP __declspec(dllexport)
+#        else
+#           define PNG_IMPEXP __declspec(dllimport)
+#        endif
+#     endif
+#  endif  /* PNG_IMPEXP */
+#else /* !(DLL || non-cygwin WINDOWS) */
+#   if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
+#      ifndef PNGAPI
+#         define PNGAPI _System
+#      endif
+#   else
+#      if 0 /* ... other platforms, with other meanings */
+#      endif
+#   endif
+#endif
+
+#ifndef PNGAPI
+#  define PNGAPI
+#endif
+#ifndef PNG_IMPEXP
+#  define PNG_IMPEXP
+#endif
+
+#ifdef PNG_BUILDSYMS
+#  ifndef PNG_EXPORT
+#    define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
+#  endif
+#  ifdef PNG_USE_GLOBAL_ARRAYS
+#    ifndef PNG_EXPORT_VAR
+#      define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
+#    endif
+#  endif
+#endif
+
+#ifndef PNG_EXPORT
+#  define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
+#endif
+
+#ifdef PNG_USE_GLOBAL_ARRAYS
+#  ifndef PNG_EXPORT_VAR
+#    define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
+#  endif
+#endif
+
+/* User may want to use these so they are not in PNG_INTERNAL. Any library
+ * functions that are passed far data must be model independent.
+ */
+
+#ifndef PNG_ABORT
+#  define PNG_ABORT() abort()
+#endif
+
+#ifdef PNG_SETJMP_SUPPORTED
+#  define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
+#else
+#  define png_jmpbuf(png_ptr) \
+   (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
+#endif
+
+#if defined(USE_FAR_KEYWORD)  /* memory model independent fns */
+/* use this to make far-to-near assignments */
+#  define CHECK   1
+#  define NOCHECK 0
+#  define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
+#  define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
+#  define png_strcpy  _fstrcpy
+#  define png_strncpy _fstrncpy   /* Added to v 1.2.6 */
+#  define png_strlen  _fstrlen
+#  define png_memcmp  _fmemcmp    /* SJT: added */
+#  define png_memcpy  _fmemcpy
+#  define png_memset  _fmemset
+#else /* use the usual functions */
+#  define CVT_PTR(ptr)         (ptr)
+#  define CVT_PTR_NOCHECK(ptr) (ptr)
+#  define png_strcpy  strcpy
+#  define png_strncpy strncpy     /* Added to v 1.2.6 */
+#  define png_strlen  strlen
+#  define png_memcmp  memcmp      /* SJT: added */
+#  define png_memcpy  memcpy
+#  define png_memset  memset
+#endif
+/* End of memory model independent support */
+
+/* Just a little check that someone hasn't tried to define something
+ * contradictory.
+ */
+#if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
+#  undef PNG_ZBUF_SIZE
+#  define PNG_ZBUF_SIZE 65536L
+#endif
+
+#ifdef PNG_READ_SUPPORTED
+/* Prior to libpng-1.0.9, this block was in pngasmrd.h */
+#if defined(PNG_INTERNAL)
+
+/* These are the default thresholds before the MMX code kicks in; if either
+ * rowbytes or bitdepth is below the threshold, plain C code is used.  These
+ * can be overridden at runtime via the png_set_mmx_thresholds() call in
+ * libpng 1.2.0 and later.  The values below were chosen by Intel.
+ */
+
+#ifndef PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT
+#  define PNG_MMX_ROWBYTES_THRESHOLD_DEFAULT  128  /*  >=  */
+#endif
+#ifndef PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT
+#  define PNG_MMX_BITDEPTH_THRESHOLD_DEFAULT  9    /*  >=  */   
+#endif
+
+/* Set this in the makefile for VC++ on Pentium, not here. */
+/* Platform must be Pentium.  Makefile must assemble and load pngvcrd.c .
+ * MMX will be detected at run time and used if present.
+ */
+#ifdef PNG_USE_PNGVCRD
+#  define PNG_HAVE_ASSEMBLER_COMBINE_ROW
+#  define PNG_HAVE_ASSEMBLER_READ_INTERLACE
+#  define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW
+#endif
+
+/* Set this in the makefile for gcc/as on Pentium, not here. */
+/* Platform must be Pentium.  Makefile must assemble and load pnggccrd.c .
+ * MMX will be detected at run time and used if present.
+ */
+#ifdef PNG_USE_PNGGCCRD
+#  define PNG_HAVE_ASSEMBLER_COMBINE_ROW
+#  define PNG_HAVE_ASSEMBLER_READ_INTERLACE
+#  define PNG_HAVE_ASSEMBLER_READ_FILTER_ROW
+#endif
+/* - see pnggccrd.c for info about what is currently enabled */
+
+#endif /* PNG_INTERNAL */
+#endif /* PNG_READ_SUPPORTED */
+
+/* Added at libpng-1.2.8 */
+#endif /* PNG_VERSION_INFO_ONLY */
+
+#endif /* PNGCONF_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/zconf.h ./aperios/include/zconf.h
--- ../Tekkotsu_2.3/aperios/include/zconf.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/zconf.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,326 @@
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2004 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id: zconf.h,v 1.2 2005/06/01 05:48:00 ejt Exp $ */
+
+#ifndef ZCONF_H
+#define ZCONF_H
+
+/*
+ * If you *really* need a unique prefix for all types and library functions,
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ */
+#ifdef Z_PREFIX
+#  define deflateInit_          z_deflateInit_
+#  define deflate               z_deflate
+#  define deflateEnd            z_deflateEnd
+#  define inflateInit_          z_inflateInit_
+#  define inflate               z_inflate
+#  define inflateEnd            z_inflateEnd
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateCopy           z_deflateCopy
+#  define deflateReset          z_deflateReset
+#  define deflateParams         z_deflateParams
+#  define deflateBound          z_deflateBound
+#  define deflatePrime          z_deflatePrime
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateCopy           z_inflateCopy
+#  define inflateReset          z_inflateReset
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define compress              z_compress
+#  define compress2             z_compress2
+#  define compressBound         z_compressBound
+#  define uncompress            z_uncompress
+#  define adler32               z_adler32
+#  define crc32                 z_crc32
+#  define get_crc_table         z_get_crc_table
+#  define zError                z_zError
+
+#  define Byte                  z_Byte
+#  define uInt                  z_uInt
+#  define uLong                 z_uLong
+#  define Bytef                 z_Bytef
+#  define charf                 z_charf
+#  define intf                  z_intf
+#  define uIntf                 z_uIntf
+#  define uLongf                z_uLongf
+#  define voidpf                z_voidpf
+#  define voidp                 z_voidp
+#endif
+
+#if defined(__MSDOS__) && !defined(MSDOS)
+#  define MSDOS
+#endif
+#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
+#  define OS2
+#endif
+#if defined(_WINDOWS) && !defined(WINDOWS)
+#  define WINDOWS
+#endif
+#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
+#  define WIN32
+#endif
+#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
+#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
+#    ifndef SYS16BIT
+#      define SYS16BIT
+#    endif
+#  endif
+#endif
+
+/*
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
+ * than 64k bytes at a time (needed on systems with 16-bit int).
+ */
+#ifdef SYS16BIT
+#  define MAXSEG_64K
+#endif
+#ifdef MSDOS
+#  define UNALIGNED_OK
+#endif
+
+#ifdef __STDC_VERSION__
+#  ifndef STDC
+#    define STDC
+#  endif
+#  if __STDC_VERSION__ >= 199901L
+#    ifndef STDC99
+#      define STDC99
+#    endif
+#  endif
+#endif
+#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
+#  define STDC
+#endif
+
+#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
+#  define STDC
+#endif
+
+#ifndef STDC
+#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+#    define const       /* note: need a more gentle solution here */
+#  endif
+#endif
+
+/* Some Mac compilers merge all .h files incorrectly: */
+#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
+#  define NO_DUMMY_DECL
+#endif
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+#  ifdef MAXSEG_64K
+#    define MAX_MEM_LEVEL 8
+#  else
+#    define MAX_MEM_LEVEL 9
+#  endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+#  define MAX_WBITS   15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+            (1 << (windowBits+2)) +  (1 << (memLevel+9))
+ that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+   The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus a few kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(args)  ()
+#  endif
+#endif
+
+/* The following definitions for FAR are needed only for MSDOS mixed
+ * model programming (small or medium model with some far allocations).
+ * This was tested only with MSC; for other MSDOS compilers you may have
+ * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
+ * just define FAR to be empty.
+ */
+#ifdef SYS16BIT
+#  if defined(M_I86SM) || defined(M_I86MM)
+     /* MSC small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef _MSC_VER
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#  if (defined(__SMALL__) || defined(__MEDIUM__))
+     /* Turbo C small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef __BORLANDC__
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#endif
+
+#if defined(WINDOWS) || defined(WIN32)
+   /* If building or using zlib as a DLL, define ZLIB_DLL.
+    * This is not mandatory, but it offers a little performance increase.
+    */
+#  ifdef ZLIB_DLL
+#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
+#      ifdef ZLIB_INTERNAL
+#        define ZEXTERN extern __declspec(dllexport)
+#      else
+#        define ZEXTERN extern __declspec(dllimport)
+#      endif
+#    endif
+#  endif  /* ZLIB_DLL */
+   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
+    * define ZLIB_WINAPI.
+    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
+    */
+#  ifdef ZLIB_WINAPI
+#    ifdef FAR
+#      undef FAR
+#    endif
+#    include <windows.h>
+     /* No need for _export, use ZLIB.DEF instead. */
+     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
+#    define ZEXPORT WINAPI
+#    ifdef WIN32
+#      define ZEXPORTVA WINAPIV
+#    else
+#      define ZEXPORTVA FAR CDECL
+#    endif
+#  endif
+#endif
+
+#if defined (__BEOS__)
+#  ifdef ZLIB_DLL
+#    ifdef ZLIB_INTERNAL
+#      define ZEXPORT   __declspec(dllexport)
+#      define ZEXPORTVA __declspec(dllexport)
+#    else
+#      define ZEXPORT   __declspec(dllimport)
+#      define ZEXPORTVA __declspec(dllimport)
+#    endif
+#  endif
+#endif
+
+#ifndef ZEXTERN
+#  define ZEXTERN extern
+#endif
+#ifndef ZEXPORT
+#  define ZEXPORT
+#endif
+#ifndef ZEXPORTVA
+#  define ZEXPORTVA
+#endif
+
+#ifndef FAR
+#  define FAR
+#endif
+
+#if !defined(__MACTYPES__)
+typedef unsigned char  Byte;  /* 8 bits */
+#endif
+typedef unsigned int   uInt;  /* 16 bits or more */
+typedef unsigned long  uLong; /* 32 bits or more */
+
+#ifdef SMALL_MEDIUM
+   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
+#  define Bytef Byte FAR
+#else
+   typedef Byte  FAR Bytef;
+#endif
+typedef char  FAR charf;
+typedef int   FAR intf;
+typedef uInt  FAR uIntf;
+typedef uLong FAR uLongf;
+
+#ifdef STDC
+   typedef void const *voidpc;
+   typedef void FAR   *voidpf;
+   typedef void       *voidp;
+#else
+   typedef Byte const *voidpc;
+   typedef Byte FAR   *voidpf;
+   typedef Byte       *voidp;
+#endif
+
+#if 1           /* HAVE_UNISTD_H -- this line is updated by ./configure */
+#  include <sys/types.h> /* for off_t */
+#  include <unistd.h>    /* for SEEK_* and off_t */
+#  ifdef VMS
+#    include <unixio.h>   /* for off_t */
+#  endif
+#  define z_off_t off_t
+#endif
+#ifndef SEEK_SET
+#  define SEEK_SET        0       /* Seek from beginning of file.  */
+#  define SEEK_CUR        1       /* Seek from current position.  */
+#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
+#endif
+#ifndef z_off_t
+#  define z_off_t long
+#endif
+
+#if defined(__OS400__)
+#  define NO_vsnprintf
+#endif
+
+#if defined(__MVS__)
+#  define NO_vsnprintf
+#  ifdef FAR
+#    undef FAR
+#  endif
+#endif
+
+/* MVS linker does not support external names larger than 8 bytes */
+#if defined(__MVS__)
+#   pragma map(deflateInit_,"DEIN")
+#   pragma map(deflateInit2_,"DEIN2")
+#   pragma map(deflateEnd,"DEEND")
+#   pragma map(deflateBound,"DEBND")
+#   pragma map(inflateInit_,"ININ")
+#   pragma map(inflateInit2_,"ININ2")
+#   pragma map(inflateEnd,"INEND")
+#   pragma map(inflateSync,"INSY")
+#   pragma map(inflateSetDictionary,"INSEDI")
+#   pragma map(compressBound,"CMBND")
+#   pragma map(inflate_table,"INTABL")
+#   pragma map(inflate_fast,"INFA")
+#   pragma map(inflate_copyright,"INCOPY")
+#endif
+
+#endif /* ZCONF_H */
diff -urdN ../Tekkotsu_2.3/aperios/include/zlib.h ./aperios/include/zlib.h
--- ../Tekkotsu_2.3/aperios/include/zlib.h	Wed Dec 31 19:00:00 1969
+++ ./aperios/include/zlib.h	Wed Jun  1 01:48:00 2005
@@ -0,0 +1,1200 @@
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+  version 1.2.2, October 3rd, 2004
+
+  Copyright (C) 1995-2004 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+
+  The data format used by the zlib library is described by RFCs (Request for
+  Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
+  (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
+*/
+
+#ifndef ZLIB_H
+#define ZLIB_H
+
+#include "zconf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ZLIB_VERSION "1.2.2"
+#define ZLIB_VERNUM 0x1220
+
+/*
+     The 'zlib' compression library provides in-memory compression and
+  decompression functions, including integrity checks of the uncompressed
+  data.  This version of the library supports only one compression method
+  (deflation) but other algorithms will be added later and will have the same
+  stream interface.
+
+     Compression can be done in a single step if the buffers are large
+  enough (for example if an input file is mmap'ed), or can be done by
+  repeated calls of the compression function.  In the latter case, the
+  application must provide more input and/or consume the output
+  (providing more output space) before each call.
+
+     The compressed data format used by default by the in-memory functions is
+  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
+  around a deflate stream, which is itself documented in RFC 1951.
+
+     The library also supports reading and writing files in gzip (.gz) format
+  with an interface similar to that of stdio using the functions that start
+  with "gz".  The gzip format is different from the zlib format.  gzip is a
+  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
+
+     This library can optionally read and write gzip streams in memory as well.
+
+     The zlib format was designed to be compact and fast for use in memory
+  and on communications channels.  The gzip format was designed for single-
+  file compression on file systems, has a larger header than zlib to maintain
+  directory information, and uses a different, slower check method than zlib.
+
+     The library does not install any signal handler. The decoder checks
+  the consistency of the compressed data, so the library should never
+  crash even in case of corrupted input.
+*/
+
+typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
+typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
+
+struct internal_state;
+
+typedef struct z_stream_s {
+    Bytef    *next_in;  /* next input byte */
+    uInt     avail_in;  /* number of bytes available at next_in */
+    uLong    total_in;  /* total nb of input bytes read so far */
+
+    Bytef    *next_out; /* next output byte should be put there */
+    uInt     avail_out; /* remaining free space at next_out */
+    uLong    total_out; /* total nb of bytes output so far */
+
+    char     *msg;      /* last error message, NULL if no error */
+    struct internal_state FAR *state; /* not visible by applications */
+
+    alloc_func zalloc;  /* used to allocate the internal state */
+    free_func  zfree;   /* used to free the internal state */
+    voidpf     opaque;  /* private data object passed to zalloc and zfree */
+
+    int     data_type;  /* best guess about the data type: ascii or binary */
+    uLong   adler;      /* adler32 value of the uncompressed data */
+    uLong   reserved;   /* reserved for future use */
+} z_stream;
+
+typedef z_stream FAR *z_streamp;
+
+/*
+   The application must update next_in and avail_in when avail_in has
+   dropped to zero. It must update next_out and avail_out when avail_out
+   has dropped to zero. The application must initialize zalloc, zfree and
+   opaque before calling the init function. All other fields are set by the
+   compression library and must not be updated by the application.
+
+   The opaque value provided by the application will be passed as the first
+   parameter for calls of zalloc and zfree. This can be useful for custom
+   memory management. The compression library attaches no meaning to the
+   opaque value.
+
+   zalloc must return Z_NULL if there is not enough memory for the object.
+   If zlib is used in a multi-threaded application, zalloc and zfree must be
+   thread safe.
+
+   On 16-bit systems, the functions zalloc and zfree must be able to allocate
+   exactly 65536 bytes, but will not be required to allocate more than this
+   if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
+   pointers returned by zalloc for objects of exactly 65536 bytes *must*
+   have their offset normalized to zero. The default allocation function
+   provided by this library ensures this (see zutil.c). To reduce memory
+   requirements and avoid any allocation of 64K objects, at the expense of
+   compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
+
+   The fields total_in and total_out can be used for statistics or
+   progress reports. After compression, total_in holds the total size of
+   the uncompressed data and may be saved for use in the decompressor
+   (particularly if the decompressor wants to decompress everything in
+   a single step).
+*/
+
+                        /* constants */
+
+#define Z_NO_FLUSH      0
+#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
+#define Z_SYNC_FLUSH    2
+#define Z_FULL_FLUSH    3
+#define Z_FINISH        4
+#define Z_BLOCK         5
+/* Allowed flush values; see deflate() and inflate() below for details */
+
+#define Z_OK            0
+#define Z_STREAM_END    1
+#define Z_NEED_DICT     2
+#define Z_ERRNO        (-1)
+#define Z_STREAM_ERROR (-2)
+#define Z_DATA_ERROR   (-3)
+#define Z_MEM_ERROR    (-4)
+#define Z_BUF_ERROR    (-5)
+#define Z_VERSION_ERROR (-6)
+/* Return codes for the compression/decompression functions. Negative
+ * values are errors, positive values are used for special but normal events.
+ */
+
+#define Z_NO_COMPRESSION         0
+#define Z_BEST_SPEED             1
+#define Z_BEST_COMPRESSION       9
+#define Z_DEFAULT_COMPRESSION  (-1)
+/* compression levels */
+
+#define Z_FILTERED            1
+#define Z_HUFFMAN_ONLY        2
+#define Z_RLE                 3
+#define Z_DEFAULT_STRATEGY    0
+/* compression strategy; see deflateInit2() below for details */
+
+#define Z_BINARY   0
+#define Z_ASCII    1
+#define Z_UNKNOWN  2
+/* Possible values of the data_type field (though see inflate()) */
+
+#define Z_DEFLATED   8
+/* The deflate compression method (the only one supported in this version) */
+
+#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
+
+#define zlib_version zlibVersion()
+/* for compatibility with versions < 1.0.2 */
+
+                        /* basic functions */
+
+ZEXTERN const char * ZEXPORT zlibVersion OF((void));
+/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+   If the first character differs, the library code actually used is
+   not compatible with the zlib.h header file used by the application.
+   This check is automatically made by deflateInit and inflateInit.
+ */
+
+/*
+ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
+
+     Initializes the internal stream state for compression. The fields
+   zalloc, zfree and opaque must be initialized before by the caller.
+   If zalloc and zfree are set to Z_NULL, deflateInit updates them to
+   use default allocation functions.
+
+     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+   1 gives best speed, 9 gives best compression, 0 gives no compression at
+   all (the input data is simply copied a block at a time).
+   Z_DEFAULT_COMPRESSION requests a default compromise between speed and
+   compression (currently equivalent to level 6).
+
+     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if level is not a valid compression level,
+   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+   with the version assumed by the caller (ZLIB_VERSION).
+   msg is set to null if there is no error message.  deflateInit does not
+   perform any compression: this will be done by deflate().
+*/
+
+
+ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
+/*
+    deflate compresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full. It may introduce some
+  output latency (reading input without producing any output) except when
+  forced to flush.
+
+    The detailed semantics are as follows. deflate performs one or both of the
+  following actions:
+
+  - Compress more input starting at next_in and update next_in and avail_in
+    accordingly. If not all input can be processed (because there is not
+    enough room in the output buffer), next_in and avail_in are updated and
+    processing will resume at this point for the next call of deflate().
+
+  - Provide more output starting at next_out and update next_out and avail_out
+    accordingly. This action is forced if the parameter flush is non zero.
+    Forcing flush frequently degrades the compression ratio, so this parameter
+    should be set only when necessary (in interactive applications).
+    Some output may be provided even if flush is not set.
+
+  Before the call of deflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming
+  more output, and updating avail_in or avail_out accordingly; avail_out
+  should never be zero before the call. The application can consume the
+  compressed output when it wants, for example when the output buffer is full
+  (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
+  and with zero avail_out, it must be called again after making room in the
+  output buffer because there might be more output pending.
+
+    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+  flushed to the output buffer and the output is aligned on a byte boundary, so
+  that the decompressor can get all input data available so far. (In particular
+  avail_in is zero after the call if enough output space has been provided
+  before the call.)  Flushing may degrade compression for some compression
+  algorithms and so it should be used only when necessary.
+
+    If flush is set to Z_FULL_FLUSH, all output is flushed as with
+  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+  restart from this point if previous compressed data has been damaged or if
+  random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
+  the compression.
+
+    If deflate returns with avail_out == 0, this function must be called again
+  with the same value of the flush parameter and more output space (updated
+  avail_out), until the flush is complete (deflate returns with non-zero
+  avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
+  avail_out is greater than six to avoid repeated flush markers due to
+  avail_out == 0 on return.
+
+    If the parameter flush is set to Z_FINISH, pending input is processed,
+  pending output is flushed and deflate returns with Z_STREAM_END if there
+  was enough output space; if deflate returns with Z_OK, this function must be
+  called again with Z_FINISH and more output space (updated avail_out) but no
+  more input data, until it returns with Z_STREAM_END or an error. After
+  deflate has returned Z_STREAM_END, the only possible operations on the
+  stream are deflateReset or deflateEnd.
+
+    Z_FINISH can be used immediately after deflateInit if all the compression
+  is to be done in a single step. In this case, avail_out must be at least
+  the value returned by deflateBound (see below). If deflate does not return
+  Z_STREAM_END, then it must be called again as described above.
+
+    deflate() sets strm->adler to the adler32 checksum of all input read
+  so far (that is, total_in bytes).
+
+    deflate() may update data_type if it can make a good guess about
+  the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
+  binary. This field is only for information purposes and does not affect
+  the compression algorithm in any manner.
+
+    deflate() returns Z_OK if some progress has been made (more input
+  processed or more output produced), Z_STREAM_END if all input has been
+  consumed and all output has been produced (only when flush is set to
+  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+  if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
+  (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
+  fatal, and deflate() can be called again with more input and more output
+  space to continue compressing.
+*/
+
+
+ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any
+   pending output.
+
+     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+   prematurely (some input or output was discarded). In the error case,
+   msg may be set but then points to a static string (which must not be
+   deallocated).
+*/
+
+
+/*
+ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
+
+     Initializes the internal stream state for decompression. The fields
+   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+   the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
+   value depends on the compression method), inflateInit determines the
+   compression method from the zlib header and allocates all data structures
+   accordingly; otherwise the allocation will be deferred to the first call of
+   inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
+   use default allocation functions.
+
+     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller.  msg is set to null if there is no error
+   message. inflateInit does not perform any decompression apart from reading
+   the zlib header if present: this will be done by inflate().  (So next_in and
+   avail_in may be modified, but next_out and avail_out are unchanged.)
+*/
+
+
+ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
+/*
+    inflate decompresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full. It may introduce
+  some output latency (reading input without producing any output) except when
+  forced to flush.
+
+  The detailed semantics are as follows. inflate performs one or both of the
+  following actions:
+
+  - Decompress more input starting at next_in and update next_in and avail_in
+    accordingly. If not all input can be processed (because there is not
+    enough room in the output buffer), next_in is updated and processing
+    will resume at this point for the next call of inflate().
+
+  - Provide more output starting at next_out and update next_out and avail_out
+    accordingly.  inflate() provides as much output as possible, until there
+    is no more input data or no more space in the output buffer (see below
+    about the flush parameter).
+
+  Before the call of inflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming
+  more output, and updating the next_* and avail_* values accordingly.
+  The application can consume the uncompressed output when it wants, for
+  example when the output buffer is full (avail_out == 0), or after each
+  call of inflate(). If inflate returns Z_OK and with zero avail_out, it
+  must be called again after making room in the output buffer because there
+  might be more output pending.
+
+    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
+  Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
+  output as possible to the output buffer. Z_BLOCK requests that inflate() stop
+  if and when it get to the next deflate block boundary. When decoding the zlib
+  or gzip format, this will cause inflate() to return immediately after the
+  header and before the first block. When doing a raw inflate, inflate() will
+  go ahead and process the first block, and will return when it gets to the end
+  of that block, or when it runs out of data.
+
+    The Z_BLOCK option assists in appending to or combining deflate streams.
+  Also to assist in this, on return inflate() will set strm->data_type to the
+  number of unused bits in the last byte taken from strm->next_in, plus 64
+  if inflate() is currently decoding the last block in the deflate stream,
+  plus 128 if inflate() returned immediately after decoding an end-of-block
+  code or decoding the complete header up to just before the first byte of the
+  deflate stream. The end-of-block will not be indicated until all of the
+  uncompressed data from that block has been written to strm->next_out.  The
+  number of unused bits may in general be greater than seven, except when
+  bit 7 of data_type is set, in which case the number of unused bits will be
+  less than eight.
+
+    inflate() should normally be called until it returns Z_STREAM_END or an
+  error. However if all decompression is to be performed in a single step
+  (a single call of inflate), the parameter flush should be set to
+  Z_FINISH. In this case all pending input is processed and all pending
+  output is flushed; avail_out must be large enough to hold all the
+  uncompressed data. (The size of the uncompressed data may have been saved
+  by the compressor for this purpose.) The next operation on this stream must
+  be inflateEnd to deallocate the decompression state. The use of Z_FINISH
+  is never required, but can be used to inform inflate that a faster approach
+  may be used for the single inflate() call.
+
+     In this implementation, inflate() always flushes as much output as
+  possible to the output buffer, and always uses the faster approach on the
+  first call. So the only effect of the flush parameter in this implementation
+  is on the return value of inflate(), as noted below, or when it returns early
+  because Z_BLOCK is used.
+
+     If a preset dictionary is needed after this call (see inflateSetDictionary
+  below), inflate sets strm->adler to the adler32 checksum of the dictionary
+  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
+  strm->adler to the adler32 checksum of all output produced so far (that is,
+  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
+  below. At the end of the stream, inflate() checks that its computed adler32
+  checksum is equal to that saved by the compressor and returns Z_STREAM_END
+  only if the checksum is correct.
+
+    inflate() will decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically.  Any information
+  contained in the gzip header is not retained, so applications that need that
+  information should instead use raw inflate, see inflateInit2() below, or
+  inflateBack() and perform their own processing of the gzip header and
+  trailer.
+
+    inflate() returns Z_OK if some progress has been made (more input processed
+  or more output produced), Z_STREAM_END if the end of the compressed data has
+  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+  corrupted (input stream not conforming to the zlib format or incorrect check
+  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
+  if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
+  Z_BUF_ERROR if no progress is possible or if there was not enough room in the
+  output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
+  inflate() can be called again with more input and more output space to
+  continue decompressing. If Z_DATA_ERROR is returned, the application may then
+  call inflateSync() to look for a good compression block if a partial recovery
+  of the data is desired.
+*/
+
+
+ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any
+   pending output.
+
+     inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
+   was inconsistent. In the error case, msg may be set but then points to a
+   static string (which must not be deallocated).
+*/
+
+                        /* Advanced functions */
+
+/*
+    The following functions are needed only in some special applications.
+*/
+
+/*
+ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
+                                     int  level,
+                                     int  method,
+                                     int  windowBits,
+                                     int  memLevel,
+                                     int  strategy));
+
+     This is another version of deflateInit with more compression options. The
+   fields next_in, zalloc, zfree and opaque must be initialized before by
+   the caller.
+
+     The method parameter is the compression method. It must be Z_DEFLATED in
+   this version of the library.
+
+     The windowBits parameter is the base two logarithm of the window size
+   (the size of the history buffer). It should be in the range 8..15 for this
+   version of the library. Larger values of this parameter result in better
+   compression at the expense of memory usage. The default value is 15 if
+   deflateInit is used instead.
+
+     windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
+   determines the window size. deflate() will then generate raw deflate data
+   with no zlib header or trailer, and will not compute an adler32 check value.
+
+     windowBits can also be greater than 15 for optional gzip encoding. Add
+   16 to windowBits to write a simple gzip header and trailer around the
+   compressed data instead of a zlib wrapper. The gzip header will have no
+   file name, no extra data, no comment, no modification time (set to zero),
+   no header crc, and the operating system will be set to 255 (unknown).  If a
+   gzip stream is being written, strm->adler is a crc32 instead of an adler32.
+
+     The memLevel parameter specifies how much memory should be allocated
+   for the internal compression state. memLevel=1 uses minimum memory but
+   is slow and reduces compression ratio; memLevel=9 uses maximum memory
+   for optimal speed. The default value is 8. See zconf.h for total memory
+   usage as a function of windowBits and memLevel.
+
+     The strategy parameter is used to tune the compression algorithm. Use the
+   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
+   string match), or Z_RLE to limit match distances to one (run-length
+   encoding). Filtered data consists mostly of small values with a somewhat
+   random distribution. In this case, the compression algorithm is tuned to
+   compress them better. The effect of Z_FILTERED is to force more Huffman
+   coding and less string matching; it is somewhat intermediate between
+   Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
+   Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
+   parameter only affects the compression ratio but not the correctness of the
+   compressed output even if it is not set appropriately.
+
+      deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
+   method). msg is set to null if there is no error message.  deflateInit2 does
+   not perform any compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the compression dictionary from the given byte sequence
+   without producing any compressed output. This function must be called
+   immediately after deflateInit, deflateInit2 or deflateReset, before any
+   call of deflate. The compressor and decompressor must use exactly the same
+   dictionary (see inflateSetDictionary).
+
+     The dictionary should consist of strings (byte sequences) that are likely
+   to be encountered later in the data to be compressed, with the most commonly
+   used strings preferably put towards the end of the dictionary. Using a
+   dictionary is most useful when the data to be compressed is short and can be
+   predicted with good accuracy; the data can then be compressed better than
+   with the default empty dictionary.
+
+     Depending on the size of the compression data structures selected by
+   deflateInit or deflateInit2, a part of the dictionary may in effect be
+   discarded, for example if the dictionary is larger than the window size in
+   deflate or deflate2. Thus the strings most likely to be useful should be
+   put at the end of the dictionary, not at the front.
+
+     Upon return of this function, strm->adler is set to the adler32 value
+   of the dictionary; the decompressor may later use this value to determine
+   which dictionary has been used by the compressor. (The adler32 value
+   applies to the whole dictionary even if only a subset of the dictionary is
+   actually used by the compressor.) If a raw deflate was requested, then the
+   adler32 value is not computed and strm->adler is not set.
+
+     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+   parameter is invalid (such as NULL dictionary) or the stream state is
+   inconsistent (for example if deflate has already been called for this stream
+   or if the compression method is bsort). deflateSetDictionary does not
+   perform any compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when several compression strategies will be
+   tried, for example when there are several ways of pre-processing the input
+   data with a filter. The streams that will be discarded should then be freed
+   by calling deflateEnd.  Note that deflateCopy duplicates the internal
+   compression state which can be quite large, so this strategy is slow and
+   can consume lots of memory.
+
+     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being NULL). msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to deflateEnd followed by deflateInit,
+   but does not free and reallocate all the internal compression state.
+   The stream will keep the same compression level and any other attributes
+   that may have been set by deflateInit2.
+
+      deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being NULL).
+*/
+
+ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
+                                      int level,
+                                      int strategy));
+/*
+     Dynamically update the compression level and compression strategy.  The
+   interpretation of level and strategy is as in deflateInit2.  This can be
+   used to switch between compression and straight copy of the input data, or
+   to switch to a different kind of input data requiring a different
+   strategy. If the compression level is changed, the input available so far
+   is compressed with the old level (and may be flushed); the new level will
+   take effect only at the next call of deflate().
+
+     Before the call of deflateParams, the stream state must be set as for
+   a call of deflate(), since the currently available input may have to
+   be compressed and flushed. In particular, strm->avail_out must be non-zero.
+
+     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
+   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
+   if strm->avail_out was zero.
+*/
+
+ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
+                                       uLong sourceLen));
+/*
+     deflateBound() returns an upper bound on the compressed size after
+   deflation of sourceLen bytes.  It must be called after deflateInit()
+   or deflateInit2().  This would be used to allocate an output buffer
+   for deflation in a single pass, and so would be called before deflate().
+*/
+
+ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     deflatePrime() inserts bits in the deflate output stream.  The intent
+  is that this function is used to start off the deflate output with the
+  bits leftover from a previous deflate stream when appending to it.  As such,
+  this function can only be used for raw deflate, and must be used before the
+  first deflate() call after a deflateInit2() or deflateReset().  bits must be
+  less than or equal to 16, and that many of the least significant bits of
+  value will be inserted in the output.
+
+      deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
+                                     int  windowBits));
+
+     This is another version of inflateInit with an extra parameter. The
+   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+   before by the caller.
+
+     The windowBits parameter is the base two logarithm of the maximum window
+   size (the size of the history buffer).  It should be in the range 8..15 for
+   this version of the library. The default value is 15 if inflateInit is used
+   instead. windowBits must be greater than or equal to the windowBits value
+   provided to deflateInit2() while compressing, or it must be equal to 15 if
+   deflateInit2() was not used. If a compressed stream with a larger window
+   size is given as input, inflate() will return with the error code
+   Z_DATA_ERROR instead of trying to allocate a larger window.
+
+     windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
+   determines the window size. inflate() will then process raw deflate data,
+   not looking for a zlib or gzip header, not generating a check value, and not
+   looking for any check values for comparison at the end of the stream. This
+   is for use with other formats that use the deflate compressed data format
+   such as zip.  Those formats provide their own check values. If a custom
+   format is developed using the raw deflate format for compressed data, it is
+   recommended that a check value such as an adler32 or a crc32 be applied to
+   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
+   most applications, the zlib format should be used as is. Note that comments
+   above on the use in deflateInit2() applies to the magnitude of windowBits.
+
+     windowBits can also be greater than 15 for optional gzip decoding. Add
+   32 to windowBits to enable zlib and gzip decoding with automatic header
+   detection, or add 16 to decode only the gzip format (the zlib format will
+   return a Z_DATA_ERROR.  If a gzip stream is being decoded, strm->adler is
+   a crc32 instead of an adler32.
+
+     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
+   memLevel). msg is set to null if there is no error message.  inflateInit2
+   does not perform any decompression apart from reading the zlib header if
+   present: this will be done by inflate(). (So next_in and avail_in may be
+   modified, but next_out and avail_out are unchanged.)
+*/
+
+ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the decompression dictionary from the given uncompressed byte
+   sequence. This function must be called immediately after a call of inflate
+   if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
+   can be determined from the adler32 value returned by this call of
+   inflate. The compressor and decompressor must use exactly the same
+   dictionary (see deflateSetDictionary).
+
+     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+   parameter is invalid (such as NULL dictionary) or the stream state is
+   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+   expected one (incorrect adler32 value). inflateSetDictionary does not
+   perform any decompression: this will be done by subsequent calls of
+   inflate().
+*/
+
+ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
+/*
+    Skips invalid compressed data until a full flush point (see above the
+  description of deflate with Z_FULL_FLUSH) can be found, or until all
+  available input is skipped. No output is provided.
+
+    inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
+  if no more input was provided, Z_DATA_ERROR if no flush point has been found,
+  or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
+  case, the application may save the current current value of total_in which
+  indicates where valid compressed data was found. In the error case, the
+  application may repeatedly call inflateSync, providing more input each time,
+  until success or end of the input data.
+*/
+
+ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when randomly accessing a large stream.  The
+   first pass through the stream can periodically record the inflate state,
+   allowing restarting inflate at those points when randomly accessing the
+   stream.
+
+     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being NULL). msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to inflateEnd followed by inflateInit,
+   but does not free and reallocate all the internal decompression state.
+   The stream will keep attributes that may have been set by inflateInit2.
+
+      inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being NULL).
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *strm, int windowBits,
+                                        unsigned char FAR *window));
+
+     Initialize the internal stream state for decompression using inflateBack()
+   calls.  The fields zalloc, zfree and opaque in strm must be initialized
+   before the call.  If zalloc and zfree are Z_NULL, then the default library-
+   derived memory allocation routines are used.  windowBits is the base two
+   logarithm of the window size, in the range 8..15.  window is a caller
+   supplied buffer of that size.  Except for special applications where it is
+   assured that deflate was used with small window sizes, windowBits must be 15
+   and a 32K byte window must be supplied to be able to decompress general
+   deflate streams.
+
+     See inflateBack() for the usage of these routines.
+
+     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
+   the paramaters are invalid, Z_MEM_ERROR if the internal state could not
+   be allocated, or Z_VERSION_ERROR if the version of the library does not
+   match the version of the header file.
+*/
+
+typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
+typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
+
+ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm,
+                                    in_func in, void FAR *in_desc,
+                                    out_func out, void FAR *out_desc));
+/*
+     inflateBack() does a raw inflate with a single call using a call-back
+   interface for input and output.  This is more efficient than inflate() for
+   file i/o applications in that it avoids copying between the output and the
+   sliding window by simply making the window itself the output buffer.  This
+   function trusts the application to not change the output buffer passed by
+   the output function, at least until inflateBack() returns.
+
+     inflateBackInit() must be called first to allocate the internal state
+   and to initialize the state with the user-provided window buffer.
+   inflateBack() may then be used multiple times to inflate a complete, raw
+   deflate stream with each call.  inflateBackEnd() is then called to free
+   the allocated state.
+
+     A raw deflate stream is one with no zlib or gzip header or trailer.
+   This routine would normally be used in a utility that reads zip or gzip
+   files and writes out uncompressed files.  The utility would decode the
+   header and process the trailer on its own, hence this routine expects
+   only the raw deflate stream to decompress.  This is different from the
+   normal behavior of inflate(), which expects either a zlib or gzip header and
+   trailer around the deflate stream.
+
+     inflateBack() uses two subroutines supplied by the caller that are then
+   called by inflateBack() for input and output.  inflateBack() calls those
+   routines until it reads a complete deflate stream and writes out all of the
+   uncompressed data, or until it encounters an error.  The function's
+   parameters and return types are defined above in the in_func and out_func
+   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the
+   number of bytes of provided input, and a pointer to that input in buf.  If
+   there is no input available, in() must return zero--buf is ignored in that
+   case--and inflateBack() will return a buffer error.  inflateBack() will call
+   out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].  out()
+   should return zero on success, or non-zero on failure.  If out() returns
+   non-zero, inflateBack() will return with an error.  Neither in() nor out()
+   are permitted to change the contents of the window provided to
+   inflateBackInit(), which is also the buffer that out() uses to write from.
+   The length written by out() will be at most the window size.  Any non-zero
+   amount of input may be provided by in().
+
+     For convenience, inflateBack() can be provided input on the first call by
+   setting strm->next_in and strm->avail_in.  If that input is exhausted, then
+   in() will be called.  Therefore strm->next_in must be initialized before
+   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
+   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
+   must also be initialized, and then if strm->avail_in is not zero, input will
+   initially be taken from strm->next_in[0 .. strm->avail_in - 1].
+
+     The in_desc and out_desc parameters of inflateBack() is passed as the
+   first parameter of in() and out() respectively when they are called.  These
+   descriptors can be optionally used to pass any information that the caller-
+   supplied in() and out() functions need to do their job.
+
+     On return, inflateBack() will set strm->next_in and strm->avail_in to
+   pass back any unused input that was provided by the last in() call.  The
+   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
+   if in() or out() returned an error, Z_DATA_ERROR if there was a format
+   error in the deflate stream (in which case strm->msg is set to indicate the
+   nature of the error), or Z_STREAM_ERROR if the stream was not properly
+   initialized.  In the case of Z_BUF_ERROR, an input or output error can be
+   distinguished using strm->next_in which will be Z_NULL only if in() returned
+   an error.  If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
+   out() returning non-zero.  (in() will always be called before out(), so
+   strm->next_in is assured to be defined if out() returns non-zero.)  Note
+   that inflateBack() cannot return Z_OK.
+*/
+
+ZEXTERN int ZEXPORT inflateBackEnd OF((z_stream FAR *strm));
+/*
+     All memory allocated by inflateBackInit() is freed.
+
+     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
+   state was inconsistent.
+*/
+
+ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
+/* Return flags indicating compile-time options.
+
+    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
+     1.0: size of uInt
+     3.2: size of uLong
+     5.4: size of voidpf (pointer)
+     7.6: size of z_off_t
+
+    Compiler, assembler, and debug options:
+     8: DEBUG
+     9: ASMV or ASMINF -- use ASM code
+     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
+     11: 0 (reserved)
+
+    One-time table building (smaller code, but not thread-safe if true):
+     12: BUILDFIXED -- build static block decoding tables when needed
+     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
+     14,15: 0 (reserved)
+
+    Library content (indicates missing functionality):
+     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
+                          deflate code when not needed)
+     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
+                    and decode gzip streams (to avoid linking crc code)
+     18-19: 0 (reserved)
+
+    Operation variations (changes in library functionality):
+     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
+     21: FASTEST -- deflate algorithm with only one, lowest compression level
+     22,23: 0 (reserved)
+
+    The sprintf variant used by gzprintf (zero is best):
+     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
+     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
+     26: 0 = returns value, 1 = void -- 1 means inferred string length returned
+
+    Remainder:
+     27-31: 0 (reserved)
+ */
+
+
+                        /* utility functions */
+
+/*
+     The following utility functions are implemented on top of the
+   basic stream-oriented functions. To simplify the interface, some
+   default options are assumed (compression level and memory usage,
+   standard memory allocation functions). The source code of these
+   utility functions can easily be modified if you need special options.
+*/
+
+ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
+                                 const Bytef *source, uLong sourceLen));
+/*
+     Compresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer. Upon entry, destLen is the total
+   size of the destination buffer, which must be at least the value returned
+   by compressBound(sourceLen). Upon exit, destLen is the actual size of the
+   compressed buffer.
+     This function can be used to compress a whole file at once if the
+   input file is mmap'ed.
+     compress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer.
+*/
+
+ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
+                                  const Bytef *source, uLong sourceLen,
+                                  int level));
+/*
+     Compresses the source buffer into the destination buffer. The level
+   parameter has the same meaning as in deflateInit.  sourceLen is the byte
+   length of the source buffer. Upon entry, destLen is the total size of the
+   destination buffer, which must be at least the value returned by
+   compressBound(sourceLen). Upon exit, destLen is the actual size of the
+   compressed buffer.
+
+     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+   Z_STREAM_ERROR if the level parameter is invalid.
+*/
+
+ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
+/*
+     compressBound() returns an upper bound on the compressed size after
+   compress() or compress2() on sourceLen bytes.  It would be used before
+   a compress() or compress2() call to allocate the destination buffer.
+*/
+
+ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
+                                   const Bytef *source, uLong sourceLen));
+/*
+     Decompresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer. Upon entry, destLen is the total
+   size of the destination buffer, which must be large enough to hold the
+   entire uncompressed data. (The size of the uncompressed data must have
+   been saved previously by the compressor and transmitted to the decompressor
+   by some mechanism outside the scope of this compression library.)
+   Upon exit, destLen is the actual size of the compressed buffer.
+     This function can be used to decompress a whole file at once if the
+   input file is mmap'ed.
+
+     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
+*/
+
+
+typedef voidp gzFile;
+
+ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
+/*
+     Opens a gzip (.gz) file for reading or writing. The mode parameter
+   is as in fopen ("rb" or "wb") but can also include a compression level
+   ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
+   Huffman only compression as in "wb1h", or 'R' for run-length encoding
+   as in "wb1R". (See the description of deflateInit2 for more information
+   about the strategy parameter.)
+
+     gzopen can be used to read a file which is not in gzip format; in this
+   case gzread will directly read from the file without decompression.
+
+     gzopen returns NULL if the file could not be opened or if there was
+   insufficient memory to allocate the (de)compression state; errno
+   can be checked to distinguish the two cases (if errno is zero, the
+   zlib error is Z_MEM_ERROR).  */
+
+ZEXTERN gzFile ZEXPORT gzdopen  OF((int fd, const char *mode));
+/*
+     gzdopen() associates a gzFile with the file descriptor fd.  File
+   descriptors are obtained from calls like open, dup, creat, pipe or
+   fileno (in the file has been previously opened with fopen).
+   The mode parameter is as in gzopen.
+     The next call of gzclose on the returned gzFile will also close the
+   file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
+   descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
+     gzdopen returns NULL if there was insufficient memory to allocate
+   the (de)compression state.
+*/
+
+ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
+/*
+     Dynamically update the compression level or strategy. See the description
+   of deflateInit2 for the meaning of these parameters.
+     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
+   opened for writing.
+*/
+
+ZEXTERN int ZEXPORT    gzread  OF((gzFile file, voidp buf, unsigned len));
+/*
+     Reads the given number of uncompressed bytes from the compressed file.
+   If the input file was not in gzip format, gzread copies the given number
+   of bytes into the buffer.
+     gzread returns the number of uncompressed bytes actually read (0 for
+   end of file, -1 for error). */
+
+ZEXTERN int ZEXPORT    gzwrite OF((gzFile file,
+                                   voidpc buf, unsigned len));
+/*
+     Writes the given number of uncompressed bytes into the compressed file.
+   gzwrite returns the number of uncompressed bytes actually written
+   (0 in case of error).
+*/
+
+ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
+/*
+     Converts, formats, and writes the args to the compressed file under
+   control of the format string, as in fprintf. gzprintf returns the number of
+   uncompressed bytes actually written (0 in case of error).  The number of
+   uncompressed bytes written is limited to 4095. The caller should assure that
+   this limit is not exceeded. If it is exceeded, then gzprintf() will return
+   return an error (0) with nothing written. In this case, there may also be a
+   buffer overflow with unpredictable consequences, which is possible only if
+   zlib was compiled with the insecure functions sprintf() or vsprintf()
+   because the secure snprintf() or vsnprintf() functions were not available.
+*/
+
+ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
+/*
+      Writes the given null-terminated string to the compressed file, excluding
+   the terminating null character.
+      gzputs returns the number of characters written, or -1 in case of error.
+*/
+
+ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
+/*
+      Reads bytes from the compressed file until len-1 characters are read, or
+   a newline character is read and transferred to buf, or an end-of-file
+   condition is encountered.  The string is then terminated with a null
+   character.
+      gzgets returns buf, or Z_NULL in case of error.
+*/
+
+ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
+/*
+      Writes c, converted to an unsigned char, into the compressed file.
+   gzputc returns the value that was written, or -1 in case of error.
+*/
+
+ZEXTERN int ZEXPORT    gzgetc OF((gzFile file));
+/*
+      Reads one byte from the compressed file. gzgetc returns this byte
+   or -1 in case of end of file or error.
+*/
+
+ZEXTERN int ZEXPORT    gzungetc OF((int c, gzFile file));
+/*
+      Push one character back onto the stream to be read again later.
+   Only one character of push-back is allowed.  gzungetc() returns the
+   character pushed, or -1 on failure.  gzungetc() will fail if a
+   character has been pushed but not read yet, or if c is -1. The pushed
+   character will be discarded if the stream is repositioned with gzseek()
+   or gzrewind().
+*/
+
+ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
+/*
+     Flushes all pending output into the compressed file. The parameter
+   flush is as in the deflate() function. The return value is the zlib
+   error number (see function gzerror below). gzflush returns Z_OK if
+   the flush parameter is Z_FINISH and all output could be flushed.
+     gzflush should be called only when strictly necessary because it can
+   degrade compression.
+*/
+
+ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
+                                      z_off_t offset, int whence));
+/*
+      Sets the starting position for the next gzread or gzwrite on the
+   given compressed file. The offset represents a number of bytes in the
+   uncompressed data stream. The whence parameter is defined as in lseek(2);
+   the value SEEK_END is not supported.
+     If the file is opened for reading, this function is emulated but can be
+   extremely slow. If the file is opened for writing, only forward seeks are
+   supported; gzseek then compresses a sequence of zeroes up to the new
+   starting position.
+
+      gzseek returns the resulting offset location as measured in bytes from
+   the beginning of the uncompressed stream, or -1 in case of error, in
+   particular if the file is opened for writing and the new starting position
+   would be before the current position.
+*/
+
+ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
+/*
+     Rewinds the given file. This function is supported only for reading.
+
+   gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+*/
+
+ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+/*
+     Returns the starting position for the next gzread or gzwrite on the
+   given compressed file. This position represents a number of bytes in the
+   uncompressed data stream.
+
+   gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+ZEXTERN int ZEXPORT gzeof OF((gzFile file));
+/*
+     Returns 1 when EOF has previously been detected reading the given
+   input stream, otherwise zero.
+*/
+
+ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
+/*
+     Flushes all pending output if necessary, closes the compressed file
+   and deallocates all the (de)compression state. The return value is the zlib
+   error number (see function gzerror below).
+*/
+
+ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
+/*
+     Returns the error message for the last error which occurred on the
+   given compressed file. errnum is set to zlib error number. If an
+   error occurred in the file system and not in the compression library,
+   errnum is set to Z_ERRNO and the application may consult errno
+   to get the exact error code.
+*/
+
+ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
+/*
+     Clears the error and end-of-file flags for file. This is analogous to the
+   clearerr() function in stdio. This is useful for continuing to read a gzip
+   file that is being written concurrently.
+*/
+
+                        /* checksum functions */
+
+/*
+     These functions are not related to compression but are exported
+   anyway because they might be useful in applications using the
+   compression library.
+*/
+
+ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
+
+/*
+     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+   return the updated checksum. If buf is NULL, this function returns
+   the required initial value for the checksum.
+   An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+   much faster. Usage example:
+
+     uLong adler = adler32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       adler = adler32(adler, buffer, length);
+     }
+     if (adler != original_adler) error();
+*/
+
+ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
+/*
+     Update a running crc with the bytes buf[0..len-1] and return the updated
+   crc. If buf is NULL, this function returns the required initial value
+   for the crc. Pre- and post-conditioning (one's complement) is performed
+   within this function so it shouldn't be done by the application.
+   Usage example:
+
+     uLong crc = crc32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       crc = crc32(crc, buffer, length);
+     }
+     if (crc != original_crc) error();
+*/
+
+
+                        /* various hacks, don't look :) */
+
+/* deflateInit and inflateInit are macros to allow checking the zlib version
+ * and the compiler's view of z_stream:
+ */
+ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
+                                      int windowBits, int memLevel,
+                                      int strategy, const char *version,
+                                      int stream_size));
+ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
+                                      const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateBackInit_ OF((z_stream FAR *strm, int windowBits,
+                                         unsigned char FAR *window,
+                                         const char *version,
+                                         int stream_size));
+#define deflateInit(strm, level) \
+        deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit(strm) \
+        inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
+#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+                      (strategy),           ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit2(strm, windowBits) \
+        inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
+#define inflateBackInit(strm, windowBits, window) \
+        inflateBackInit_((strm), (windowBits), (window), \
+        ZLIB_VERSION, sizeof(z_stream))
+
+
+#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
+    struct internal_state {int dummy;}; /* hack for buggy compilers */
+#endif
+
+ZEXTERN const char   * ZEXPORT zError           OF((int));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
+ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ZLIB_H */
diff -urdN ../Tekkotsu_2.3/aperios/lib/CVS/Entries ./aperios/lib/CVS/Entries
--- ../Tekkotsu_2.3/aperios/lib/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/lib/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,8 @@
+/libjpeg.a/1.2/Wed Jun  1 05:48:02 2005/-kb/Ttekkotsu-2_4
+/libpng.a/1.2/Wed Jun  1 05:48:03 2005/-kb/Ttekkotsu-2_4
+/libpng12.a/1.2/Wed Jun  1 05:48:03 2005/-kb/Ttekkotsu-2_4
+/libxml2.a/1.2/Wed Jun  1 05:48:03 2005/-kb/Ttekkotsu-2_4
+/libxml2.la/1.2/Wed Jun  1 05:48:06 2005//Ttekkotsu-2_4
+/libz.a/1.2/Wed Jun  1 05:48:06 2005/-kb/Ttekkotsu-2_4
+/xml2Conf.sh/1.2/Wed Jun  1 05:48:06 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/lib/CVS/Repository ./aperios/lib/CVS/Repository
--- ../Tekkotsu_2.3/aperios/lib/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/lib/CVS/Repository	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/lib
diff -urdN ../Tekkotsu_2.3/aperios/lib/CVS/Root ./aperios/lib/CVS/Root
--- ../Tekkotsu_2.3/aperios/lib/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/lib/CVS/Root	Wed Aug 10 11:03:22 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/lib/CVS/Tag ./aperios/lib/CVS/Tag
--- ../Tekkotsu_2.3/aperios/lib/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/lib/CVS/Tag	Wed Aug 10 11:03:24 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
Binary files ../Tekkotsu_2.3/aperios/lib/libjpeg.a and ./aperios/lib/libjpeg.a differ
Binary files ../Tekkotsu_2.3/aperios/lib/libpng.a and ./aperios/lib/libpng.a differ
Binary files ../Tekkotsu_2.3/aperios/lib/libpng12.a and ./aperios/lib/libpng12.a differ
Binary files ../Tekkotsu_2.3/aperios/lib/libxml2.a and ./aperios/lib/libxml2.a differ
diff -urdN ../Tekkotsu_2.3/aperios/lib/libxml2.la ./aperios/lib/libxml2.la
--- ../Tekkotsu_2.3/aperios/lib/libxml2.la	Wed Dec 31 19:00:00 1969
+++ ./aperios/lib/libxml2.la	Wed Jun  1 01:48:06 2005
@@ -0,0 +1,35 @@
+# libxml2.la - a libtool library file
+# Generated by ltmain.sh - GNU libtool 1.5.6 (1.1220.2.95 2004/04/11 05:50:42)
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# The name that we can dlopen(3).
+dlname=''
+
+# Names of this library.
+library_names=''
+
+# The name of the static archive.
+old_library='libxml2.a'
+
+# Libraries that this one depends upon.
+dependency_libs=' -L/usr0/ejt/TekkotsuSim/aperios/lib -lz -lm'
+
+# Version information for libxml2.
+current=8
+age=6
+revision=19
+
+# Is this an already installed library?
+installed=yes
+
+# Should we warn about portability when linking against -modules?
+shouldnotlink=no
+
+# Files to dlopen/dlpreopen
+dlopen=''
+dlpreopen=''
+
+# Directory that this library needs to be installed in:
+libdir='/usr0/ejt/TekkotsuSim/aperios/lib'
Binary files ../Tekkotsu_2.3/aperios/lib/libz.a and ./aperios/lib/libz.a differ
diff -urdN ../Tekkotsu_2.3/aperios/lib/xml2Conf.sh ./aperios/lib/xml2Conf.sh
--- ../Tekkotsu_2.3/aperios/lib/xml2Conf.sh	Wed Dec 31 19:00:00 1969
+++ ./aperios/lib/xml2Conf.sh	Wed Jun  1 01:48:06 2005
@@ -0,0 +1,8 @@
+#
+# Configuration file for using the XML library in GNOME applications
+#
+XML2_LIBDIR="-L/usr0/ejt/TekkotsuSim/aperios/lib"
+XML2_LIBS="-lxml2 -L/usr0/ejt/TekkotsuSim/aperios/lib -lz   -lm "
+XML2_INCLUDEDIR="-I/usr0/ejt/TekkotsuSim/aperios/include/libxml2"
+MODULE_VERSION="xml2-2.6.19"
+
diff -urdN ../Tekkotsu_2.3/aperios/share/CVS/Entries ./aperios/share/CVS/Entries
--- ../Tekkotsu_2.3/aperios/share/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+D/aclocal////
diff -urdN ../Tekkotsu_2.3/aperios/share/CVS/Repository ./aperios/share/CVS/Repository
--- ../Tekkotsu_2.3/aperios/share/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/CVS/Repository	Wed Aug 10 11:03:24 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/share
diff -urdN ../Tekkotsu_2.3/aperios/share/CVS/Root ./aperios/share/CVS/Root
--- ../Tekkotsu_2.3/aperios/share/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/CVS/Root	Wed Aug 10 11:03:24 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/share/CVS/Tag ./aperios/share/CVS/Tag
--- ../Tekkotsu_2.3/aperios/share/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/CVS/Tag	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Entries ./aperios/share/aclocal/CVS/Entries
--- ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/aclocal/CVS/Entries	Wed Aug 10 11:03:25 2005
@@ -0,0 +1,2 @@
+/libxml.m4/1.2/Wed Jun  1 05:48:06 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Repository ./aperios/share/aclocal/CVS/Repository
--- ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/aclocal/CVS/Repository	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Tekkotsu/aperios/share/aclocal
diff -urdN ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Root ./aperios/share/aclocal/CVS/Root
--- ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/aclocal/CVS/Root	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Tag ./aperios/share/aclocal/CVS/Tag
--- ../Tekkotsu_2.3/aperios/share/aclocal/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/aclocal/CVS/Tag	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/aperios/share/aclocal/libxml.m4 ./aperios/share/aclocal/libxml.m4
--- ../Tekkotsu_2.3/aperios/share/aclocal/libxml.m4	Wed Dec 31 19:00:00 1969
+++ ./aperios/share/aclocal/libxml.m4	Wed Jun  1 01:48:06 2005
@@ -0,0 +1,188 @@
+# Configure paths for LIBXML2
+# Mike Hommey 2004-06-19
+# use CPPFLAGS instead of CFLAGS
+# Toshio Kuratomi 2001-04-21
+# Adapted from:
+# Configure paths for GLIB
+# Owen Taylor     97-11-3
+
+dnl AM_PATH_XML2([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
+dnl Test for XML, and define XML_CPPFLAGS and XML_LIBS
+dnl
+AC_DEFUN([AM_PATH_XML2],[ 
+AC_ARG_WITH(xml-prefix,
+            [  --with-xml-prefix=PFX   Prefix where libxml is installed (optional)],
+            xml_config_prefix="$withval", xml_config_prefix="")
+AC_ARG_WITH(xml-exec-prefix,
+            [  --with-xml-exec-prefix=PFX Exec prefix where libxml is installed (optional)],
+            xml_config_exec_prefix="$withval", xml_config_exec_prefix="")
+AC_ARG_ENABLE(xmltest,
+              [  --disable-xmltest       Do not try to compile and run a test LIBXML program],,
+              enable_xmltest=yes)
+
+  if test x$xml_config_exec_prefix != x ; then
+     xml_config_args="$xml_config_args"
+     if test x${XML2_CONFIG+set} != xset ; then
+        XML2_CONFIG=$xml_config_exec_prefix/bin/xml2-config
+     fi
+  fi
+  if test x$xml_config_prefix != x ; then
+     xml_config_args="$xml_config_args --prefix=$xml_config_prefix"
+     if test x${XML2_CONFIG+set} != xset ; then
+        XML2_CONFIG=$xml_config_prefix/bin/xml2-config
+     fi
+  fi
+
+  AC_PATH_PROG(XML2_CONFIG, xml2-config, no)
+  min_xml_version=ifelse([$1], ,2.0.0,[$1])
+  AC_MSG_CHECKING(for libxml - version >= $min_xml_version)
+  no_xml=""
+  if test "$XML2_CONFIG" = "no" ; then
+    no_xml=yes
+  else
+    XML_CPPFLAGS=`$XML2_CONFIG $xml_config_args --cflags`
+    XML_LIBS=`$XML2_CONFIG $xml_config_args --libs`
+    xml_config_major_version=`$XML2_CONFIG $xml_config_args --version | \
+           sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
+    xml_config_minor_version=`$XML2_CONFIG $xml_config_args --version | \
+           sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
+    xml_config_micro_version=`$XML2_CONFIG $xml_config_args --version | \
+           sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
+    if test "x$enable_xmltest" = "xyes" ; then
+      ac_save_CPPFLAGS="$CPPFLAGS"
+      ac_save_LIBS="$LIBS"
+      CPPFLAGS="$CPPFLAGS $XML_CPPFLAGS"
+      LIBS="$XML_LIBS $LIBS"
+dnl
+dnl Now check if the installed libxml is sufficiently new.
+dnl (Also sanity checks the results of xml2-config to some extent)
+dnl
+      rm -f conf.xmltest
+      AC_TRY_RUN([
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <libxml/xmlversion.h>
+
+int 
+main()
+{
+  int xml_major_version, xml_minor_version, xml_micro_version;
+  int major, minor, micro;
+  char *tmp_version;
+
+  system("touch conf.xmltest");
+
+  /* Capture xml2-config output via autoconf/configure variables */
+  /* HP/UX 9 (%@#!) writes to sscanf strings */
+  tmp_version = (char *)strdup("$min_xml_version");
+  if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, &micro) != 3) {
+     printf("%s, bad version string from xml2-config\n", "$min_xml_version");
+     exit(1);
+   }
+   free(tmp_version);
+
+   /* Capture the version information from the header files */
+   tmp_version = (char *)strdup(LIBXML_DOTTED_VERSION);
+   if (sscanf(tmp_version, "%d.%d.%d", &xml_major_version, &xml_minor_version, &xml_micro_version) != 3) {
+     printf("%s, bad version string from libxml includes\n", "LIBXML_DOTTED_VERSION");
+     exit(1);
+   }
+   free(tmp_version);
+
+ /* Compare xml2-config output to the libxml headers */
+  if ((xml_major_version != $xml_config_major_version) ||
+      (xml_minor_version != $xml_config_minor_version) ||
+      (xml_micro_version != $xml_config_micro_version))
+    {
+      printf("*** libxml header files (version %d.%d.%d) do not match\n",
+         xml_major_version, xml_minor_version, xml_micro_version);
+      printf("*** xml2-config (version %d.%d.%d)\n",
+         $xml_config_major_version, $xml_config_minor_version, $xml_config_micro_version);
+      return 1;
+    } 
+/* Compare the headers to the library to make sure we match */
+  /* Less than ideal -- doesn't provide us with return value feedback, 
+   * only exits if there's a serious mismatch between header and library.
+   */
+    LIBXML_TEST_VERSION;
+
+    /* Test that the library is greater than our minimum version */
+    if ((xml_major_version > major) ||
+        ((xml_major_version == major) && (xml_minor_version > minor)) ||
+        ((xml_major_version == major) && (xml_minor_version == minor) &&
+        (xml_micro_version >= micro)))
+      {
+        return 0;
+       }
+     else
+      {
+        printf("\n*** An old version of libxml (%d.%d.%d) was found.\n",
+               xml_major_version, xml_minor_version, xml_micro_version);
+        printf("*** You need a version of libxml newer than %d.%d.%d. The latest version of\n",
+           major, minor, micro);
+        printf("*** libxml is always available from ftp://ftp.xmlsoft.org.\n");
+        printf("***\n");
+        printf("*** If you have already installed a sufficiently new version, this error\n");
+        printf("*** probably means that the wrong copy of the xml2-config shell script is\n");
+        printf("*** being found. The easiest way to fix this is to remove the old version\n");
+        printf("*** of LIBXML, but you can also set the XML2_CONFIG environment to point to the\n");
+        printf("*** correct copy of xml2-config. (In this case, you will have to\n");
+        printf("*** modify your LD_LIBRARY_PATH enviroment variable, or edit /etc/ld.so.conf\n");
+        printf("*** so that the correct libraries are found at run-time))\n");
+    }
+  return 1;
+}
+],, no_xml=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"])
+       CPPFLAGS="$ac_save_CPPFLAGS"
+       LIBS="$ac_save_LIBS"
+     fi
+  fi
+
+  if test "x$no_xml" = x ; then
+     AC_MSG_RESULT(yes (version $xml_config_major_version.$xml_config_minor_version.$xml_config_micro_version))
+     ifelse([$2], , :, [$2])     
+  else
+     AC_MSG_RESULT(no)
+     if test "$XML2_CONFIG" = "no" ; then
+       echo "*** The xml2-config script installed by LIBXML could not be found"
+       echo "*** If libxml was installed in PREFIX, make sure PREFIX/bin is in"
+       echo "*** your path, or set the XML2_CONFIG environment variable to the"
+       echo "*** full path to xml2-config."
+     else
+       if test -f conf.xmltest ; then
+        :
+       else
+          echo "*** Could not run libxml test program, checking why..."
+          CPPFLAGS="$CPPFLAGS $XML_CPPFLAGS"
+          LIBS="$LIBS $XML_LIBS"
+          AC_TRY_LINK([
+#include <libxml/xmlversion.h>
+#include <stdio.h>
+],      [ LIBXML_TEST_VERSION; return 0;],
+        [ echo "*** The test program compiled, but did not run. This usually means"
+          echo "*** that the run-time linker is not finding LIBXML or finding the wrong"
+          echo "*** version of LIBXML. If it is not finding LIBXML, you'll need to set your"
+          echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point"
+          echo "*** to the installed location  Also, make sure you have run ldconfig if that"
+          echo "*** is required on your system"
+          echo "***"
+          echo "*** If you have an old version installed, it is best to remove it, although"
+          echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH" ],
+        [ echo "*** The test program failed to compile or link. See the file config.log for the"
+          echo "*** exact error that occured. This usually means LIBXML was incorrectly installed"
+          echo "*** or that you have moved LIBXML since it was installed. In the latter case, you"
+          echo "*** may want to edit the xml2-config script: $XML2_CONFIG" ])
+          CPPFLAGS="$ac_save_CPPFLAGS"
+          LIBS="$ac_save_LIBS"
+       fi
+     fi
+
+     XML_CPPFLAGS=""
+     XML_LIBS=""
+     ifelse([$3], , :, [$3])
+  fi
+  AC_SUBST(XML_CPPFLAGS)
+  AC_SUBST(XML_LIBS)
+  rm -f conf.xmltest
+])
diff -urdN ../Tekkotsu_2.3/common.h ./common.h
--- ../Tekkotsu_2.3/common.h	Wed Dec 31 19:00:00 1969
+++ ./common.h	Fri Jul  1 15:45:42 2005
@@ -0,0 +1,307 @@
+/* This is a file lists the most depended-upon header files used by
+ * the project.  It is automatically generated by tools/genCommonHeader.
+ * When compiling for PLATFORM_LOCAL, this header will be precompiled. 
+ * It was created at Sat Mar 12 13:19:45 EST 2005 and checked into 
+ * CVS at $Date: 2005/07/01 19:45:42 $ */
+
+#ifdef __cplusplus //lets us blindly apply to C files as well
+
+#ifdef PLATFORM_LOCAL
+#ifdef TGT_ERS210
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Shared/ReferenceCounter.h" //64
+#include "Events/EventTrapper.h" //64
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/ERS210Info.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //56
+#include "IPC/SemaphoreManager.h" //54
+#include "IPC/ProcessID.h" //54
+#include "IPC/ListMemBuf.h" //54
+#include "IPC/MutexLock.h" //53
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/LockScope.h" //48
+#include "IPC/RCRegion.h" //47
+#include "IPC/MessageQueue.h" //45
+#include "Motion/OutputCmd.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/TimeET.h" //42
+#include "Shared/Config.h" //42
+#include "IPC/SharedObject.h" //42
+#include "Shared/mathutils.h" //41
+#include "Shared/Profiler.h" //41
+#include "Motion/MotionManagerMsg.h" //41
+#include "Motion/MotionCommand.h" //41
+#include "Motion/OutputPID.h" //40
+#include "Motion/MotionManager.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS210
+#ifdef TGT_ERS220
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Shared/ReferenceCounter.h" //64
+#include "Events/EventTrapper.h" //64
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/ERS220Info.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //56
+#include "IPC/SemaphoreManager.h" //54
+#include "IPC/ProcessID.h" //54
+#include "IPC/ListMemBuf.h" //54
+#include "IPC/MutexLock.h" //53
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/LockScope.h" //48
+#include "IPC/RCRegion.h" //47
+#include "IPC/MessageQueue.h" //45
+#include "Motion/OutputCmd.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/TimeET.h" //42
+#include "Shared/Config.h" //42
+#include "IPC/SharedObject.h" //42
+#include "Shared/mathutils.h" //41
+#include "Shared/Profiler.h" //41
+#include "Motion/MotionManagerMsg.h" //41
+#include "Motion/MotionCommand.h" //41
+#include "Motion/OutputPID.h" //40
+#include "Motion/MotionManager.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS220
+#ifdef TGT_ERS2xx
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Shared/ReferenceCounter.h" //64
+#include "Events/EventTrapper.h" //64
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/ERS2xxInfo.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //56
+#include "IPC/SemaphoreManager.h" //54
+#include "IPC/ProcessID.h" //54
+#include "IPC/ListMemBuf.h" //54
+#include "IPC/MutexLock.h" //53
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/LockScope.h" //48
+#include "IPC/RCRegion.h" //47
+#include "IPC/MessageQueue.h" //45
+#include "Motion/OutputCmd.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/TimeET.h" //42
+#include "Shared/Config.h" //42
+#include "IPC/SharedObject.h" //42
+#include "Shared/mathutils.h" //41
+#include "Shared/Profiler.h" //41
+#include "Motion/MotionManagerMsg.h" //41
+#include "Motion/MotionCommand.h" //41
+#include "Motion/OutputPID.h" //40
+#include "Motion/MotionManager.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS2xx
+#ifdef TGT_ERS7
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Shared/ReferenceCounter.h" //64
+#include "Events/EventTrapper.h" //64
+#include "Shared/ERS7Info.h" //59
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //56
+#include "IPC/SemaphoreManager.h" //54
+#include "IPC/ProcessID.h" //54
+#include "IPC/ListMemBuf.h" //54
+#include "IPC/MutexLock.h" //53
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/LockScope.h" //48
+#include "IPC/RCRegion.h" //47
+#include "IPC/MessageQueue.h" //45
+#include "Motion/OutputCmd.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/TimeET.h" //42
+#include "Shared/Config.h" //42
+#include "IPC/SharedObject.h" //42
+#include "Shared/mathutils.h" //41
+#include "Shared/Profiler.h" //41
+#include "Motion/MotionManagerMsg.h" //41
+#include "Motion/MotionCommand.h" //41
+#include "Motion/OutputPID.h" //40
+#include "Motion/MotionManager.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS7
+#endif //PLATFORM_LOCAL
+
+#ifdef PLATFORM_APERIOS
+#ifdef TGT_ERS210
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Events/EventTrapper.h" //64
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/ERS210Info.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //55
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/ProcessID.h" //49
+#include "IPC/MutexLock.h" //48
+#include "Shared/Config.h" //44
+#include "IPC/RCRegion.h" //44
+#include "IPC/LockScope.h" //44
+#include "IPC/ListMemBuf.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/ReferenceCounter.h" //42
+#include "Motion/OutputCmd.h" //41
+#include "Shared/TimeET.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS210
+#ifdef TGT_ERS220
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Events/EventTrapper.h" //64
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/ERS220Info.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //55
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/ProcessID.h" //49
+#include "IPC/MutexLock.h" //48
+#include "Shared/Config.h" //44
+#include "IPC/RCRegion.h" //44
+#include "IPC/LockScope.h" //44
+#include "IPC/ListMemBuf.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/ReferenceCounter.h" //42
+#include "Motion/OutputCmd.h" //41
+#include "Shared/TimeET.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS220
+#ifdef TGT_ERS2xx
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Events/EventTrapper.h" //64
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/ERS2xxInfo.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //55
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/ProcessID.h" //49
+#include "IPC/MutexLock.h" //48
+#include "Shared/Config.h" //44
+#include "IPC/RCRegion.h" //44
+#include "IPC/LockScope.h" //44
+#include "IPC/ListMemBuf.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/ReferenceCounter.h" //42
+#include "Motion/OutputCmd.h" //41
+#include "Shared/TimeET.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS2xx
+#ifdef TGT_ERS7
+#include "Shared/get_time.h" //75
+#include "Shared/LoadSave.h" //75
+#include "Events/EventBase.h" //74
+#include "Events/EventTrapper.h" //64
+#include "Shared/ERS7Info.h" //59
+#include "Shared/CommonInfo.h" //59
+#include "Shared/RobotInfo.h" //58
+#include "Shared/debuget.h" //56
+#include "Events/EventListener.h" //55
+#include "Wireless/Socket.h" //52
+#include "Events/EventRouter.h" //52
+#include "IPC/ProcessID.h" //49
+#include "IPC/MutexLock.h" //48
+#include "Shared/Config.h" //44
+#include "IPC/RCRegion.h" //44
+#include "IPC/LockScope.h" //44
+#include "IPC/ListMemBuf.h" //43
+#include "Events/EventTranslator.h" //43
+#include "Shared/ReferenceCounter.h" //42
+#include "Motion/OutputCmd.h" //41
+#include "Shared/TimeET.h" //40
+#include "Behaviors/BehaviorBase.h" //40
+#include "Shared/newmat/newmat.h" //forced (pattern match)
+#include "Shared/newmat/myexcept.h" //forced (pattern match)
+#include "Shared/newmat/include.h" //forced (pattern match)
+#include "Shared/newmat/newmatio.h" //forced (pattern match)
+#include "Shared/newmat/newmatap.h" //forced (pattern match)
+#include "Motion/roboop/utils.h" //forced (pattern match)
+#include "Motion/roboop/robot.h" //forced (pattern match)
+#include "Motion/roboop/config.h" //forced (pattern match)
+#endif //TGT_ERS7
+#endif //PLATFORM_APERIOS
+
+#endif //cplusplus
diff -urdN ../Tekkotsu_2.3/docs/CVS/Entries ./docs/CVS/Entries
--- ../Tekkotsu_2.3/docs/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./docs/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,14 @@
+/CMPack_license.txt/1.1/Thu Jan  9 02:03:00 2003//Ttekkotsu-2_4
+/JointSpeedLimits.txt/1.1/Tue Dec 23 06:33:44 2003//Ttekkotsu-2_4
+/PositionFileFormat.txt/1.1.1.1/Mon Sep 30 18:19:47 2002//Ttekkotsu-2_4
+/builddocs/1.22/Wed Aug 10 15:01:05 2005//Ttekkotsu-2_4
+/doxygencfg/1.42/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/doxygenfoot.html/1.3/Tue Feb 10 01:47:08 2004//Ttekkotsu-2_4
+/doxygenhead.html/1.10/Tue Jul 19 23:35:22 2005//Ttekkotsu-2_4
+/exthead.html/1.1/Wed Nov 24 21:30:39 2004//Ttekkotsu-2_4
+/newmat.doxycfg/1.3/Wed Nov 24 21:30:40 2004//Ttekkotsu-2_4
+/newmatfoot.html/1.1/Tue Jul 20 17:57:01 2004//Ttekkotsu-2_4
+/roboop.doxycfg/1.3/Wed Nov 24 21:30:40 2004//Ttekkotsu-2_4
+/roboopfoot.html/1.1/Tue Jul 20 17:57:01 2004//Ttekkotsu-2_4
+D/benchmarks////
+D/html////
diff -urdN ../Tekkotsu_2.3/docs/CVS/Repository ./docs/CVS/Repository
--- ../Tekkotsu_2.3/docs/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./docs/CVS/Repository	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Tekkotsu/docs
diff -urdN ../Tekkotsu_2.3/docs/CVS/Root ./docs/CVS/Root
--- ../Tekkotsu_2.3/docs/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./docs/CVS/Root	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/docs/CVS/Tag ./docs/CVS/Tag
--- ../Tekkotsu_2.3/docs/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./docs/CVS/Tag	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/docs/benchmarks/CVS/Entries ./docs/benchmarks/CVS/Entries
--- ../Tekkotsu_2.3/docs/benchmarks/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./docs/benchmarks/CVS/Entries	Wed Aug 10 11:03:25 2005
@@ -0,0 +1,19 @@
+/STARTUP_2.3.txt/1.1/Sat Jan 29 00:39:40 2005//Ttekkotsu-2_4
+/profilerun_ERS210A_1.1.txt/1.2/Wed Feb  4 21:54:44 2004//Ttekkotsu-2_4
+/profilerun_ERS210A_1.4.txt/1.2/Wed Feb  4 21:54:44 2004//Ttekkotsu-2_4
+/profilerun_ERS210A_1.5.txt/1.2/Wed Feb  4 21:54:44 2004//Ttekkotsu-2_4
+/profilerun_ERS210A_2.0.txt/1.3/Wed Feb  4 21:55:32 2004//Ttekkotsu-2_4
+/profilerun_ERS210A_2.1.txt/1.1/Wed Mar 17 02:58:49 2004//Ttekkotsu-2_4
+/profilerun_ERS210A_2.2.txt/1.1/Mon Oct 18 20:33:52 2004//Ttekkotsu-2_4
+/profilerun_ERS210A_2.3.txt/1.1/Sat Jan 29 00:38:42 2005//Ttekkotsu-2_4
+/profilerun_ERS210A_2.4.txt/1.1/Wed Aug 10 03:35:14 2005//Ttekkotsu-2_4
+/profilerun_ERS210_1.1.txt/1.2/Wed Feb  4 21:54:44 2004//Ttekkotsu-2_4
+/profilerun_ERS210_1.4.txt/1.2/Wed Feb  4 21:54:44 2004//Ttekkotsu-2_4
+/profilerun_ERS210_1.5.txt/1.2/Wed Feb  4 21:54:44 2004//Ttekkotsu-2_4
+/profilerun_ERS210_2.0.txt/1.1/Wed Feb  4 21:55:32 2004//Ttekkotsu-2_4
+/profilerun_ERS7_2.0.txt/1.3/Wed Feb  4 21:55:32 2004//Ttekkotsu-2_4
+/profilerun_ERS7_2.1.txt/1.1/Wed Mar 17 02:58:49 2004//Ttekkotsu-2_4
+/profilerun_ERS7_2.2.txt/1.1/Mon Oct 18 20:33:52 2004//Ttekkotsu-2_4
+/profilerun_ERS7_2.3.txt/1.1/Sat Jan 29 00:38:42 2005//Ttekkotsu-2_4
+/profilerun_ERS7_2.4.txt/1.1/Wed Aug 10 03:35:14 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/docs/benchmarks/CVS/Repository ./docs/benchmarks/CVS/Repository
--- ../Tekkotsu_2.3/docs/benchmarks/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./docs/benchmarks/CVS/Repository	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Tekkotsu/docs/benchmarks
diff -urdN ../Tekkotsu_2.3/docs/benchmarks/CVS/Root ./docs/benchmarks/CVS/Root
--- ../Tekkotsu_2.3/docs/benchmarks/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./docs/benchmarks/CVS/Root	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/docs/benchmarks/CVS/Tag ./docs/benchmarks/CVS/Tag
--- ../Tekkotsu_2.3/docs/benchmarks/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./docs/benchmarks/CVS/Tag	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/docs/benchmarks/profilerun_ERS210A_2.4.txt ./docs/benchmarks/profilerun_ERS210A_2.4.txt
--- ../Tekkotsu_2.3/docs/benchmarks/profilerun_ERS210A_2.4.txt	Wed Dec 31 19:00:00 1969
+++ ./docs/benchmarks/profilerun_ERS210A_2.4.txt	Tue Aug  9 23:35:14 2005
@@ -0,0 +1,119 @@
+Setup:
+  Default build for ERS-2xx (TGT_ERS2xx)
+  Pink ball in view (8.5in from snout)
+  Press power button, start timer
+  Telnet to system console (port 59000)
+  Connect ControllerGUI
+  STARTUP script:
+    Launch StareAtBallBehavior (leave E-Stop ON)
+    Navigate to Status Reports -> Profiler
+  Wait until 5 minutes from initial press of power button.
+  Recorded profiler run shown below
+ 
+~~~ Main: ~~~
+Profiling information since: 22.064388 to 297.846219
+ReadySendJoints():
+        2142 calls
+        0.386470 ms avg
+        0.327930 ms exp.avg
+        0.000954 ms avg child time (0.200000%)
+        128.262485 ms avg inter (7.796512 fps)
+        128.548828 ms exp.avg (7.779145 fps)
+        Exec: 0 1 1883 258 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 1 2 0 0 0 0 0 0 0 1728 408 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+GotSensorFrame():
+        8553 calls
+        0.689438 ms avg
+        0.640750 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        32.116282 ms avg inter (31.136854 fps)
+        33.498589 ms exp.avg (29.852003 fps)
+        Exec: 0 0 7321 910 322 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 2 5 1696 26 2746 4075 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+PowerEvent():
+        22 calls
+        37.252545 ms avg
+        27.207577 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        11925.084682 ms avg inter (0.083857 fps)
+        8167.484375 ms exp.avg (0.122437 fps)
+        Exec: 0 0 14 7 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 3 0 3 0 2 0 8
+GotAudio():
+        8552 calls
+        0.538072 ms avg
+        0.520855 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        32.015920 ms avg inter (31.234461 fps)
+        30.959778 ms exp.avg (32.299973 fps)
+        Exec: 0 0 7684 864 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 1 5 1701 3427 3416 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+GotImage():
+        6823 calls
+        24.163581 ms avg
+        24.534712 ms exp.avg
+        19.063732 ms avg child time (78.800000%)
+        40.136761 ms avg inter (24.914816 fps)
+        40.565296 ms exp.avg (24.651613 fps)
+        Exec: 0 0 0 1 6 0 910 5904 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 1 1 7 6812 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+BallDetection::processEvent():
+        6819 calls
+        19.075321 ms avg
+        19.678658 ms exp.avg
+        18.297997 ms avg child time (95.900000%)
+        40.069845 ms avg inter (24.956423 fps)
+        40.464199 ms exp.avg (24.713203 fps)
+        Exec: 0 2 0 0 1 0 6280 536 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 1 0 0 1 0 1 6 6809 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+RegionGenerator::calcImage(...):
+        6816 calls
+        18.306051 ms avg
+        18.956593 ms exp.avg
+        12.567141 ms avg child time (68.600000%)
+        40.102133 ms avg inter (24.936329 fps)
+        40.480694 ms exp.avg (24.703133 fps)
+        Exec: 0 0 0 0 0 0 6721 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 0 0 5 6810 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+RLEGenerator::calcImage(...):
+        6816 calls
+        12.567141 ms avg
+        12.602772 ms exp.avg
+        8.314293 ms avg child time (66.100000%)
+        40.102607 ms avg inter (24.936035 fps)
+        40.480934 ms exp.avg (24.702988 fps)
+        Exec: 0 0 0 0 0 932 5883 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 0 0 5 6810 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+SegmentedColorGenerator::calcImage(...):
+        6816 calls
+        8.314293 ms avg
+        8.229791 ms exp.avg
+        0.051083 ms avg child time (0.600000%)
+        40.102741 ms avg inter (24.935951 fps)
+        40.480812 ms exp.avg (24.703062 fps)
+        Exec: 0 0 0 0 0 6809 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 0 0 5 6810 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+RawCameraGenerator::calcImage(...):
+        20448 calls
+        0.017028 ms avg
+        0.013911 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        13.363331 ms avg inter (74.831644 fps)
+        11.247458 ms exp.avg (88.908974 fps)
+        Exec: 16 20121 310 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 13495 135 2 0 0 0 7 6808 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+Bucket distribution (in ms):
+        0<0.00802, <0.133, <0.686, <2.2, <5.43, <11.4, <21.2, <36.4, <58.7, <90, <132, <188, <260, <352, <465, <604, <772, <973, <1.21e+03, <1.49e+03, <1.82e+03, <2.19e+03, <2.63e+03, <3.12e+03, <3.68e+03, <4.31e+03, <5.03e+03, <5.82e+03, <6.71e+03, <7.7e+03, <8.79e+03, <1e+04,
+~~~ Motion: ~~~
+Profiling information since: 22.065116 to 297.856438
+ReadySendJoints():
+        8564 calls
+        3.394833 ms avg
+        3.618192 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        32.068783 ms avg inter (31.182973 fps)
+        32.179592 ms exp.avg (31.075598 fps)
+        Exec: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8564
+        Inter: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8563
+Bucket distribution (in ms):
+        0<0.00802, <0.133, <0.686, <2.2, <5.43, <11.4, <21.2, <36.4, <58.7, <90, <132, <188, <260, <352, <465, <604, <772, <973, <1.21e+03, <1.49e+03, <1.82e+03, <2.19e+03, <2.63e+03, <3.12e+03, <3.68e+03, <4.31e+03, <5.03e+03, <5.82e+03, <6.71e+03, <7.7e+03, <8.79e+03, <1e+04,
diff -urdN ../Tekkotsu_2.3/docs/benchmarks/profilerun_ERS7_2.4.txt ./docs/benchmarks/profilerun_ERS7_2.4.txt
--- ../Tekkotsu_2.3/docs/benchmarks/profilerun_ERS7_2.4.txt	Wed Dec 31 19:00:00 1969
+++ ./docs/benchmarks/profilerun_ERS7_2.4.txt	Tue Aug  9 23:35:14 2005
@@ -0,0 +1,119 @@
+Setup:
+  Default build for ERS-2xx (TGT_ERS2xx)
+  Pink ball in view (8.5in from snout)
+  Press power button, start timer
+  Telnet to system console (port 59000)
+  Connect ControllerGUI
+  STARTUP script:
+    Launch StareAtBallBehavior (leave E-Stop ON)
+    Navigate to Status Reports -> Profiler
+  Wait until 5 minutes from initial press of power button.
+  Recorded profiler run shown below
+ 
+~~~ Main: ~~~
+Profiling information since: 17.556942 to 297.868945
+ReadySendJoints():
+        1 calls
+        0.009000 ms avg
+        0.009000 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        0.000000 ms avg inter (Inf fps)
+        0.000000 ms exp.avg (Inf fps)
+        Exec: 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+GotSensorFrame():
+        8727 calls
+        0.806189 ms avg
+        0.774136 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        32.024136 ms avg inter (31.226447 fps)
+        31.421780 ms exp.avg (31.825058 fps)
+        Exec: 0 0 4395 4332 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 1 2 28 8336 357 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+GotAudio():
+        8726 calls
+        0.195090 ms avg
+        0.138485 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        32.036403 ms avg inter (31.214491 fps)
+        32.031750 ms exp.avg (31.219027 fps)
+        Exec: 0 2030 6664 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 1 1 1 8718 2 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+GotImage():
+        8368 calls
+        9.210970 ms avg
+        9.374177 ms exp.avg
+        7.652236 ms avg child time (83.000000%)
+        33.403262 ms avg inter (29.937196 fps)
+        32.999611 ms exp.avg (30.303387 fps)
+        Exec: 0 0 29 7 0 8328 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 1 1 1 6934 1428 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+PowerEvent():
+        16 calls
+        25.260625 ms avg
+        35.200535 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        17064.880625 ms avg inter (0.058600 fps)
+        18500.957031 ms exp.avg (0.054051 fps)
+        Exec: 0 1 13 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 14
+BallDetection::processEvent():
+        8335 calls
+        7.682573 ms avg
+        7.838047 ms exp.avg
+        6.915032 ms avg child time (90.000000%)
+        33.338823 ms avg inter (29.995060 fps)
+        32.965073 ms exp.avg (30.335138 fps)
+        Exec: 2 0 1 0 0 8330 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 1 1 0 0 2 1 6907 1422 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+RegionGenerator::calcImage(...):
+        8332 calls
+        6.917521 ms avg
+        7.068184 ms exp.avg
+        6.640900 ms avg child time (96.000000%)
+        33.353379 ms avg inter (29.981970 fps)
+        32.968765 ms exp.avg (30.331738 fps)
+        Exec: 0 0 0 0 0 8330 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 1 1 6907 1422 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+RLEGenerator::calcImage(...):
+        8332 calls
+        6.640900 ms avg
+        6.789381 ms exp.avg
+        5.014728 ms avg child time (75.500000%)
+        33.353191 ms avg inter (29.982139 fps)
+        32.968517 ms exp.avg (30.331968 fps)
+        Exec: 0 0 0 0 0 8332 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 1 1 6907 1422 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+SegmentedColorGenerator::calcImage(...):
+        8332 calls
+        5.014728 ms avg
+        5.147758 ms exp.avg
+        0.020552 ms avg child time (0.400000%)
+        33.353314 ms avg inter (29.982029 fps)
+        32.968628 ms exp.avg (30.331865 fps)
+        Exec: 0 0 0 0 5241 3091 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 0 0 0 0 0 1 1 6907 1422 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+RawCameraGenerator::calcImage(...):
+        24996 calls
+        0.006851 ms avg
+        0.006298 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        11.116064 ms avg inter (89.959896 fps)
+        9.098195 ms exp.avg (109.911903 fps)
+        Exec: 16663 8332 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+        Inter: 8198 8465 1 0 0 1 1 6907 1422 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+Bucket distribution (in ms):
+        0<0.00802, <0.133, <0.686, <2.2, <5.43, <11.4, <21.2, <36.4, <58.7, <90, <132, <188, <260, <352, <465, <604, <772, <973, <1.21e+03, <1.49e+03, <1.82e+03, <2.19e+03, <2.63e+03, <3.12e+03, <3.68e+03, <4.31e+03, <5.03e+03, <5.82e+03, <6.71e+03, <7.7e+03, <8.79e+03, <1e+04,
+~~~ Motion: ~~~
+Profiling information since: 17.557096 to 297.876168
+ReadySendJoints():
+        8717 calls
+        1.728631 ms avg
+        1.584685 ms exp.avg
+        0.000000 ms avg child time (0.000000%)
+        32.065137 ms avg inter (31.186519 fps)
+        32.081375 ms exp.avg (31.170732 fps)
+        Exec: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8716
+        Inter: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8716
+Bucket distribution (in ms):
+        0<0.00802, <0.133, <0.686, <2.2, <5.43, <11.4, <21.2, <36.4, <58.7, <90, <132, <188, <260, <352, <465, <604, <772, <973, <1.21e+03, <1.49e+03, <1.82e+03, <2.19e+03, <2.63e+03, <3.12e+03, <3.68e+03, <4.31e+03, <5.03e+03, <5.82e+03, <6.71e+03, <7.7e+03, <8.79e+03, <1e+04,
diff -urdN ../Tekkotsu_2.3/docs/builddocs ./docs/builddocs
--- ../Tekkotsu_2.3/docs/builddocs	Tue Jan  4 18:29:22 2005
+++ ./docs/builddocs	Wed Aug 10 11:01:05 2005
@@ -15,7 +15,7 @@
 searchengine="SEARCHENGINE = NO";
 enabled_sections="ENABLED_SECTIONS += INTERNAL";
 input="$src";
-exclude="$input/TinyFTPD $input/ms $input/tools $input/contrib $input/deprecated $input/Shared/jpeg-6b $input/Motion/Spline.h $input/Motion/gvector.h $input/Motion/Path.h $input/SoundPlay/WAV.h $input/SoundPlay/WAV.cc $input/Wireless/ionetstream.h $input/Motion/OldKinematics.h $input/Motion/OldKinematics.cc $input/Motion/Geometry.h $input/Shared/Util.h $input/project/templates";
+exclude="$input/build $input/TinyFTPD $input/ms $input/tools $input/contrib $input/deprecated $input/Shared/jpeg-6b $input/Motion/Spline.h $input/Motion/gvector.h $input/Motion/Path.h $input/SoundPlay/WAV.h $input/SoundPlay/WAV.cc $input/Wireless/ionetstream.h $input/Motion/OldKinematics.h $input/Motion/OldKinematics.cc $input/Motion/Geometry.h $input/Shared/Util.h $input/project/templates";
 
 while [ $# -gt 0 ] ; do
 	case $1 in
@@ -80,7 +80,7 @@
 
 if [ $search -ne 0 ] ; then
 	printf "Updating search.php form action...";
-	"${src}/tools/filewordreplace" -c "@" -q '"search.php"' '"http://cvs.tekkotsu.org/search.php"' "$target/*.html";
+	find "$target" -name "*.html" -exec "${src}/tools/filewordreplace" -c "@" -q '"search.php"' '"http://cvs.tekkotsu.org/search.php"' \{\} \;;
 	printf "done\n";
 fi;
 
diff -urdN ../Tekkotsu_2.3/docs/doxygencfg ./docs/doxygencfg
--- ../Tekkotsu_2.3/docs/doxygencfg	Fri Jan 28 20:06:23 2005
+++ ./docs/doxygencfg	Sun Aug  7 00:11:04 2005
@@ -1,4 +1,4 @@
-# Doxyfile 1.3.9.1
+# Doxyfile 1.4.4
 
 # This file describes the settings to be used by the documentation system
 # doxygen (www.doxygen.org) for a project
@@ -23,7 +23,7 @@
 # This could be handy for archiving the generated documentation or 
 # if some version control system is used.
 
-PROJECT_NUMBER         = 2.3
+PROJECT_NUMBER         = 2.4
 
 # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) 
 # base path where the generated documentation will be put. 
@@ -31,14 +31,14 @@
 # where doxygen was started. If left blank the current directory will be used.
 
 #builddocs will set this in doxygenbuildcfg
-#OUTPUT_DIRECTORY      = generated
+#OUTPUT_DIRECTORY       = generated
 
 # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 
 # 4096 sub-directories (in 2 levels) under the output directory of each output 
 # format and will distribute the generated files over these directories. 
-# Enabling this option can be useful when feeding doxygen a huge amount of source 
-# files, where putting all generated files in the same directory would otherwise 
-# cause performance problems for the file system.
+# Enabling this option can be useful when feeding doxygen a huge amount of 
+# source files, where putting all generated files in the same directory would 
+# otherwise cause performance problems for the file system.
 
 CREATE_SUBDIRS         = NO
 
@@ -81,11 +81,12 @@
 # This tag implements a quasi-intelligent brief description abbreviator 
 # that is used to form the text in various listings. Each string 
 # in this list, if found as the leading text of the brief description, will be 
-# stripped from the text and the result after processing the whole list, is used 
-# as the annotated text. Otherwise, the brief description is used as-is. If left 
-# blank, the following values are used ("$name" is automatically replaced with the 
-# name of the entity): "The $name class" "The $name widget" "The $name file" 
-# "is" "provides" "specifies" "contains" "represents" "a" "an" "the"
+# stripped from the text and the result after processing the whole list, is 
+# used as the annotated text. Otherwise, the brief description is used as-is. 
+# If left blank, the following values are used ("$name" is automatically 
+# replaced with the name of the entity): "The $name class" "The $name widget" 
+# "The $name file" "is" "provides" "specifies" "contains" 
+# "represents" "a" "an" "the"
 
 ABBREVIATE_BRIEF       = 
 
@@ -94,12 +95,12 @@
 # description.
 
 #builddocs will set this in doxygenbuildcfg
-#ALWAYS_DETAILED_SEC    = NO
+#ALWAYS_DETAILED_SEC    = YES
 
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited 
-# members of a class in the documentation of that class as if those members were 
-# ordinary class members. Constructors, destructors and assignment operators of 
-# the base classes will not be shown.
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all 
+# inherited members of a class in the documentation of that class as if those 
+# members were ordinary class members. Constructors, destructors and assignment 
+# operators of the base classes will not be shown.
 
 INLINE_INHERITED_MEMB  = NO
 
@@ -169,6 +170,12 @@
 
 DISTRIBUTE_GROUP_DOC   = YES
 
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce 
+# a new page for each member. If set to NO, the documentation of a member will 
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
 # The TAB_SIZE tag can be used to set the number of spaces in a tab. 
 # Doxygen uses this value to replace tabs by spaces in code fragments.
 
@@ -183,8 +190,8 @@
 
 ALIASES                = 
 
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources 
-# only. Doxygen will then generate output that is more tailored for C. 
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C 
+# sources only. Doxygen will then generate output that is more tailored for C. 
 # For instance, some of the names that are used will be different. The list 
 # of all members will be omitted, etc.
 
@@ -352,6 +359,7 @@
 # The ENABLED_SECTIONS tag can be used to enable conditional 
 # documentation sections, marked by \if sectionname ... \endif.
 
+#builddocs will set this in doxygenbuildcfg
 ENABLED_SECTIONS       = 
 
 # The MAX_INITIALIZER_LINES tag determines the maximum number of lines 
@@ -372,10 +380,20 @@
 
 # If the sources in your project are distributed over multiple directories 
 # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy 
-# in the documentation.
+# in the documentation. The default is YES.
 
 SHOW_DIRECTORIES       = YES
 
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that 
+# doxygen should invoke to get the current version for each file (typically from the 
+# version control system). Doxygen will invoke the program by executing (via 
+# popen()) the command <command> <input-file>, where <command> is the value of 
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file 
+# provided by doxygen. Whatever the progam writes to standard output 
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    = 
+
 #---------------------------------------------------------------------------
 # configuration options related to warning and progress messages
 #---------------------------------------------------------------------------
@@ -404,10 +422,20 @@
 
 WARN_IF_DOC_ERROR      = YES
 
+# This WARN_NO_PARAMDOC option can be abled to get warnings for 
+# functions that are documented, but have no documentation for their parameters 
+# or return value. If set to NO (the default) doxygen will only warn about 
+# wrong or incomplete parameter documentation, but not about the absence of 
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
 # The WARN_FORMAT tag determines the format of the warning messages that 
 # doxygen can produce. The string should contain the $file, $line, and $text 
 # tags, which will be replaced by the file and line number from which the 
-# warning originated and the warning text.
+# warning originated and the warning text. Optionally the format may contain 
+# $version, which will be replaced by the version of the file (if it could 
+# be obtained via FILE_VERSION_FILTER)
 
 WARN_FORMAT            = "$file:$line: $text"
 
@@ -433,8 +461,8 @@
 # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp 
 # and *.h) to filter out the source-files in the directories. If left 
 # blank the following patterns are tested: 
-# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp 
-# *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx 
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm
 
 FILE_PATTERNS          = 
 
@@ -448,24 +476,28 @@
 # excluded from the INPUT source files. This way you can easily exclude a 
 # subdirectory from a directory tree whose root is specified with the INPUT tag.
 
--#builddocs will set this in doxygenbuildcfg
--#EXCLUDE                = 
-
+#builddocs will set this in doxygenbuildcfg
+EXCLUDE                = 
 
-# The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories 
-# that are symbolic links (a Unix filesystem feature) are excluded from the input.
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or 
+# directories that are symbolic links (a Unix filesystem feature) are excluded 
+# from the input.
 
 EXCLUDE_SYMLINKS       = NO
 
 # If the value of the INPUT tag contains directories, you can use the 
 # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude 
-# certain files from those directories.
+# certain files from those directories. Note that the wildcards are matched 
+# against the file with absolute path, so to exclude all test directories 
+# for example use the pattern */test/*
 
 EXCLUDE_PATTERNS       = */docs/*.h \
                          */docs/*.cc \
                          */Shared/newmat/* \
                          */Motion/roboop/* \
-                         */project/*
+                         */project/* \
+                         */local/* \
+                         */aperios/*
 
 # The EXAMPLE_PATH tag can be used to specify one or more files or 
 # directories that contain example code fragments that are included (see 
@@ -552,6 +584,14 @@
 
 REFERENCES_RELATION    = NO
 
+# If the USE_HTAGS tag is set to YES then the references to source code 
+# will point to the HTML generated by the htags(1) tool instead of doxygen 
+# built-in source browser. The htags tool is part of GNU's global source 
+# tagging system (see http://www.gnu.org/software/global/global.html). You 
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
 # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen 
 # will generate a verbatim copy of the header file for each class for 
 # which an include is specified. Set to NO to disable this.
@@ -984,8 +1024,8 @@
 # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then 
 # doxygen's preprocessor will remove all function-like macros that are alone 
 # on a line, have an all uppercase name, and do not end with a semicolon. Such 
-# function macros are typically used for boiler-plate code, and will confuse the 
-# parser if not removed.
+# function macros are typically used for boiler-plate code, and will confuse 
+# the parser if not removed.
 
 SKIP_FUNCTION_MACROS   = NO
 
@@ -1015,7 +1055,7 @@
 # a tag file that is based on the input files it reads.
 
 #builddocs will set this in doxygenbuildcfg
-#GENERATE_TAGFILE       = 
+#GENERATE_TAGFILE       = generated/tekkotsu.tag
 
 # If the ALLEXTERNALS tag is set to YES all external classes will be listed 
 # in the class index. If set to NO only the inherited external classes 
@@ -1039,10 +1079,11 @@
 #---------------------------------------------------------------------------
 
 # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will 
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base or 
-# super classes. Setting the tag to NO turns the diagrams off. Note that this 
-# option is superseded by the HAVE_DOT option below. This is only a fallback. It is 
-# recommended to install and use dot, since it yields more powerful graphs.
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base 
+# or super classes. Setting the tag to NO turns the diagrams off. Note that 
+# this option is superseded by the HAVE_DOT option below. This is only a 
+# fallback. It is recommended to install and use dot, since it yields more 
+# powerful graphs.
 
 CLASS_DIAGRAMS         = YES
 
@@ -1073,6 +1114,11 @@
 
 COLLABORATION_GRAPH    = NO
 
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen 
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
 # If the UML_LOOK tag is set to YES doxygen will generate inheritance and 
 # collaboration diagrams in a style similar to the OMG's Unified Modeling 
 # Language.
@@ -1111,6 +1157,13 @@
 
 GRAPHICAL_HIERARCHY    = NO
 
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES 
+# then doxygen will show the dependencies a directory has on other directories 
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
 # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images 
 # generated by dot. Possible values are png, jpg, or gif
 # If left blank png will be used.
@@ -1118,7 +1171,7 @@
 DOT_IMAGE_FORMAT       = png
 
 # The tag DOT_PATH can be used to specify the path where the dot tool can be 
-# found. If left blank, it is assumed the dot tool can be found on the path.
+# found. If left blank, it is assumed the dot tool can be found in the path.
 
 DOT_PATH               = 
 
@@ -1146,15 +1199,31 @@
 
 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the 
 # graphs generated by dot. A depth value of 3 means that only nodes reachable 
-# from the root by following a path via at most 3 edges will be shown. Nodes that 
-# lay further from the root node will be omitted. Note that setting this option to 
-# 1 or 2 may greatly reduce the computation time needed for large code bases. Also 
-# note that a graph may be further truncated if the graph's image dimensions are 
-# not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH and MAX_DOT_GRAPH_HEIGHT). 
-# If 0 is used for the depth value (the default), the graph is not depth-constrained.
+# from the root by following a path via at most 3 edges will be shown. Nodes 
+# that lay further from the root node will be omitted. Note that setting this 
+# option to 1 or 2 may greatly reduce the computation time needed for large 
+# code bases. Also note that a graph may be further truncated if the graph's 
+# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH 
+# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), 
+# the graph is not depth-constrained.
 
 MAX_DOT_GRAPH_DEPTH    = 0
 
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent 
+# background. This is disabled by default, which results in a white background. 
+# Warning: Depending on the platform used, enabling this option may lead to 
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to 
+# read).
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output 
+# files in one run (i.e. multiple -o and -T options on the command line). This 
+# makes dot run faster, but since only newer versions of dot (>1.8.10) 
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = NO
+
 # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will 
 # generate a legend page explaining the meaning of the various boxes and 
 # arrows in the dot generated graphs.
@@ -1182,4 +1251,3 @@
 #---------------------------------------------------------------------------
 
 @INCLUDE = doxygenbuildcfg
-
diff -urdN ../Tekkotsu_2.3/docs/doxygenhead.html ./docs/doxygenhead.html
--- ../Tekkotsu_2.3/docs/doxygenhead.html	Tue Jan  4 18:29:22 2005
+++ ./docs/doxygenhead.html	Tue Jul 19 19:35:22 2005
@@ -3,7 +3,10 @@
 	<head>
 		<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
 		<title>$title</title>
-		<link href="doxygen.css" rel="stylesheet" type="text/css">
+		<link type="text/css" rel="stylesheet" href="doxygen.css">
+		<link type="text/css" rel="stylesheet" href="../tutorialcode.css">
+		<link type="text/css" rel="stylesheet" href="../tekkotsu.css">
+		<link type="text/css" rel="stylesheet" href="doxygen-override.css">
 		<link rel="home" href="../index.html">
 		<link rel="up" href="../index.html">
 		<link rel="SHORTCUT ICON" href="favicon.ico">
@@ -18,15 +21,15 @@
 					<!-- #Bar# --> <td style="vertical-align: top; background-color: rgb(0, 0, 0);"><br></td>
 					<!-- #Demos# --> <td style="vertical-align: top;"><a target="_top" href="../Samples.html">Demos</a></td>
 					<!-- #Bar# --> <td style="vertical-align: top; background-color: rgb(0, 0, 0);"><br></td>
-					<!-- #Overview# --> <td style="vertical-align: top;"><a target="_top" href="../Overview.html">Overview</a></td>
+					<!-- #Overview# --> <td style="vertical-align: top;"><a target="_top" href="../ArchitecturalOverview.html">Overview</a></td>
 					<!-- #Bar# --> <td style="vertical-align: top; background-color: rgb(0, 0, 0);"><br></td>
-					<!-- #Downloads# --> <td style="vertical-align: top;"><a target="_top" href="../VersionHistory.html">Downloads</a></td>
+					<!-- #Downloads# --> <td style="vertical-align: top;"><a target="_top" href="../downloads.html">Downloads</a></td>
 					<!-- #Bar# --> <td style="vertical-align: top; background-color: rgb(0, 0, 0);"><br></td>
-					<!-- #Tutorials# --> <td style="vertical-align: top;"><a target="_top" href="../Tutorials.html">Tutorials</a></td>
+					<!-- #Tutorials# --> <td style="vertical-align: top;"><a target="_top" href="../development.html">Tutorials</a></td>
 					<!-- #Bar# --> <td style="vertical-align: top; background-color: rgb(0, 0, 0);"><br></td>
 					<!-- #Current# --><!-- #Reference# --> <td style="vertical-align: top;"><i>Reference</i></td>
 					<!-- #Bar# --> <td style="vertical-align: top; background-color: rgb(0, 0, 0);"><br></td>
-					<!-- #Credits# --> <td style="vertical-align: top;"><a target="_top" href="../Credits.html">Credits</a> </td>
+					<!-- #Credits# --> <td style="vertical-align: top;"><a target="_top" href="../acknowledgements.html">Credits</a> </td>
 				</tr>
 			</tbody>
 		</table>
diff -urdN ../Tekkotsu_2.3/docs/html/CVS/Entries ./docs/html/CVS/Entries
--- ../Tekkotsu_2.3/docs/html/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./docs/html/CVS/Entries	Wed Aug 10 11:03:26 2005
@@ -0,0 +1,19 @@
+/.htaccess/1.4/Wed Jan 21 08:15:40 2004//Ttekkotsu-2_4
+/NumberLEDs.jpg/1.4/Wed Oct 15 01:20:16 2003/-kb/Ttekkotsu-2_4
+/Waypoint_Abs.png/1.1/Tue Aug  9 20:44:16 2005/-kb/Ttekkotsu-2_4
+/Waypoint_AngleAbs.png/1.1/Tue Aug  9 20:44:16 2005/-kb/Ttekkotsu-2_4
+/Waypoint_AngleRel.png/1.1/Tue Aug  9 20:44:16 2005/-kb/Ttekkotsu-2_4
+/Waypoint_Arc.png/1.1/Tue Aug  9 20:44:16 2005/-kb/Ttekkotsu-2_4
+/Waypoint_Ego.png/1.1/Tue Aug  9 20:44:16 2005/-kb/Ttekkotsu-2_4
+/Waypoint_Error.png/1.1/Tue Aug  9 20:44:16 2005/-kb/Ttekkotsu-2_4
+/Waypoint_Off.png/1.1/Tue Aug  9 20:44:16 2005/-kb/Ttekkotsu-2_4
+/aibo.jpg/1.1/Thu Jan  9 02:03:00 2003/-kb/Ttekkotsu-2_4
+/aibopup.jpg/1.1/Thu Jan  9 02:03:01 2003/-kb/Ttekkotsu-2_4
+/aibosmall.jpg/1.1/Thu Jan  9 02:03:01 2003/-kb/Ttekkotsu-2_4
+/doxygen-override.css/1.1/Wed Jul 20 00:00:17 2005//Ttekkotsu-2_4
+/doxygen.css/1.7/Tue Jul 19 23:35:27 2005//Ttekkotsu-2_4
+/favicon.ico/1.3/Sun Dec  5 04:04:54 2004/-kb/Ttekkotsu-2_4
+/index.html/1.46/Sun Aug  7 04:11:04 2005//Ttekkotsu-2_4
+/robots.txt/1.1/Thu Jan  9 02:03:01 2003//Ttekkotsu-2_4
+/search.png/1.1/Fri Oct 10 21:32:51 2003/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/docs/html/CVS/Repository ./docs/html/CVS/Repository
--- ../Tekkotsu_2.3/docs/html/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./docs/html/CVS/Repository	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+Tekkotsu/docs/html
diff -urdN ../Tekkotsu_2.3/docs/html/CVS/Root ./docs/html/CVS/Root
--- ../Tekkotsu_2.3/docs/html/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./docs/html/CVS/Root	Wed Aug 10 11:03:25 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/docs/html/CVS/Tag ./docs/html/CVS/Tag
--- ../Tekkotsu_2.3/docs/html/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./docs/html/CVS/Tag	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
Binary files ../Tekkotsu_2.3/docs/html/Waypoint_Abs.png and ./docs/html/Waypoint_Abs.png differ
Binary files ../Tekkotsu_2.3/docs/html/Waypoint_AngleAbs.png and ./docs/html/Waypoint_AngleAbs.png differ
Binary files ../Tekkotsu_2.3/docs/html/Waypoint_AngleRel.png and ./docs/html/Waypoint_AngleRel.png differ
Binary files ../Tekkotsu_2.3/docs/html/Waypoint_Arc.png and ./docs/html/Waypoint_Arc.png differ
Binary files ../Tekkotsu_2.3/docs/html/Waypoint_Ego.png and ./docs/html/Waypoint_Ego.png differ
Binary files ../Tekkotsu_2.3/docs/html/Waypoint_Error.png and ./docs/html/Waypoint_Error.png differ
Binary files ../Tekkotsu_2.3/docs/html/Waypoint_Off.png and ./docs/html/Waypoint_Off.png differ
diff -urdN ../Tekkotsu_2.3/docs/html/doxygen-override.css ./docs/html/doxygen-override.css
--- ../Tekkotsu_2.3/docs/html/doxygen-override.css	Wed Dec 31 19:00:00 1969
+++ ./docs/html/doxygen-override.css	Tue Jul 19 20:00:17 2005
@@ -0,0 +1,5 @@
+H1 { letter-spacing: 0; margin-top: 1em; }
+H2 { letter-spacing: .1em; border: none; text-align:left; margin-bottom: 0px; }
+PRE.fragment { border:none; background-color:none; margin:0; padding:10px 0; }
+P {
+}
diff -urdN ../Tekkotsu_2.3/docs/html/doxygen.css ./docs/html/doxygen.css
--- ../Tekkotsu_2.3/docs/html/doxygen.css	Tue Jan  4 13:53:34 2005
+++ ./docs/html/doxygen.css	Tue Jul 19 19:35:27 2005
@@ -1,3 +1,4 @@
+/*
 H1 {
 	text-align: center;
 	font-family: Arial, Helvetica, sans-serif;
@@ -9,6 +10,7 @@
 P {
 	width: 620px;
 }
+*/
 CAPTION { font-weight: bold }
 DIV.qindex {
 	background-color: #eeeeff;
@@ -70,7 +72,7 @@
 A.code:visited { text-decoration: none; font-weight: normal; color: #0000FF}
 A.codeRef:link { font-weight: normal; color: #0000FF}
 A.codeRef:visited { font-weight: normal; color: #0000FF}
-A:hover { text-decoration: none; background-color: #f2f2ff }
+/*A:hover { text-decoration: none; background-color: #f2f2ff }*/
 DL.el { margin-left: -1cm }
 .fragment {
        font-family: monospace;
diff -urdN ../Tekkotsu_2.3/docs/html/index.html ./docs/html/index.html
--- ../Tekkotsu_2.3/docs/html/index.html	Fri Jan 28 20:06:23 2005
+++ ./docs/html/index.html	Sun Aug  7 00:11:04 2005
@@ -1,15 +1,13 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 <html>
 <head>
+<!--#include virtual="../setup.shtml" -->
   <meta content="text/html;charset=iso-8859-1" http-equiv="Content-Type">
-  <title>Tekkotsu Framework</title>
+  <title>Tekkotsu: Reference Documenation</title>
   <link type="text/css" rel="stylesheet" href="doxygen.css">
-  <link href="../index.html" rel="home">
-  <link href="../index.html" rel="up">
-  <link href="../index.html" rel="first">
-  <link href="../Credits.html" rel="last">
-  <link href="../Tutorials.html" rel="previous">
-  <link href="../Credits.html" rel="next">
+	<link type="text/css" rel="stylesheet" href="../tutorialcode.css">
+	<link type="text/css" rel="stylesheet" href="../tekkotsu.css">
+	<link type="text/css" rel="stylesheet" href="doxygen-override.css">
   <link href="favicon.ico" rel="SHORTCUT ICON">
 </head>
 <body>
@@ -28,17 +26,17 @@
  style="vertical-align: top; background-color: rgb(0, 0, 0);"><br>
       </td>
 <!-- #Overview# --> <td style="vertical-align: top;"><a
- href="../Overview.html" target="_top">Overview</a></td>
+ href="../ArchitecturalOverview.html" target="_top">Overview</a></td>
 <!-- #Bar# --> <td
  style="vertical-align: top; background-color: rgb(0, 0, 0);"><br>
       </td>
 <!-- #Downloads# --> <td style="vertical-align: top;"><a
- href="../QuickStart.html" target="_top">Downloads</a></td>
+ href="../downloads.html" target="_top">Downloads</a></td>
 <!-- #Bar# --> <td
  style="vertical-align: top; background-color: rgb(0, 0, 0);"><br>
       </td>
 <!-- #Tutorials# --> <td style="vertical-align: top;"><a
- href="../Tutorials.html" target="_top">Tutorials</a></td>
+ href="../development.html" target="_top">Tutorials</a></td>
 <!-- #Bar# --> <td
  style="vertical-align: top; background-color: rgb(0, 0, 0);"><br>
       </td>
@@ -48,7 +46,7 @@
  style="vertical-align: top; background-color: rgb(0, 0, 0);"><br>
       </td>
 <!-- #Credits# --> <td style="vertical-align: top;"><a
- href="../Credits.html" target="_top">Credits</a> </td>
+ href="../acknowledgements.html" target="_top">Credits</a> </td>
     </tr>
   </tbody>
 </table>
@@ -58,7 +56,7 @@
   <tbody>
     <tr>
       <td style="vertical-align: top;">
-<div class="qindex">  <form class="search" action="http://cvs.tekkotsu.org/search.php" method="get">
+<div class="qindex">  <form class="search" action="http://cvs.tekkotsu.org/search.php" method="get" name="doxyform">
 <table border=0 class="qindex"><tr><td width="20%" align="center"><a class="qindexHL" href="main.html">Main&nbsp;Page</a></td>
 <td width="0px" bgcolor="000000"></td>
 <td valign="top" width="20%" align="left"><b>Classes: </b><center><a class="qindex" href="annotated.html">List</a>, <a class="qindex" href="classes.html">Index</a>, <a class="qindex" href="hierarchy.html">Hierarchy</a>, <a class="qindex" href="functions.html">Members</a></center></td>
@@ -67,22 +65,22 @@
 <td width="0px" bgcolor="000000"></td>
 <td valign="top" width="20%" align="left"><b>Files: </b><center><a class="qindex" href="files.html">List</a>, <a class="qindex" href="dirs.html">Directories</a>, <a class="qindex" href="globals.html">Members</a></center></td>
 <td width="0px" bgcolor="000000"></td>
-<td valign="top" width="20%" align="center"><a class="qindex" href="pages.html">Other&nbsp;Pages</a><hr><span class="search"><u>S</u>earch&nbsp;<input class="search" type="text" name="query" value="" size="10" accesskey="s"/></span></td>
+<td valign="top" width="20%" align="center"><a class="qindex" href="pages.html">Other&nbsp;Pages</a><hr><span class="search"><u>S</u>earch&nbsp;<input value="0" name="page" type="hidden"><input class="search" type="text" name="query" value="" size="10" accesskey="s"/></span></td>
 </tr></table></form>
 </div>
 <center>
-<h1>Tekkotsu Source Documentation</h1>
+<h1>Tekkotsu Reference Documentation</h1>
 </center>
       <div style="text-align: center;"> </div>
       <p style="text-align: center;"><a target="_top" href="index.html">Frames</a>
 | <a target="_top" href="main.html">No Frames</a><br>
       </p>
       <h3>Documentation Contents:</h3>
-      <p style="margin-left: 40px;">If you want a more general overview
+      <p>If you want a more general overview
 of what this software does and how the pieces fit together, you may
 want
 to visit the <a target="_top" href="../Overview.html">overview</a>.</p>
-      <ul style="margin-left: 40px;">
+      <ul>
         <li><a href="classes.html">Alphabetical Index</a> - Lists all
 classes and structs<br>
         </li>
@@ -109,10 +107,7 @@
  height="16" type="image" width="74"></form>
         </li>
       </ul>
-      <ul style="margin-left: 40px;">
-      </ul>
-      <div style="margin-left: 40px;"> </div>
-      <p style="margin-left: 40px;">These documents will give you
+      <p>These documents will give you
 nitty-gritty details on the individual functions, classes, and data
 structures. &nbsp;It is collated from comments embedded in the source
 code by <a href="http://www.doxygen.org/">doxygen</a>.&nbsp; Expect a
@@ -123,32 +118,31 @@
 line</a>!<br>
       </p>
       <h3>Documentation Download:</h3>
-      <p style="margin-left: 40px;">If you would like to obtain local
-static copies of the documentation, there are two formats:<br>
-      </p>
-      <ul style="margin-left: 40px;">
-        <li><a href="../media/Tekkotsu_doc_2.3.tar.gz">HTML</a>
-(v2.3)</li>
+      <p>If you would like to obtain a local
+copy of the reference materials, you may download a tarball of this site:<br>
+      <ul>
+        <li><a href="../media/Tekkotsu_doc_<!--#echo var="current_version" -->.tar.gz">HTML</a>
+(v<!--#echo var="current_version" -->, <!--#fsize virtual="../media/Tekkotsu_doc_${current_version}.tar.gz" -->B)</li>
       </ul>
-      <div style="margin-left: 40px;">If you're using the most recent
+      </p>
+      <p>If you're using the most recent
 version from the <a href="http://cvs.tekkotsu.org/">CVS repository</a>,
 you can build the corresponding documentation locally by typing <span
  style="font-family: monospace;">make docs</span> in the root Tekkotsu
 directory.<br>
-      </div>
+      </p>
       <h3>External Documentation:<br>
       </h3>
-      <p style="margin-left: 40px;">We make use of two independent
+      <p>We have integrated two independent
 libraries: the <a href="http://www.robertnz.net/nm_intro.htm"
  target="_top">newmat</a> matrix library
 and the <a href="http://www.cours.polymtl.ca/roboop/" target="_top">ROBOOP</a>
 kinematics library. We mirror their own doxygen documentation on our
 site so that our documentation can link to it.
       </p>
-      <p style="margin-left: 40px;">You can directly access these
+      <p>You can directly access these
 libraries' documentation with these links:
-      </p>
-      <ul style="margin-left: 40px;">
+      <ul>
         <li><a href="newmat/index.html" target="_top">newmat</a>
 Documentation
         </li>
@@ -156,9 +150,17 @@
 Documentation
         </li>
       </ul>
-      <p></p>
-      <p></p>
-      <p style="margin-left: 40px;"> This code is originally based on
+      </p>
+      <p>In addition, we provide precompiled copies of several other libraries for the AIBO platform.
+You may wish to make use of their references as well:
+<ul>
+<li><a href="http://www.ijg.org/files/">libjpeg</a> - lossy image compression</li>
+<li><a href="http://www.libpng.org/pub/png/libpng-1.2.5-manual.html">libpng</a> - lossless image compression</li>
+<li><a href="http://xmlsoft.org/html/index.html">libxml2</a> - XML generation and parsing</li>
+<li><a href="http://www.zlib.net/manual.html">zlib</a> - compression utilities</li>
+</ul>
+</p>
+      <p> This code is originally based on
 an early version of CMU's
 2002 Legged RoboSoccer entry, <a
  href="http://www-2.cs.cmu.edu/%7Erobosoccer/legged/legged-team.html">CMPack</a>.
@@ -168,7 +170,7 @@
 still fall under their <a href="CMPack_license.txt">license</a>.
 &nbsp;This license is also included in the files themselves.<br>
       </p>
-      <p style="margin-left: 40px;"> Note that although we include the
+      <p> Note that although we include the
 CMVision classes within our reference section, CMVision does not have
 any inline doxygen documentation.&nbsp; However, there is some external
 documentation as <a
diff -urdN ../Tekkotsu_2.3/local/CVS/Entries ./local/CVS/Entries
--- ../Tekkotsu_2.3/local/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./local/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,3 @@
+/Makefile.local/1.2/Wed Jun  1 05:48:06 2005//Ttekkotsu-2_4
+/minisim.h/1.4/Mon Aug  1 23:18:00 2005//Ttekkotsu-2_4
+D/sim////
diff -urdN ../Tekkotsu_2.3/local/CVS/Repository ./local/CVS/Repository
--- ../Tekkotsu_2.3/local/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./local/CVS/Repository	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Tekkotsu/local
diff -urdN ../Tekkotsu_2.3/local/CVS/Root ./local/CVS/Root
--- ../Tekkotsu_2.3/local/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./local/CVS/Root	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/local/CVS/Tag ./local/CVS/Tag
--- ../Tekkotsu_2.3/local/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./local/CVS/Tag	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/local/Makefile.local ./local/Makefile.local
--- ../Tekkotsu_2.3/local/Makefile.local	Wed Dec 31 19:00:00 1969
+++ ./local/Makefile.local	Wed Jun  1 01:48:06 2005
@@ -0,0 +1,17 @@
+ifeq ($(TEKKOTSU_ENVIRONMENT_CONFIGURATION),)
+$(error This makefile is not meant to be run directly.  It is intended to contain local-specific build instructions.  Please run 'make' from the main project directory.);
+endif
+
+.PHONY: 
+
+#Each directory should represent a separate executable
+EXECS:=$(filter-out CVS,$(subst local/,,$(shell find local -mindepth 1 -maxdepth 1 -type d -prune)))
+
+ESRCS:=$(shell find local -name "*$(SRCSUFFIX)")
+DEPENDS:=$(DEPENDS) $(addprefix $(TK_BD)/,$(ESRCS:$(SRCSUFFIX)=.d))
+
+ifeq ($(shell uname | grep -ci cygwin),0)
+  PLATFORM_FLAGS:=$(PLATFORM_FLAGS) -DHAVE_READDIR_R
+endif
+
+platformBuild: $(addprefix $(TK_BD)/,$(ESRCS:$(SRCSUFFIX)=.o)) $(TK_BD)/libtekkotsu.a
diff -urdN ../Tekkotsu_2.3/local/minisim.h ./local/minisim.h
--- ../Tekkotsu_2.3/local/minisim.h	Wed Dec 31 19:00:00 1969
+++ ./local/minisim.h	Mon Aug  1 19:18:00 2005
@@ -0,0 +1,179 @@
+//-*-c++-*-
+#ifndef INCLUDED_minisim_h_
+#define INCLUDED_minisim_h_
+
+#ifdef TK_ENABLE_CONFIG
+#  include "Shared/Config.h"
+#endif
+
+#ifdef TK_ENABLE_EROUTER
+#  include "Events/EventRouter.h"
+#endif
+
+#ifdef TK_ENABLE_WIRELESS
+#  include "Wireless/Wireless.h"
+#  include "IPC/Thread.h"
+#endif
+#ifdef TK_ENABLE_SOUTSERR
+#  include "Wireless/Socket.h"
+#endif
+
+#ifdef TK_ENABLE_KINEMATICS
+#  include <iostream>
+#  include "Shared/Config.h"
+#  include "Motion/Kinematics.h"
+#endif
+
+#define TK_cstr(s) TK_str(s)
+#define TK_str(s) #s
+
+//! description of minisim
+namespace minisim {
+#ifdef TK_ENABLE_WIRELESS
+	class WirelessThread : public Thread {
+	public:
+		virtual unsigned int runloop() {
+			// initial setup done by wireless's own constructor
+			wireless->pollTest(NULL); // by passing NULL, we wait indefinitely, so no need to usleep in the Thread code
+			wireless->pollProcess();
+			wireless->pollSetup(); // reinitialize for next test
+			return 0; //no sleep time because pollTest blocks
+		}
+	} wireless_thread;
+#endif
+	
+	void initialize() {
+#ifdef TK_ENABLE_CONFIG
+		if(config==NULL) {
+			string configfile=TK_cstr(TK_ENABLE_CONFIG);
+			config=new Config(configfile.size()==0 ? "tekkotsu.cfg" : configfile);
+		}
+#endif
+		
+#ifdef TK_ENABLE_EROUTER
+		erouter=new EventRouter;
+#endif
+		
+#ifdef TK_ENABLE_WIRELESS
+		wireless = new Wireless();
+#endif
+#ifdef TK_ENABLE_SOUTSERR
+#  ifdef TK_ENABLE_WIRELESS
+		sout=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*12);
+		serr=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*4);
+		wireless->setDaemon(sout);
+		wireless->setDaemon(serr);
+#  else
+		sout=new Socket(0);
+		serr=new Socket(1);
+#  endif
+		serr->setFlushType(SocketNS::FLUSH_BLOCKING);
+		sout->setTextForward();
+		serr->setForward(sout);
+#  ifdef TK_ENABLE_WIRELESS
+#    ifdef TK_ENABLE_CONFIG
+		wireless->listen(sout, if(config!=NULL) ? 10000 : config->main.console_port);
+		wireless->listen(serr, if(config!=NULL) ? 10001 : config->main.stderr_port);
+#    else
+		wireless->listen(sout, 10000 );
+		wireless->listen(serr, 10001 );
+#    endif
+#  endif
+#else //no sout/serr
+#  ifdef TK_ENABLE_WIRELESS //but if wireless is enabled, might as well define them
+		sout=new Socket(-1);
+		serr=new Socket(-1);
+		serr->setFlushType(SocketNS::FLUSH_BLOCKING);
+		sout->setTextForward();
+		serr->setForward(sout);
+#  endif
+#endif //sout and serr
+		
+#ifdef TK_ENABLE_KINEMATICS
+		if(config==NULL) {
+			std::cerr << "ERROR: Kinematics depends on Config -- either define TK_ENABLE_CONFIG,\n"
+			            "  or manually create a Config, either way providing values for:\n"
+			            "    motion_config::kinematics - location of the kinematics spec file\n"
+			            "    motion_config::kinematic_chains - name(s) of chain(s) to load" << std::endl;
+			exit(1);
+		}
+		if(config->motion.kinematics.size()==0 || config->motion.kinematic_chains.size()==0) {
+			std::cerr << "ERROR: The specified configuration does not provide values for:\n"
+			            "    motion_config::kinematics - location of the kinematics spec file\n"
+			            "    motion_config::kinematic_chains - name(s) of chain(s) to load\n"
+			            "  These values are required for Kinematics initialization." << std::endl;
+			exit(1);
+		}
+#ifndef TK_ENABLE_SOUTSERR
+#  warning If using Kinematics, it is wise to enable sout & serr in case errors are enountered.
+#endif
+		kine = new Kinematics();
+#endif
+		
+#ifdef TK_ENABLE_WIRELESS
+		wireless_thread.start();
+#endif
+	}
+
+	
+	void destruct() {
+#ifdef TK_ENABLE_WIRELESS
+		wireless_thread.stop();
+		wireless->wakeup();
+		wireless_thread.join();
+#endif
+		
+#ifdef TK_ENABLE_KINEMATICS
+		delete kine;
+#endif
+		
+
+#if defined(TK_ENABLE_WIRELESS) || defined(TK_ENABLE_SOUTSERR)
+		if(serr!=NULL) {
+#  if defined(TK_ENABLE_WIRELESS) && defined(TK_ENABLE_SOUTSERR)
+			wireless->setDaemon(serr,false);
+			wireless->close(serr);
+#  else
+			delete serr;
+#  endif
+			serr=NULL;
+		}
+		
+		if(sout!=NULL) {
+#  if defined(TK_ENABLE_WIRELESS) && defined(TK_ENABLE_SOUTSERR)
+			wireless->setDaemon(sout,false);
+			wireless->close(sout);
+#  else
+			delete sout;
+#  endif
+			sout=NULL;
+		}
+
+#  ifdef TK_ENABLE_WIRELESS
+		delete wireless;
+#  endif
+#endif
+		
+#ifdef TK_ENABLE_EROUTER
+		delete erouter;
+#endif
+		
+#ifdef TK_ENABLE_CONFIG
+		delete config;
+#endif
+	}
+	
+};
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/08/01 23:18:00 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/CVS/Entries ./local/sim/CVS/Entries
--- ../Tekkotsu_2.3/local/sim/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./local/sim/CVS/Entries	Wed Aug 10 11:03:26 2005
@@ -0,0 +1,21 @@
+/LoadFileThread.cc/1.12/Thu Aug  4 21:32:16 2005//Ttekkotsu-2_4
+/LoadFileThread.h/1.10/Thu Aug  4 21:32:16 2005//Ttekkotsu-2_4
+/LoadImageThread.cc/1.3/Mon Jun 13 18:00:04 2005//Ttekkotsu-2_4
+/LoadImageThread.h/1.2/Wed Jun  1 05:48:07 2005//Ttekkotsu-2_4
+/Main.cc/1.11/Wed Jul  6 22:53:10 2005//Ttekkotsu-2_4
+/Main.h/1.6/Wed Jul  6 22:53:10 2005//Ttekkotsu-2_4
+/Motion.cc/1.3/Wed Jun 29 22:06:41 2005//Ttekkotsu-2_4
+/Motion.h/1.4/Wed Jun 29 22:06:41 2005//Ttekkotsu-2_4
+/Process.cc/1.3/Wed Jun 15 18:54:26 2005//Ttekkotsu-2_4
+/Process.h/1.3/Wed Jun 15 18:54:43 2005//Ttekkotsu-2_4
+/SharedGlobals.cc/1.6/Wed Jul 27 17:37:53 2005//Ttekkotsu-2_4
+/SharedGlobals.h/1.8/Thu Jul 28 18:22:26 2005//Ttekkotsu-2_4
+/SimConfig.cc/1.2/Wed Jun  1 05:48:07 2005//Ttekkotsu-2_4
+/SimConfig.h/1.3/Tue Jul 26 03:07:36 2005//Ttekkotsu-2_4
+/Simulator.cc/1.9/Wed Aug  3 06:37:41 2005//Ttekkotsu-2_4
+/Simulator.h/1.5/Wed Aug  3 06:37:42 2005//Ttekkotsu-2_4
+/SoundPlay.cc/1.3/Wed Jun 29 22:06:41 2005//Ttekkotsu-2_4
+/SoundPlay.h/1.4/Wed Jun 29 22:06:41 2005//Ttekkotsu-2_4
+/sim.cc/1.8/Thu Aug  4 21:30:07 2005//Ttekkotsu-2_4
+/sim.h/1.5/Mon Aug  1 23:18:00 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/local/sim/CVS/Repository ./local/sim/CVS/Repository
--- ../Tekkotsu_2.3/local/sim/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./local/sim/CVS/Repository	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Tekkotsu/local/sim
diff -urdN ../Tekkotsu_2.3/local/sim/CVS/Root ./local/sim/CVS/Root
--- ../Tekkotsu_2.3/local/sim/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./local/sim/CVS/Root	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/local/sim/CVS/Tag ./local/sim/CVS/Tag
--- ../Tekkotsu_2.3/local/sim/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./local/sim/CVS/Tag	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/local/sim/LoadFileThread.cc ./local/sim/LoadFileThread.cc
--- ../Tekkotsu_2.3/local/sim/LoadFileThread.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/LoadFileThread.cc	Thu Aug  4 17:32:16 2005
@@ -0,0 +1,307 @@
+#include "LoadFileThread.h"
+#include "Shared/get_time.h"
+#include <sys/stat.h>
+#include <regex.h>
+#include <dirent.h>
+
+LoadFileThread::~LoadFileThread() {
+	Thread::Lock l(lock);
+	src.removePrimitiveListener(this);
+	verbose.removePrimitiveListener(this);
+	while(sent.size()>0) {
+		freeRegion(sent.front());
+		sent.pop_front();
+	}
+	while(loaded.size()>0) {
+		freeRegion(loaded.front());
+		loaded.pop_front();
+	}
+}
+
+void LoadFileThread::loadFileList(bool clearCurrent/*=true*/) {
+	Thread::Lock l(lock);
+	struct stat sb;
+	if(stat(src.c_str(),&sb)) {
+		std::cerr << "Could not open source " << src << std::endl;
+		return;
+	}
+	if(clearCurrent)
+		files.clear();
+	isIndexed=false;
+	if(sb.st_mode&S_IFDIR) {
+		loadFileListFromDirectory();
+	} else {
+		//Test to see if the file matches the filter
+		regex_t re;
+		if(int err=regcomp(&re,filenameFilter.c_str(),REG_EXTENDED | REG_NOSUB)) {
+			char msg[128];
+			regerror(err,&re,msg,128);
+			std::cerr << "Bad filter '" << filenameFilter << "': " << msg << std::endl;
+			regfree(&re);
+			return;
+		}
+		int match=regexec(&re,src.c_str(),0,NULL,0);
+		regfree(&re);
+		if(match==0) {
+			loadSingleFile(src.c_str());
+		} else if(match==REG_NOMATCH) {
+			//if it doesn't match the image RE, assume it's an index file
+			//loadFileListFromIndex();
+		} else {
+			char msg[128];
+			regerror(match,&re,msg,128);
+			std::cerr << "Regex error on '" << src << "': " << msg << std::endl;
+		}
+	}
+	setFrame(0);
+}
+
+void LoadFileThread::setFrame(unsigned int f) {
+	Thread::Lock l(lock);
+	loopRemainder=0;
+	startTimeOffset=(int)(get_time()-f*1000/framerate);
+	resetTimeOffset(startTimeOffset);
+	curfile=files.begin();
+	advance(curfile,f);
+}
+
+void LoadFileThread::loadSingleFile(const std::string& file) {
+	Thread::Lock l(lock);
+	files[(unsigned int)calcLoopTime()]=file;
+}
+
+void LoadFileThread::loadFileListFromDirectory() {
+	Thread::Lock l(lock);
+	regex_t re;
+	if(int err=regcomp(&re,filenameFilter.c_str(),REG_EXTENDED | REG_NOSUB)) {
+		char msg[128];
+		regerror(err,&re,msg,128);
+		std::cerr << "Bad filter '" << filenameFilter << "': " << msg << std::endl;
+		regfree(&re);
+		return;
+	}
+	DIR * d=opendir(src.c_str());
+	if(d==NULL) {
+		std::cerr << "Could not open directory " << src << std::endl;
+		regfree(&re);
+		return;
+	}
+	float tinc=1000.f/framerate;
+	float time=calcLoopTime();
+	struct dirent* res;
+	
+#ifdef HAVE_READDIR_R
+	struct dirent cur;
+	if(readdir_r(d,&cur,&res)) {
+		std::cerr << "Error reading files from " << src << std::endl;
+		closedir(d);
+		regfree(&re);
+		return;
+	}
+#else
+	res=readdir(d);
+#endif
+	while(res!=NULL) {
+		int match=regexec(&re,res->d_name,0,NULL,0);
+		if(match==0) {
+			files[static_cast<unsigned int>(time)]=(src+"/")+res->d_name;
+			//std::cout << "Enqueuing " << res->d_name << std::endl;
+			time+=tinc;
+		} else if(match!=REG_NOMATCH) {
+			char msg[128];
+			regerror(match,&re,msg,128);
+			std::cerr << "Regex error on '" << res->d_name << "': " << msg << std::endl;
+		} // else std::cout << "Skipping " << res->d_name << std::endl;
+#ifdef HAVE_READDIR_R
+		if(readdir_r(d,&cur,&res)) {
+			std::cerr << "Error reading files from " << src << std::endl;
+			closedir(d);
+			regfree(&re);
+			return;
+		}
+#else
+		res=readdir(d);
+#endif
+	}
+	closedir(d);
+	regfree(&re);
+}
+
+/*
+void LoadFileThread::loadFileListFromIndex() {
+	isIndexed=true;
+	regex_t re;
+	if(int err=regcomp(&re,filenameFilter.c_str(),REG_EXTENDED | REG_NOSUB)) {
+		char msg[128];
+		regerror(err,&re,msg,128);
+		std::cerr << "Bad filter '" << filenameFilter << "': " << msg << std::endl;
+		regfree(&re);
+		return;
+	}
+	// todo read index file
+	regfree(&re);
+}
+*/
+
+bool LoadFileThread::incrementCurfile(float loopTime, int& curTime) {
+	if(++curfile == files.end()) {
+		if(!loop) {
+			if(verbose)
+				std::cout << "Out of data from '" << src << "' -- set 'loop' to true, or use 'restart' command to manually loop" << std::endl;
+			return false;
+		} else {
+			if(verbose)
+				std::cout << "Looping data from '" << src << "'" << std::endl;
+			unsigned int loopTimeI = (unsigned int)(loopTime);
+			loopRemainder+=loopTime-loopTimeI;
+			unsigned int loopRemainderI=(unsigned int)(loopRemainder);
+			loopRemainder-=loopRemainderI;
+			timeOffset=(startTimeOffset+=loopTimeI+loopRemainderI);
+			curTime-=loopTimeI;
+			curfile=files.begin();
+		}
+	}
+	return true;
+}
+
+void LoadFileThread::getNextData(RCRegion*& data, unsigned int& t) {
+	if(files.size()==0 || curfile==files.end())
+		return;
+	if(startTimeOffset!=timeOffset)
+		resetTimeOffset(startTimeOffset);
+
+	//skip old data -- current time is already past these frames, no point in loading them
+	unsigned int realt=get_time();
+	int curt=realt-timeOffset;
+	float loopTime=calcLoopTime();
+	if(curt>(int)(loopTime)) {
+		if(!loop) {
+			if(verbose)
+				std::cout << "Way out of data from '" << src << "' -- set 'loop' to true, or use 'restart' command to manually loop" << std::endl;
+			curfile=files.end();
+			return;
+		}
+		if(verbose)
+			std::cout << "Mass looping data from '" << src << "'" << std::endl;
+		unsigned int loops=(unsigned int)(curt/loopTime);
+		float massLoopTime=loops*loopTime;
+		unsigned int massLoopTimeI=(unsigned int)(massLoopTime);
+		loopRemainder+=massLoopTime-massLoopTimeI;
+		unsigned int loopRemainderI=(unsigned int)(loopRemainder);
+		loopRemainder-=loopRemainderI;
+		startTimeOffset+=massLoopTimeI+loopRemainderI;
+		resetTimeOffset(startTimeOffset);
+		curt=realt-timeOffset;
+		curfile=files.begin();
+	}
+	while(static_cast<int>(curfile->first)<curt)
+		if(!incrementCurfile(loopTime,curt))
+			return;
+
+	if(verbose)
+		std::cout << "Loading frame from " << curfile->second << " dt="<<curfile->first << " scheduled:" << (curfile->first+timeOffset) << std::endl;
+	msgbuf_t::iterator it;
+	for(it=sent.begin();it!=sent.end(); ++it)
+		if((*it)->NumberOfReference()==1)
+			break;
+	if(it!=sent.end()) {
+		if(!loadFile(curfile->second, *it)) {
+			std::cerr << "Bad load on " << curfile->second << std::endl;
+			++curfile;
+			return;
+		}
+		data=*it;
+		sent.erase(it);
+	} else {
+		if(!loadFile(curfile->second, data)) {
+			std::cerr << "Bad load on " << curfile->second << std::endl;
+			++curfile;
+			return;
+		}
+	}
+	t=curfile->first+timeOffset;
+	incrementCurfile(loopTime,curt);
+}
+
+unsigned int LoadFileThread::runloop() {
+	Thread::Lock l(lock);
+	if(unsigned int read=msgr.pollStatus())
+		fireMessagesRead(read);
+	unsigned int curt=get_time();
+	if(timestamps.size()>0 && curt>=timestamps.front()) {
+		if(verbose)
+			std::cout << "Sending frame " << timestamps.front() << " at " << curt << std::endl;
+		msgr.sendMessage(loaded.front());
+		sent.push_back(loaded.front());
+		loaded.pop_front();
+		timestamps.pop_front();
+	}
+	if(loaded.size()<NUM_PRELOAD) {
+		RCRegion* rcr=NULL;
+		unsigned int t=-1U;
+		getNextData(rcr,t);
+		if(t==-1U) {
+			//out of data, skip a frame and then check again in case we get reset
+			return (1000000/(unsigned int)framerate);
+		}
+		if(rcr==NULL) {
+			std::cerr << "Could not allocate new shared memory region or bad initial load" << std::endl;
+			return (1000000/(unsigned int)framerate);
+		}
+		if(timestamps.size()==0 || t>timestamps.back()) {
+			loaded.push_back(rcr);
+			timestamps.push_back(t);
+		} else {
+			std::cerr << "ERROR: LoadFileThread received old data from getNextData" << std::endl;
+			sent.push_front(rcr);
+		}
+	}
+	return 1000;
+}
+
+void LoadFileThread::fireMessagesRead(unsigned int howmany) {
+	std::list<MessageQueueBase::StatusListener*>::iterator it=statusListeners.begin();
+	while(it!=statusListeners.end()) {
+		std::list<MessageQueueBase::StatusListener*>::iterator cur=it++; //increment early in case the listener changes subscription
+		(*cur)->messagesRead(msgr,howmany);
+	}
+}
+
+void LoadFileThread::resetTimeOffset(int t) {
+	while(loaded.size()>0) {
+		sent.push_front(loaded.front());
+		loaded.pop_front();
+	}
+	timestamps.clear();
+	if(timeOffset<t) {
+		//need to rewind curfile
+		curfile=files.begin(); //getNextData will fast forward to current time
+	}
+	timeOffset=t;
+}
+
+float LoadFileThread::calcLoopTime() {
+	if(files.size()==0)
+		return 0;
+	float tinc=1000.f/framerate;
+	if(isIndexed) {
+		files_t::iterator lastfile=files.end();
+		--lastfile;
+		unsigned int last=lastfile->first;
+		return last+tinc;
+	} else {
+		return files.size()*tinc;
+	}
+}
+
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.12 $
+ * $State: Exp $
+ * $Date: 2005/08/04 21:32:16 $
+ */
diff -urdN ../Tekkotsu_2.3/local/sim/LoadFileThread.h ./local/sim/LoadFileThread.h
--- ../Tekkotsu_2.3/local/sim/LoadFileThread.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/LoadFileThread.h	Thu Aug  4 17:32:16 2005
@@ -0,0 +1,167 @@
+//-*-c++-*-
+#ifndef INCLUDED_LoadFileThread_h_
+#define INCLUDED_LoadFileThread_h_
+
+#include "IPC/Thread.h"
+#include "Shared/plist.h"
+#include "IPC/MessageQueue.h"
+#include <list>
+
+//! Provides resources for loading time-based data from disk
+/*! Runs in a separate thread, preloads data into shared memory buffers, and
+ *  then sends the buffer when the time is right.  Thread doesn't start until
+ *  you set the source or call loadFileList(). */
+class LoadFileThread : public Thread, public plist::Dictionary, public plist::PrimitiveListener {
+public:
+
+	//! constructor
+	/*! @param source the path to either a directory to load files from, or a single specific data file
+	 *  @param filter a regular expression (POSIX.2 extended format) to select which files to load from @a source, if @a is a directory
+	 *  @param fps frames per second, see #frameRate
+	 *  @param messages the MessageQueue through which to send the data
+	 *
+	 *  The file list is not actually loaded until you call loadFileList -- this
+	 *  gives you a chance to reset the default values you supplied in the
+	 *  constructor with actual values from, for example, a preference file, and
+	 *  then load the file list after the settings are correct.
+	 */
+	LoadFileThread(std::string source, std::string filter, float fps, MessageQueueBase& messages)
+	: Thread(), plist::Dictionary(),
+		src(source),
+		filenameFilter(filter),
+		framerate(fps),
+		startTimeOffset(0),
+		verbose(false),
+		loop(true),
+		sent(), loaded(), timestamps(), files(), curfile(files.begin()), msgr(messages),
+		timeOffset(0), lock(), loopRemainder(0), isIndexed(false), statusListeners()
+	{
+		addEntry("Source",src,"The directory from which data samples should be loaded, or a single specific file.\nIn the future, this could also be network addresses for teleoperation and remote processing.");
+		addEntry("FileFilter",filenameFilter,"If Source is a directory, only files matching the filter will be loaded from it.");
+		addEntry("Framerate",framerate,"The rate at which images should be loaded");
+		addEntry("StartTime",startTimeOffset,"The time at which the file list should start being processed");
+		addEntry("Verbose",verbose,"If true, input status information will be dumped on the console");
+		addEntry("Loop",loop,"If true, restart file list at the beginning when the end is reached; otherwise just stop loading data");
+		src.addPrimitiveListener(this);
+		verbose.addPrimitiveListener(this);
+	}
+	//! destructor
+	~LoadFileThread();
+	
+	//! source the path to either a directory to load files from, or a single specific data file
+	plist::Primitive<std::string> src;
+
+	//! a regular expression (POSIX.2 extended format) to select which files to load from @a source, if @a is a directory
+	plist::Primitive<std::string> filenameFilter;
+
+	//! frames per second to send -- only referenced when setting up #files during loadFileList -- later modifications won't resent the already loaded file list
+	plist::Primitive<float> framerate;
+
+	//! the requested time of start of run through #files -- if this is modified, it will be noticed during runloop() and #curfile will be updated appropriately
+	plist::Primitive<int> startTimeOffset;
+
+	//! controls whether to give feedback messages on the console regarding progress
+	plist::Primitive<bool> verbose; 
+
+	//! controls whether to restart #curfile at the beginning of #files when it reaches the end
+	plist::Primitive<bool> loop; 
+
+
+	//! call this to (re)load the list of available file names from disk
+	/*! If @a clearCurrent is set, then the current file list will be cleared;
+	 *  otherwise, the loaded files will be appended to the current queue */
+	virtual void loadFileList(bool clearCurrent=true);
+	//! sets the next frame to be sent (e.g. pass 0 to reset to the first frame)
+	virtual void setFrame(unsigned int f);
+	
+	//! returns the timestamp of the next message in the queue ready to be sent
+	virtual unsigned int nextTimestamp() { return timestamps.size()>0 ? timestamps.front() : -1U; }
+	
+	//! Request updates to StatusListener callbacks
+	virtual void addStatusListener(MessageQueueBase::StatusListener* l) {
+		if(l==NULL)
+			return;
+		statusListeners.push_back(l);
+	}
+	//! Unsubscribes a StatusListener from future updates
+	virtual void removeStatusListener(MessageQueueBase::StatusListener* l) {
+		std::list<MessageQueueBase::StatusListener*>::iterator it=find(statusListeners.begin(),statusListeners.end(),l);
+		if(it!=statusListeners.end())
+			statusListeners.erase(it);
+	}
+	
+	virtual void plistValueChanged(const plist::PrimitiveBase& pl) {
+		if(&pl==&src)
+			loadFileList();
+		else if(&pl==&verbose)
+			msgr.setReportDroppings(verbose);
+	}
+	
+protected:
+	//! removes our reference to a region created by loadFile()
+	virtual void freeRegion(RCRegion* rcr) { rcr->RemoveReference(); }
+	//! loads the next data element from file and provides its timestamp, skipping any files which have already expired
+	/*! @param[in] data a pre-allocated region to use, or NULL to request creation of a new one
+	 *  @param[out] data the address of the region with loaded data
+	 *  @param[out] t the timestamp at which @a data should be consumed */
+	virtual void getNextData(RCRegion*& data, unsigned int& t);
+	//! does the actual work of loading and processing data from disk, should be provided by subclass
+	/*! @param[in] file full path of file to load
+	 *  @param[in] data a pre-allocated region to use, or NULL to request creation of a new one
+	 *  @param[out] data the address of the region which has been filled in */
+	virtual bool loadFile(const std::string& file, RCRegion*& data)=0;
+	//! increments #curfile, looping if necessary; returns false if end of list reached and not #loop
+	/*! @param[in] loopTime is the time of a single loop (the time of the last frame, plus inter-frame time)
+	 *  @param[in] curTime is the current time, relative to beginning of current loop (#timeOffset)
+	 *  @param[out] modified curTime if loop has occurred, subtracting loopTime */
+	virtual bool incrementCurfile(float loopTime, int& curTime);
+	
+	//! load a list of files from a directory specified by #src
+	virtual void loadFileListFromDirectory();
+	//! load a single file
+	virtual void loadSingleFile(const std::string& file);
+	// ! NOT DONE -- load a list of files from an index file specified by #src
+	//virtual void loadFileListFromIndex();
+
+	//! monitor #msgr, send new messages when their timestamp indicates they are due, then load upcoming messages
+	virtual unsigned int runloop();
+
+	//! Notifies statusListeners that a message has been read by all MessageQueue receivers
+	virtual void fireMessagesRead(unsigned int howmany);
+
+	//! assign a new value @a t to #timeOffset -- clears loaded data queue (to be reloaded on next call to getNextData())
+	virtual void resetTimeOffset(int t);
+	
+	//! computes the time of an entire loop through the files (including inter-frame time at the end of the loop)
+	virtual float calcLoopTime();
+
+	static const unsigned int NUM_PRELOAD=2; //!< number of data elements to preload
+	typedef std::list<RCRegion* > msgbuf_t; //!< type of collection of shared data regions
+	typedef std::map<unsigned int,std::string> files_t; //!< type of #files, the list of files to load
+
+	msgbuf_t sent; //!< for efficiency, reuse old buffers -- oldest at front, most recently used at back
+	msgbuf_t loaded; //!< for efficiency, reuse old buffers -- oldest at front, most recently used at back
+	std::list<unsigned int> timestamps; //!< the timestamps to send data queued in #loaded
+	files_t files; //!< the list of files to load ('second'), and their timestamps ('first')
+	files_t::const_iterator curfile; //!< an iterator referencing #files -- indicates next file to load
+	MessageQueueBase& msgr; //!< the MessageQueue through which to send the data
+	int timeOffset; //!< the starting time of the run through #files, see #startTimeOffset
+	Thread::Lock lock; //!< allows mutual exclusion over this object's member variables
+	float loopRemainder; //!< a bit ugly -- this is the fractional leftover accumulated from looping so we won't "drift" over time
+	bool isIndexed; //!< if we're using an index file, we have to handle the loopRemainder differently
+
+	std::list<MessageQueueBase::StatusListener*> statusListeners; //!< MessageQueueBase::StatusListeners currently subscribed from addStatusListener()
+};
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.10 $
+ * $State: Exp $
+ * $Date: 2005/08/04 21:32:16 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/LoadImageThread.cc ./local/sim/LoadImageThread.cc
--- ../Tekkotsu_2.3/local/sim/LoadImageThread.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/LoadImageThread.cc	Mon Jun 13 14:00:04 2005
@@ -0,0 +1,85 @@
+#include "LoadImageThread.h"
+
+extern "C" {
+#include <jpeglib.h>
+}
+#include "sim.h"
+#include "SimConfig.h"
+
+using namespace std;
+
+LoadImageThread::LoadImageThread(std::string source, std::string filter, float fps, MessageQueueBase& messages)
+: LoadFileThread(source,filter,fps,messages), cinfo(new jpeg_decompress_struct), jerr(new jpeg_error_mgr), frameIndex(0)
+{
+	cinfo->err = jpeg_std_error(jerr);
+	jpeg_create_decompress(cinfo);
+}
+
+LoadImageThread::~LoadImageThread() {
+	jpeg_destroy_decompress(cinfo);
+	delete cinfo;
+	delete jerr;
+}
+
+bool LoadImageThread::loadFile(const std::string& file, RCRegion*& data) {
+	FILE * infile= fopen(file.c_str(), "rb");
+	if (infile==NULL) {
+		cerr << "Could not open '" << file << "'" << endl;
+		return false;
+	}
+	jpeg_stdio_src(cinfo, infile);
+	jpeg_read_header(cinfo, true);
+	cinfo->out_color_space=JCS_YCbCr;
+	jpeg_calc_output_dimensions(cinfo);
+	if(cinfo->output_width==0 || cinfo->output_height==0) {
+		cerr << "Empty image '" << file << "'" << endl;
+		return false;
+	}
+	const unsigned int HEADER_SIZE=sizeof(unsigned int)*5;
+	unsigned int reqBufSize=sizeof(JSAMPLE)*cinfo->output_width*cinfo->output_height*cinfo->output_components+HEADER_SIZE;
+	if(data==NULL)
+		data=new RCRegion(reqBufSize);
+	else if(data->Size()<reqBufSize) {
+		//too small -- free it, we'll make another one the right size
+		freeRegion(data);
+		data=new RCRegion(reqBufSize);
+	}
+	reinterpret_cast<unsigned int*>(data->Base())[0]=cinfo->output_width;
+	reinterpret_cast<unsigned int*>(data->Base())[1]=cinfo->output_height;
+	reinterpret_cast<unsigned int*>(data->Base())[2]=cinfo->output_components;
+	reinterpret_cast<unsigned int*>(data->Base())[3]=frameIndex++;
+	reinterpret_cast<int*>(data->Base())[4]=*dynamic_cast<plist::Primitive<int>*>(sim::config.findEntry("Vision.Layer"));
+	unsigned int row_stride = cinfo->output_width * cinfo->output_components;
+	//JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
+	jpeg_start_decompress(cinfo);
+	unsigned int remain=cinfo->output_height;
+	JSAMPROW rows[remain];
+	rows[0]=reinterpret_cast<JSAMPROW>(data->Base()+HEADER_SIZE);
+	for(unsigned int i=1; i<remain; i++)
+		rows[i]=rows[i-1]+row_stride;
+	JSAMPROW* curpos=rows;
+	while (remain>0) {
+		unsigned int used=jpeg_read_scanlines(cinfo, curpos, remain);
+		curpos+=used;
+		remain-=used;
+	}
+	jpeg_finish_decompress(cinfo);
+	fclose(infile);
+	if(jerr->num_warnings>0) {
+		cerr << "Warning: Decompression of '" << file << "' had warnings" << endl;
+		jerr->num_warnings=0;
+	}
+	return true;
+}
+
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/13 18:00:04 $
+ */
diff -urdN ../Tekkotsu_2.3/local/sim/LoadImageThread.h ./local/sim/LoadImageThread.h
--- ../Tekkotsu_2.3/local/sim/LoadImageThread.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/LoadImageThread.h	Wed Jun  1 01:48:07 2005
@@ -0,0 +1,36 @@
+//-*-c++-*-
+#ifndef INCLUDED_LoadImageThread_h_
+#define INCLUDED_LoadImageThread_h_
+
+#include "LoadFileThread.h"
+
+//! description of LoadImageThread
+class LoadImageThread : public LoadFileThread {
+public:
+	LoadImageThread(std::string source, std::string filter, float fps, MessageQueueBase& messages);
+	~LoadImageThread();
+
+	virtual bool loadFile(const std::string& file, RCRegion*& data);
+	
+protected:
+	struct jpeg_decompress_struct* cinfo; //!< used to interface with libjpeg - holds compression parameters and state
+	struct jpeg_error_mgr* jerr;          //!< used to interface with libjpeg - gives us access to error information
+	unsigned int frameIndex; //!< serial number, incremented for each frame loaded
+	
+private:
+	LoadImageThread(const LoadImageThread&); //!< don't call
+	LoadImageThread& operator=(const LoadImageThread&); //!< don't call
+};
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:48:07 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/Main.cc ./local/sim/Main.cc
--- ../Tekkotsu_2.3/local/sim/Main.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Main.cc	Wed Jul  6 18:53:10 2005
@@ -0,0 +1,209 @@
+#include "Main.h"
+#include "SoundPlay.h"
+#include "Motion.h"
+#include "Simulator.h"
+#include "IPC/RegionRegistry.h"
+#include "IPC/MessageReceiver.h"
+#include "Motion/Kinematics.h"
+#include "Wireless/Wireless.h"
+#include "Shared/ProjectInterface.h"
+#include "Behaviors/BehaviorBase.h"
+#include "Vision/BufferedImageGenerator.h"
+#include "Events/DataEvent.h"
+#include "Events/EventRouter.h"
+#include "Shared/Config.h"
+
+#include "Events/EventBase.h"
+#include "Events/LocomotionEvent.h"
+#include "Events/TextMsgEvent.h"
+#include "Events/VisionObjectEvent.h"
+
+Main::Main()
+	: Process(getID(),getClassName()),
+	sounds(ipc_setup->registerRegion(SoundPlay::getSoundPlayID(),sizeof(sim::SoundPlayQueue_t))),
+	motions(ipc_setup->registerRegion(Motion::getMotionCommandID(),sizeof(sim::MotionCommandQueue_t))),
+	events(ipc_setup->registerRegion(getEventsID(),sizeof(sim::EventQueue_t))),
+	cameraFrames(ipc_setup->registerRegion(Simulator::getCameraQueueID(),sizeof(sim::CameraQueue_t))),
+	sensorFrames(ipc_setup->registerRegion(Simulator::getSensorQueueID(),sizeof(sim::SensorQueue_t))),
+	motionmanager(ipc_setup->registerRegion(Motion::getMotionManagerID(),sizeof(MotionManager))),
+	soundmanager(ipc_setup->registerRegion(SoundPlay::getSoundManagerID(),sizeof(SoundManager))),
+	worldstate(ipc_setup->registerRegion(getWorldStateID(),sizeof(WorldState))),
+	visrecv(NULL), sensrecv(NULL), evtrecv(NULL), visionRead(true), sensorRead(true),
+	wireless_thread(), curimg(NULL)
+{
+	new (&(*events)) sim::EventQueue_t;
+	new (&(*worldstate)) WorldState;
+	state=&(*worldstate);
+	motman=&(*motionmanager);
+	sndman=&(*soundmanager);
+
+	//Setup wireless
+	wireless = new Wireless();
+	sout=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*12);
+	serr=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*4);
+	wireless->setDaemon(sout);
+	wireless->setDaemon(serr);
+	serr->setFlushType(SocketNS::FLUSH_BLOCKING);
+	sout->setTextForward();
+	serr->setForward(sout);
+
+	//Setup Kinematics
+	kine=new Kinematics();
+	
+	//need to register any events which we might be sending or receiving
+	EventTranslator::registerPrototype<EventBase>();
+	EventTranslator::registerPrototype<LocomotionEvent>();
+	EventTranslator::registerPrototype<TextMsgEvent>();
+	EventTranslator::registerPrototype<VisionObjectEvent>();
+
+	//EventRouter and Config are set up for all processes by main() before fork
+}
+
+Main::~Main() {
+}
+
+
+void Main::DoStart() {
+	Process::DoStart();
+	//These are constructed by other processes, so need to wait
+	//until the construction runlevel is complete
+	sndman->InitAccess(*sounds);
+	motman->InitAccess(*motions);
+
+	wireless->listen(sout, config->main.console_port);
+	wireless->listen(serr, config->main.stderr_port);
+	wireless_thread.start();
+	evtrecv=new MessageReceiver(*events,gotEvent,false);
+	visrecv=new MessageReceiver(*cameraFrames,gotCamera,false);
+}
+
+void Main::run() {
+	ProjectInterface::startupBehavior().DoStart();
+
+	evtrecv->start();
+	visrecv->start();
+	
+	Process::run();
+
+	visrecv->finish();
+	evtrecv->finish();
+
+	ProjectInterface::startupBehavior().DoStop();
+}
+
+void Main::DoStop() {
+	events->close();
+
+	delete visrecv;
+	visrecv=NULL;
+	delete evtrecv;
+	evtrecv=NULL;
+
+	wireless_thread.stop();
+	wireless->wakeup();
+	wireless_thread.join();
+	wireless->setDaemon(sout,false);
+	wireless->close(sout);
+	sout=NULL;
+	wireless->setDaemon(serr,false);
+	wireless->close(serr);
+	serr=NULL;
+	
+	motman->RemoveAccess();
+	
+	if(curimg!=NULL)
+		curimg->RemoveReference();
+
+	Process::DoStop();
+}
+
+bool Main::canManuallyAdvance() {
+	Main * main=dynamic_cast<Main*>(Process::getCurrent());
+	if(main==NULL) {
+		cerr << "WARNING: attempt to call Main::advanceVision() from outside Main process!" << endl;
+		return false;
+	}
+	if(globals->timeScale >= 0) //ignore call if we're in realtime mode
+		return false;
+	if(globals->advanceOnAccess) //ignore call if we're advancing on access
+		return false;
+	return true;
+}
+
+void Main::advanceVision() {
+	Main * main=dynamic_cast<Main*>(Process::getCurrent());
+	if(main==NULL) {
+		cerr << "WARNING: attempt to call Main::advanceVision() from outside Main process!" << endl;
+		return;
+	}
+	if(globals->timeScale >= 0) //ignore call if we're in realtime mode
+		return;
+	if(globals->advanceOnAccess) //ignore call if we're advancing on access
+		return;
+	if(main->visionRead) //already marked this frame read
+		return;
+	main->visionRead=true;
+	main->visrecv->markRead();
+}
+
+void Main::advanceSensor() {
+	Main * main=dynamic_cast<Main*>(Process::getCurrent());
+	if(main==NULL) {
+		cerr << "WARNING: attempt to call Main::advanceSensor() from outside Main process!" << endl;
+		return;
+	}
+	if(globals->timeScale >= 0) //ignore call if we're in realtime mode
+		return;
+	if(globals->advanceOnAccess) //ignore call if we're advancing on access
+		return;
+	if(main->sensorRead) //already marked this frame read
+		return;
+	main->sensorRead=true;
+	main->sensrecv->markRead();
+}
+
+
+bool Main::gotCamera(RCRegion* msg) {
+	if(msg==NULL)
+		return true;
+	msg->AddReference();
+	Main * main=dynamic_cast<Main*>(Process::getCurrent());
+	if(main->curimg!=NULL)
+		main->curimg->RemoveReference();
+	main->curimg=msg;
+	BufferedImageGenerator::ImageSource img;
+	memcpy(&img,msg->Base(),sizeof(unsigned int)*4);
+	int l=reinterpret_cast<int*>(msg->Base())[4];
+	img.layer = (l<0)?ProjectInterface::defRawCameraGenerator->getNumLayers()+l:l;
+	bool isRealtime=(globals->timeScale >= 0);
+	main->visionRead=globals->advanceOnAccess; //not actually read until the BufferedImageGenerator is accessed, but it's read as far as advanceVision() is concerned
+	if(!isRealtime && main->visionRead)
+		img.receiver = main->visrecv;
+	img.img = reinterpret_cast<unsigned char*>(msg->Base()+sizeof(unsigned int)*5);
+	erouter->postEvent(new DataEvent<BufferedImageGenerator::ImageSource>(img,EventBase::visOFbkEGID,0,EventBase::activateETID));
+	erouter->postEvent(new DataEvent<BufferedImageGenerator::ImageSource>(img,EventBase::visOFbkEGID,0,EventBase::statusETID));
+	erouter->postEvent(new DataEvent<BufferedImageGenerator::ImageSource>(img,EventBase::visOFbkEGID,0,EventBase::deactivateETID));
+	return isRealtime;
+}
+
+bool Main::gotEvent(RCRegion* msg) {
+	EventBase* evt=EventTranslator::decodeEvent(msg->Base(),msg->Size());
+	if(evt==NULL) {
+		cerr << "ERROR: Main::gotEvent() failed to decode message" << endl;
+		return true;
+	}
+	erouter->postEvent(evt);
+	return true;
+}
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.11 $
+ * $State: Exp $
+ * $Date: 2005/07/06 22:53:10 $
+ */
+
diff -urdN ../Tekkotsu_2.3/local/sim/Main.h ./local/sim/Main.h
--- ../Tekkotsu_2.3/local/sim/Main.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Main.h	Wed Jul  6 18:53:10 2005
@@ -0,0 +1,76 @@
+//-*-c++-*-
+#ifndef INCLUDED_Main_h_
+#define INCLUDED_Main_h_
+
+#include "Process.h"
+#include "sim.h"
+#include "IPC/SharedObject.h"
+#include "SharedGlobals.h"
+#include "Motion/MotionManager.h"
+#include "Sound/SoundManager.h"
+#include "Shared/WorldState.h"
+class MessageReceiver;
+
+class Main : public Process {
+public:
+	//! constructor
+	Main();
+	//! destructor
+	~Main();
+
+	virtual void DoStart();
+	virtual void DoStop();
+	virtual void run();
+
+	//! Will return true if calls to advanceVision() and advanceSensor() will be heeded
+	static bool canManuallyAdvance();
+
+	//! Use this to request the next vision frame be sent
+	static void advanceVision();
+
+	//! Use this to request the next sensor frame be sent
+	static void advanceSensor();
+	
+	static const char* getClassName() { return "Main"; }
+	static ProcessID::ProcessID_t getID() { return ProcessID::MainProcess; }
+	
+	static const char * getEventsID() { return "MainEvents"; }
+	static const char * getWorldStateID() { return "WorldState"; }
+	
+protected:
+	SharedObject<sim::SoundPlayQueue_t> sounds;
+	SharedObject<sim::MotionCommandQueue_t> motions;
+	SharedObject<sim::EventQueue_t> events;
+	SharedObject<sim::CameraQueue_t> cameraFrames;
+	SharedObject<sim::SensorQueue_t> sensorFrames;
+	SharedObject<MotionManager> motionmanager;
+	SharedObject<SoundManager> soundmanager;
+	SharedObject<WorldState> worldstate;
+	MessageReceiver * visrecv;
+	MessageReceiver * sensrecv;
+	MessageReceiver * evtrecv;
+	bool visionRead;
+	bool sensorRead;
+	WirelessThread wireless_thread;
+
+	static bool gotCamera(RCRegion* msg);
+	static bool gotEvent(RCRegion* msg);
+	RCRegion * curimg;
+	
+private:
+	Main(const Main&); //!< don't call (copy constructor)
+	Main& operator=(const Main&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines Main, which DESCRIPTION
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
+ * $State: Exp $
+ * $Date: 2005/07/06 22:53:10 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/Motion.cc ./local/sim/Motion.cc
--- ../Tekkotsu_2.3/local/sim/Motion.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Motion.cc	Wed Jun 29 18:06:41 2005
@@ -0,0 +1,106 @@
+#include "Motion.h"
+#include "Main.h"
+#include "SoundPlay.h"
+#include "IPC/RegionRegistry.h"
+#include "IPC/MessageReceiver.h"
+#include "Motion/Kinematics.h"
+#include "Wireless/Wireless.h"
+#include "Events/EventRouter.h"
+
+#include "Events/EventBase.h"
+#include "Events/LocomotionEvent.h"
+#include "Events/TextMsgEvent.h"
+#include "Events/VisionObjectEvent.h"
+
+Motion::Motion()
+	: Process(getID(),getClassName()),
+	sounds(ipc_setup->registerRegion(SoundPlay::getSoundPlayID(),sizeof(sim::SoundPlayQueue_t))),
+	motions(ipc_setup->registerRegion(getMotionCommandID(),sizeof(sim::MotionCommandQueue_t))),
+	events(ipc_setup->registerRegion(Main::getEventsID(),sizeof(sim::EventQueue_t))),
+	motionmanager(ipc_setup->registerRegion(getMotionManagerID(),sizeof(MotionManager))),
+	soundmanager(ipc_setup->registerRegion(SoundPlay::getSoundManagerID(),sizeof(SoundManager))),
+	worldstate(ipc_setup->registerRegion(Main::getWorldStateID(),sizeof(WorldState))),
+	etrans(NULL), mcrecv(NULL), wireless_thread()
+{
+	new (&(*motions)) sim::MotionCommandQueue_t;
+	new (&(*motionmanager)) MotionManager();
+	motman=&(*motionmanager);
+	motman->InitAccess(*motions);
+	sndman=&(*soundmanager);
+	state=&(*worldstate);
+	
+	//Setup wireless
+	wireless = new Wireless();
+	sout=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*12);
+	serr=wireless->socket(SocketNS::SOCK_STREAM,Wireless::WIRELESS_DEF_RECV_SIZE,Wireless::WIRELESS_DEF_SEND_SIZE*4);
+	wireless->setDaemon(sout);
+	wireless->setDaemon(serr);
+	serr->setFlushType(SocketNS::FLUSH_BLOCKING);
+	sout->setTextForward();
+	serr->setForward(sout);
+
+	//Setup Kinematics
+	kine=new Kinematics();
+	
+	//need to register any events which we might be sending or receiving
+	EventTranslator::registerPrototype<EventBase>();
+	EventTranslator::registerPrototype<LocomotionEvent>();
+	EventTranslator::registerPrototype<TextMsgEvent>();
+	EventTranslator::registerPrototype<VisionObjectEvent>();
+
+	//EventRouter and Config are set up for all processes by main() before fork
+}
+
+Motion::~Motion() {
+	delete etrans;
+	etrans=NULL;
+	MotionManager::setTranslator(NULL);
+}
+
+void Motion::DoStart() {
+	Process::DoStart();
+	//These are constructed by other processes, so need to wait
+	//until the construction runlevel is complete before we access them
+	sndman->InitAccess(*sounds);
+	etrans=new IPCEventTranslator(*events);
+	MotionManager::setTranslator(etrans);
+	
+	// Set up Event Translator to trap and send events to main process
+	//send everything over except erouter events
+	for(unsigned int i=0; i<EventBase::numEGIDs; i++)
+		if(i!=EventBase::erouterEGID)
+			erouter->addTrapper(etrans,static_cast<EventBase::EventGeneratorID_t>(i));
+	
+	wireless_thread.start();
+	mcrecv=new MessageReceiver(*motions,gotMC);
+}
+
+
+void Motion::run() {
+	Process::run();
+}
+
+void Motion::DoStop() {
+	wireless_thread.stop();
+	wireless->wakeup();
+	wireless_thread.join();
+
+	mcrecv->finish();
+	delete mcrecv;
+	mcrecv=NULL;
+	erouter->removeTrapper(etrans);
+	motman->RemoveAccess();
+	Process::DoStop();
+}
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:06:41 $
+ */
+
diff -urdN ../Tekkotsu_2.3/local/sim/Motion.h ./local/sim/Motion.h
--- ../Tekkotsu_2.3/local/sim/Motion.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Motion.h	Wed Jun 29 18:06:41 2005
@@ -0,0 +1,60 @@
+//-*-c++-*-
+#ifndef INCLUDED_Motion_h_
+#define INCLUDED_Motion_h_
+
+#include "Process.h"
+#include "sim.h"
+#include "IPC/ProcessID.h"
+#include "IPC/SharedObject.h"
+#include "SharedGlobals.h"
+#include "Motion/MotionManager.h"
+#include "Sound/SoundManager.h"
+#include "Shared/WorldState.h"
+
+class Motion : public Process {
+public:
+	//! constructor
+	Motion();
+	//! destructor
+	~Motion();
+
+	virtual void DoStart();
+	virtual void run();
+	virtual void DoStop();
+
+	static const char * getClassName() { return "Motion"; }
+	static ProcessID::ProcessID_t getID() { return ProcessID::MotionProcess; }
+	
+	static const char * getMotionCommandID() { return "MotionCommands"; }
+	static const char * getMotionManagerID() { return "MotionManager"; }
+
+protected:
+	SharedObject<sim::SoundPlayQueue_t> sounds;
+	SharedObject<sim::MotionCommandQueue_t> motions;
+	SharedObject<sim::EventQueue_t> events;
+	SharedObject<MotionManager> motionmanager;
+	SharedObject<SoundManager> soundmanager;
+	SharedObject<WorldState> worldstate;
+	IPCEventTranslator * etrans;
+	class MessageReceiver * mcrecv;
+	WirelessThread wireless_thread;
+
+	static bool gotMC(RCRegion* msg) { motman->processMsg(msg); return true; }
+	
+private:
+	Motion(const Motion&); //!< don't call (copy constructor)
+	Motion& operator=(const Motion&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines Motion, which DESCRIPTION
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:06:41 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/Process.cc ./local/sim/Process.cc
--- ../Tekkotsu_2.3/local/sim/Process.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Process.cc	Wed Jun 15 14:54:26 2005
@@ -0,0 +1,33 @@
+#include "Process.h"
+#include "SharedGlobals.h"
+#include <unistd.h>
+
+std::string Process::name;
+Process * Process::current;
+
+Process::Process(ProcessID::ProcessID_t pid, const std::string& pname) {
+	ProcessID::setID(pid);
+	name=pname;
+	current=this;
+	globals->pids[ProcessID::getID()]=getpid();
+	strncpy(globals->processNames[ProcessID::getID()],name.c_str(),SharedGlobals::MAX_PROCESS_NAME_LEN);
+}
+
+Process::~Process() {
+	current=NULL;
+}
+
+void Process::run() {
+	globals->waitShutdown();
+}
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/15 18:54:26 $
+ */
diff -urdN ../Tekkotsu_2.3/local/sim/Process.h ./local/sim/Process.h
--- ../Tekkotsu_2.3/local/sim/Process.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Process.h	Wed Jun 15 14:54:43 2005
@@ -0,0 +1,40 @@
+//-*-c++-*-
+#ifndef INCLUDED_Process_h_
+#define INCLUDED_Process_h_
+
+#include "IPC/ProcessID.h"
+#include <string>
+
+//! Represents a common interface for each process being run
+class Process {
+public:
+	Process(ProcessID::ProcessID_t pid, const std::string& pname);
+	virtual ~Process();
+	virtual void DoStart() {}
+	virtual void DoStop() {}
+	virtual void run();
+
+	static const std::string& getName() { return name; }
+	static Process * getCurrent() { return current; }
+
+protected:
+	static std::string name;
+	static Process * current;
+	
+private:
+	Process(const Process&);            //!< don't call
+	Process& operator=(const Process&); //!< don't call
+};
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/15 18:54:43 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/SharedGlobals.cc ./local/sim/SharedGlobals.cc
--- ../Tekkotsu_2.3/local/sim/SharedGlobals.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/SharedGlobals.cc	Wed Jul 27 13:37:53 2005
@@ -0,0 +1,49 @@
+#include "SharedGlobals.h"
+
+const char * const SharedGlobals::runlevel_names[SharedGlobals::NUM_RUNLEVELS] = {
+	"CREATED",
+	"CONSTRUCTING",
+	"STARTING",
+	"RUNNING",
+	"STOPPING",
+	"DESTRUCTING",
+	"DESTRUCTED"
+};
+
+ipc_setup_t * ipc_setup=NULL;
+SharedGlobals * globals=NULL;
+
+unsigned int SharedGlobals::get_time() {
+	if(timeScale<=0) {
+		//just need to update lastTimeScale in case it had been realtime mode
+		//adding an 'if' to test before the assignment is slower than just always doing the assignment
+		lastTimeScale=timeScale;
+	} else {
+		if(lastTimeScale<=0) {
+			//switching from non-realtime to realtime mode -- reset time offset
+			timeOffset=bootTime.Age().Value()*timeScale*1000-simulatorTime;
+			lastTimeScale=timeScale;
+			//we reset timeOffset such that simulatorTime hasn't changed
+		} else if(lastTimeScale!=timeScale) {
+			//switching speeds -- reset time offset
+			simulatorTime=get_real_time(lastTimeScale);
+			timeOffset=bootTime.Age().Value()*timeScale*1000-simulatorTime;
+			lastTimeScale=timeScale;
+		} else {
+			simulatorTime=get_real_time(timeScale);
+		}
+		//cout << timeOffset << ' ' << lastTimeScale << ' ' << timeScale << endl;
+	}
+	return simulatorTime;
+}
+
+/*! @file
+ * @brief A class to hold various simulator parameters which need to be accessed from multiple processes
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.6 $
+ * $State: Exp $
+ * $Date: 2005/07/27 17:37:53 $
+ */
diff -urdN ../Tekkotsu_2.3/local/sim/SharedGlobals.h ./local/sim/SharedGlobals.h
--- ../Tekkotsu_2.3/local/sim/SharedGlobals.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/SharedGlobals.h	Thu Jul 28 14:22:26 2005
@@ -0,0 +1,189 @@
+//-*-c++-*-
+#ifndef INCLUDED_CLASSNAME_h_
+#define INCLUDED_CLASSNAME_h_
+
+#include "IPC/MutexLock.h"
+#include "IPC/SemaphoreManager.h"
+#include "IPC/ProcessID.h"
+#include "Shared/plist.h"
+#include "Shared/TimeET.h"
+
+//! A class to hold various simulator parameters which need to be accessed from multiple processes
+class SharedGlobals {
+public:
+	//! constructor
+	SharedGlobals()
+		: simulatorTime(0), timeScale(1), advanceOnAccess(true), lock(),
+		bootTime(), timeOffset(0), lastTimeScale(1), autoPauseTime(-1U),
+		semgr(), running(semgr.getSemaphore())
+	{
+		for(unsigned int i=0; i<NUM_RUNLEVELS; i++)
+			level_count[i]=0;
+		semgr.raise(running,1);
+	}
+	//! destructor
+	~SharedGlobals() {
+		semgr.releaseSemaphore(running);
+	}
+
+	//       ****************
+	//!@name Shutdown Control
+	//       ****************
+
+	//! call this to cause "system shutdown" -- clean halt of the simulator (not actually the host system)
+	void signalShutdown() {
+		semgr.setValue(running,0);
+	}
+	//! test to see if the shutdown flag has been set (non-blocking)
+	bool isShutdown() {
+		return semgr.testZero(running,false);
+	}
+	//! blocks until shutdown flag has been set
+	bool waitShutdown() {
+		return semgr.testZero(running,true);
+	}
+	
+	//! access to #semgr, returns SemaphoreManager::hadFault()
+	bool hadFault() const { return semgr.hadFault(); }
+	
+	//! access to #semgr's SemaphoreManager::faultShutdown() -- call this *after* a fault has occured from the signal handler; doesn't signal the fault itself
+	void faultShutdown() { semgr.faultShutdown(); }
+	
+	//@}
+
+
+	//       ************
+	//!@name Time Control
+	//       ************
+
+	//! returns the current simulator time, in milliseconds since startup
+	/*! the simulator should set project_get_time::get_time_callback to call this,
+	 *  so calls to ::get_time() will be forwarded here.  That wall all processes
+	 *  will share the same time */
+	unsigned int get_time();
+
+	//! the current time within the simulation, only applicable when #isRealTime is false
+	unsigned int simulatorTime;
+	
+	//! The speed at which time from get_time() will move when #isRealTime is true
+	/*! You can use this to pretend your hardware is faster or slower
+	 *  than it actually is.  For instance, a value of .5 means time
+	 *  will move at half speed (pretending your hardware is twice as
+	 *  fast)  This can be useful for "slow motion" analysis, or you
+	 *  can speed up time to simulate a more processor-restrictive platform.
+	 *
+	 *  Negative values indicate full-speed processing -- time will be
+	 *  incremented only as quickly as it can be without dropping any
+	 *  video or sensor frames. (may be faster or slower than realtime)
+	 *
+	 *  A value of zero halts time. */
+	plist::Primitive<double> timeScale;
+
+	//! If true, and #timeScale is negative, simulator will automatically advance simulatorTime after each data update is processed, allowing full-speed processing
+	/*! This functionality is actually achieved by having the receiver mark the
+	 *  message read when it is ready for another message.  If #advanceOnAccess is
+	 *  false, the receiver will not automatically mark the message read when it
+	 *  is accessed, and you will have to make a manual call within your code to
+	 *  signal completion.  For example, typically you will be doing this from
+	 *  Main process, which would look like this:
+	 *
+	 *  @code
+	 *  #include "local/sim/Main.h"
+	 *  
+	 *  Main::advanceVision(); //only legal if your code is
+	 *  Main::advanceSensor(); // actually running in Main!
+	 *  @endcode
+	 *
+	 *  This flag applies to both sensors and vision, but ignored when in realtime
+	 *  mode (0 or positive #timeScale, or loading from a realtime source, such as
+	 *  live telemetry)
+	 */
+	plist::Primitive<bool> advanceOnAccess;
+
+	//! sets #autoPauseTime
+	void setAutoPauseTime(unsigned int t) { autoPauseTime=t; }
+	
+	//@}
+
+
+	//       **********************
+	//!@name Runlevel Communication
+	//       **********************
+
+	//! defines the runlevels that each process passes through; runlevels should monotonically increase (can't go backwards)
+	enum runlevel_t {
+		CREATED=0,    //!< corresponding element of #level_count is incremented prior to each fork -- not strictly a runlevel per se
+		CONSTRUCTING, //!< currently initializing
+		STARTING,     //!< setting up shared memory regions with other processes
+		RUNNING,      //!< full activity, stay here until the #running semaphore is set to 0
+		STOPPING,     //!< dereferencing shared regions, waiting for threads to finish
+		DESTRUCTING,  //!< destructors are in progress
+		DESTRUCTED,   //!< destruction has completed, corresponding element of #level_count is incremented immediately prior to process completion
+	};
+	static const unsigned int NUM_RUNLEVELS=DESTRUCTED+1; //!< symbolic access to the total number of runlevel stages
+
+	//! string versions of runlevel_t for runtime user-feedback
+	static const char * const runlevel_names[NUM_RUNLEVELS];
+
+	//! a count of the number of processes which have passed through each runlevel
+	unsigned int level_count[NUM_RUNLEVELS];
+
+	//@}
+
+	//! allows mutually exclusive access to the fields of SharedObject
+	MutexLock<ProcessID::NumProcesses> lock;
+
+	//! holds the host system's process ID for each simulator process
+	pid_t pids[ProcessID::NumProcesses];
+
+	//! maximum storage size of strings in #processNames
+	static const unsigned int MAX_PROCESS_NAME_LEN=32;
+
+	//! each process should set a string version of its name for user feedback
+	char processNames[ProcessID::NumProcesses][MAX_PROCESS_NAME_LEN];
+	
+protected:
+	//! this returns time since boot (#bootTime), scaled by @a scale, relative to #timeOffset
+	unsigned int get_real_time(double scale) const {
+		return static_cast<unsigned int>(bootTime.Age().Value()*scale*1000-timeOffset);
+	}
+
+	//! real time since simulator startup (or, at least, since SharedGlobals was constructed... close enough)
+	TimeET bootTime; 
+
+	//! the scaled value of #bootTime at which isRealTime was last activated, allows you to start and stop realtime fluidly
+	double timeOffset; 
+	
+	//! updated by each call to get_time(), if timeScale differs, allows timeOffset to be updated fluidly
+	double lastTimeScale;
+	
+	//! if simulatorTime is about to move past this value, timeScale is set to 0 instead, and simulatorTime is set to this
+	unsigned int autoPauseTime;
+	
+	SemaphoreManager semgr; //!< a semaphore set, only used for #running
+	SemaphoreManager::semid_t running; //!< the semaphore within #semgr to communicate shutdown status between processes -- when the semaphore is set to 0, shutdown is requested
+};
+
+const unsigned int MAX_SUBJECTS=50; //!< maximum number of message queues the simulator can maintain
+const unsigned int MAX_SUBJECT_NAME=50; //!< maximum storage capacity of subject names
+
+// just a forward definition of RegionRegistry
+template<unsigned int MAX_SUBJECTS, unsigned int MAX_SUBJECT_NAME> class RegionRegistry;
+//! the type to use for the inter-process communication registry
+typedef RegionRegistry<MAX_SUBJECTS,MAX_SUBJECT_NAME> ipc_setup_t;
+
+extern ipc_setup_t * ipc_setup; //!< a global pointer to the inter-process message queue registry (a RegionRegistry)
+extern SharedGlobals * globals; //!< a global pointer to the SharedGlobals instance
+
+/*! @file
+ * @brief A class to hold various simulator parameters which need to be accessed from multiple processes
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.8 $
+ * $State: Exp $
+ * $Date: 2005/07/28 18:22:26 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/SimConfig.cc ./local/sim/SimConfig.cc
--- ../Tekkotsu_2.3/local/sim/SimConfig.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/SimConfig.cc	Wed Jun  1 01:48:07 2005
@@ -0,0 +1,14 @@
+#include "SimConfig.h"
+
+
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.2 $
+ * $State: Exp $
+ * $Date: 2005/06/01 05:48:07 $
+ */
diff -urdN ../Tekkotsu_2.3/local/sim/SimConfig.h ./local/sim/SimConfig.h
--- ../Tekkotsu_2.3/local/sim/SimConfig.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/SimConfig.h	Mon Jul 25 23:07:36 2005
@@ -0,0 +1,59 @@
+//-*-c++-*-
+#ifndef INCLUDED_SimConfig_h_
+#define INCLUDED_SimConfig_h_
+
+#include "Shared/plist.h"
+#include "SharedGlobals.h"
+
+//! description of SimConfig
+class SimConfig : public plist::Dictionary {
+public:
+	SimConfig() : 
+		cmdPrompt("sim >"),
+		initSimTime(0),
+		tgtRunlevel(SharedGlobals::RUNNING, SharedGlobals::runlevel_names, SharedGlobals::NUM_RUNLEVELS),
+		runTo(-1U),
+		lastfile()
+	{
+		setUnusedWarning(false);
+		addEntry("InitialTime",initSimTime,"The value to initialize the simulator's clock (in milliseconds)");
+		addEntry("InitialRunlevel",tgtRunlevel,"Specifies how far startup should proceed before pausing for user interaction.\nThis value only affects startup, and setting this value from the simulator command prompt will have no effect.  (Use the 'runlevel' command instead.)");
+		addEntry("RunToTime",runTo,"Time at which to automatically set Speed to 0, from either realtime or non-realtime mode");
+	}
+	
+	std::string cmdPrompt; //!< not persistently stored -- [re]set by main(...) on each run
+	plist::Primitive<unsigned int> initSimTime;
+	plist::NamedEnumeration<SharedGlobals::runlevel_t> tgtRunlevel;
+	plist::Primitive<unsigned int> runTo;
+
+	void setLastFile(const std::string& str) const {
+		lastfile=str;
+	}
+	const std::string& getLastFile() const {
+		return lastfile;
+	}
+	virtual	unsigned int LoadFile(const char* filename) {
+		lastfile=filename;
+		return Dictionary::LoadFile(filename);
+	}
+	virtual unsigned int SaveFile(const char* filename) const {
+		lastfile=filename;
+		return Dictionary::SaveFile(filename);
+	}
+	
+protected:
+	mutable std::string lastfile;
+};
+
+/*! @file
+ * @brief 
+ * @author Ethan Tira-Thompson (ejt) (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/07/26 03:07:36 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/Simulator.cc ./local/sim/Simulator.cc
--- ../Tekkotsu_2.3/local/sim/Simulator.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Simulator.cc	Wed Aug  3 02:37:41 2005
@@ -0,0 +1,334 @@
+#include "Simulator.h"
+#include "IPC/RegionRegistry.h"
+#include "Shared/string_util.h"
+#include "Shared/RobotInfo.h"
+#include <iostream>
+#include "SimConfig.h"
+
+using namespace std;
+
+Simulator::Simulator()
+: Process(getID(),getClassName()),
+cameraQueue(ipc_setup->registerRegion(Simulator::getCameraQueueID(),sizeof(sim::CameraQueue_t))),
+sensorQueue(ipc_setup->registerRegion(Simulator::getSensorQueueID(),sizeof(sim::SensorQueue_t))),
+vision("images", ".*\\.jpg", 30, *cameraQueue),
+sensors("sensors", ".*\\.txt", 1000.f/NumFrames/FrameTime, *sensorQueue),
+visionLayer(-2)
+{
+	new (&(*cameraQueue)) sim::CameraQueue_t;
+	new (&(*sensorQueue)) sim::SensorQueue_t;
+	sim::config.writeParseTree();
+	sim::config.addEntry("Sensors",sensors);
+	sim::config.addEntry("Vision",vision);
+	vision.addEntry("Layer",visionLayer,"Controls at what resolution layer the image should be processed.\n0 and positive numbers indicate the resolution layer directly as it would be accessed by behaviors.\nNegative values are relative to the number of layers marked available by the vision setup, so that typically -1 would correspond to the \"double\" layer, and -2 would correspond to the \"full\" layer.");
+	sim::config.readParseTree();
+	for(unsigned int i=0; i<sim::assignments.size(); i++) {
+		vector<string> setarg;
+		setarg.push_back("set");
+		setarg.push_back(sim::assignments[i]);
+		cmdSet(setarg);
+	}
+	if(globals->timeScale<0) {
+		cameraQueue->setOverflowPolicy(MessageQueueBase::WAIT);
+		sensorQueue->setOverflowPolicy(MessageQueueBase::WAIT);
+	} else {
+		cameraQueue->setOverflowPolicy(MessageQueueBase::DROP_OLDEST);
+		sensorQueue->setOverflowPolicy(MessageQueueBase::DROP_OLDEST);
+	}
+	globals->timeScale.addPrimitiveListener(this);
+	processRunlevel(SharedGlobals::CONSTRUCTING);
+}
+
+Simulator::~Simulator() {
+	globals->timeScale.removePrimitiveListener(this);
+	processRunlevel(SharedGlobals::DESTRUCTING);
+}
+
+void Simulator::DoStart() {
+	Process::DoStart();
+	processRunlevel(SharedGlobals::STARTING);
+}
+
+void Simulator::run() {
+	for(unsigned int i=0; i<ProcessID::NumProcesses; ++i)
+		cout << globals->processNames[i] << " pid=" << globals->pids[i] << ";  ";
+	cout << endl;
+
+	vision.addStatusListener(this);
+	vision.addStatusListener(this);
+	vision.loadFileList();
+	vision.start();
+
+	processRunlevel(SharedGlobals::RUNNING);
+
+	vision.stop();
+	vision.removeStatusListener(this);
+	vision.removeStatusListener(this);
+
+	globals->signalShutdown();
+	cout << "So long buddy!" << endl;
+}
+
+void Simulator::plistValueChanged(const plist::PrimitiveBase& pl) {
+	if(&pl==&globals->timeScale) {
+		get_time(); // force SharedGlobals to notice the change and update its state
+		if(globals->timeScale<0) {
+			cameraQueue->setOverflowPolicy(MessageQueueBase::WAIT);
+			sensorQueue->setOverflowPolicy(MessageQueueBase::WAIT);
+			unsigned int next=std::min(vision.nextTimestamp(),sensors.nextTimestamp());
+			if(next!=-1U)
+				globals->simulatorTime=next;
+		} else {
+			cameraQueue->setOverflowPolicy(MessageQueueBase::DROP_OLDEST);
+			sensorQueue->setOverflowPolicy(MessageQueueBase::DROP_OLDEST);
+		}
+	} else {
+		cerr << "WARNING: Simulator got a plistValueChanged for an unknown plist primitive";
+	}
+}
+
+void Simulator::messagesRead(MessageQueueBase& mq, unsigned int /*n*/) {
+	if(globals->timeScale<0) {
+		if(&mq==&(*cameraQueue)) {
+			unsigned int next=vision.nextTimestamp();
+			if(next!=-1U)
+				globals->simulatorTime=next;
+		} else if(&mq==&(*sensorQueue)) {
+			unsigned int next=sensors.nextTimestamp();
+			if(next!=-1U)
+				globals->simulatorTime=next;
+		}
+	}
+}
+
+void Simulator::DoStop() {
+	processRunlevel(SharedGlobals::STOPPING);
+	Process::DoStop();
+}
+
+void Simulator::processRunlevel(SharedGlobals::runlevel_t curLevel) {
+	while(sim::config.tgtRunlevel==curLevel && (!globals->isShutdown() || curLevel>SharedGlobals::RUNNING)) {
+		string line;
+		cout << sim::config.cmdPrompt << flush;
+		getline(cin,line);
+		if(line=="shutdown" || line=="quit" || line=="exit" || !cin) {
+			sim::config.tgtRunlevel=SharedGlobals::DESTRUCTED;
+			break;
+		}
+		vector<string> args;
+		vector <unsigned int> offs;
+		if(!string_util::parseArgs(line,args,offs)) {
+			cerr << "Mismatched quotes" << endl;
+			continue;
+		}
+		if(args.size()==0)
+			continue;
+		if(args[0]=="load") {
+			cmdLoad(args);
+		} else if(args[0]=="save") {
+			cmdSave(args);
+		} else if(args[0]=="runlevel") {
+			cmdRunlevel(args, curLevel);
+		} else if(args[0]=="get_time") {
+			cout << "Current time is " << get_time() << endl;
+		} else if(args[0]=="set") {
+			cmdSet(args);
+		} else if(args[0]=="runto") {
+			cmdRun(args,curLevel,false);
+		} else if(args[0]=="runfor") {
+			cmdRun(args,curLevel,true);
+		} else if(args[0]=="run") {
+			cmdRun(args,curLevel);
+		} else if(args[0]=="pause") {
+			cmdPause(args,curLevel);
+		} else if(args[0]=="help") {
+			cmdHelp(args);
+		} else {
+			cout << "Unknown command '" << args[0] << "'" << endl;
+		}
+	}
+}
+
+void Simulator::cmdLoad(const std::vector<std::string>& args) {
+	if(args.size()>1)
+		for(unsigned int i=1; i<args.size(); i++)
+			sim::config.LoadFile(args[i].c_str());
+	else
+		sim::config.LoadFile(sim::config.getLastFile().c_str());
+}
+void Simulator::cmdSave(const std::vector<std::string>& args) {
+	if(args.size()>1)
+		for(unsigned int i=1; i<args.size(); i++)
+			sim::config.SaveFile(args[i].c_str());
+	else
+		sim::config.SaveFile(sim::config.getLastFile().c_str());
+}
+void Simulator::cmdRunlevel(const std::vector<std::string>& args, SharedGlobals::runlevel_t curLevel) {
+	if(args.size()==1) {
+		sim::config.tgtRunlevel=static_cast<SharedGlobals::runlevel_t>(sim::config.tgtRunlevel+1);
+		cout << "Moving to next runlevel: " << SharedGlobals::runlevel_names[sim::config.tgtRunlevel] << endl;
+		return;
+	}
+	try {
+		sim::config.tgtRunlevel=string_util::makeUpper(args[1]);
+	} catch(...) {
+		cout << "Invalid runlevel specification.  Try one of:\n\t";
+		for(unsigned int i=0; i<SharedGlobals::NUM_RUNLEVELS; i++)
+			cout << i << ' ' << SharedGlobals::runlevel_names[i] << ", ";
+		cout << "\nCurrently at " << SharedGlobals::runlevel_names[curLevel] << endl;
+		return;
+	}
+	if(sim::config.tgtRunlevel<curLevel) {
+		sim::config.tgtRunlevel=curLevel;
+		cout << "Cannot reduce runlevel, currently at " << curLevel << ' ' << SharedGlobals::runlevel_names[curLevel] << "\n\t";
+		for(unsigned int i=0; i<SharedGlobals::NUM_RUNLEVELS; i++)
+			cout << i << ' ' << SharedGlobals::runlevel_names[i] << ", ";
+		cout << endl;
+	} else if(sim::config.tgtRunlevel==curLevel) {
+		cout << "Already at " << curLevel << ' ' << SharedGlobals::runlevel_names[curLevel] << "\n\t";
+		for(unsigned int i=0; i<SharedGlobals::NUM_RUNLEVELS; i++)
+			cout << i << ' ' << SharedGlobals::runlevel_names[i] << ", ";
+		cout << endl;
+	}
+}
+void Simulator::cmdSet(const std::vector<std::string>& args) {
+	if(args.size()==1) {
+		cout << sim::config << endl;
+		return;
+	}
+	string arg;
+	for(unsigned int i=1; i<args.size(); i++) {
+		arg+=args[i];
+		if(i!=args.size()-1)
+			arg+=" ";
+	}
+	if(arg.rfind("=")==string::npos) {
+		plist::ObjectBase* ob=sim::config.findEntry(arg);
+		if(ob==NULL) {
+			cout << "'" << arg << "' is unknown" << endl;
+			return;
+		}
+		cout << *ob << endl;
+	} else {
+		string value=string_util::trim(arg.substr(arg.find("=")+1));
+		string key=string_util::trim(arg.substr(0,arg.find("=")));
+		plist::ObjectBase* ob=sim::config.findEntry(key);
+		if(ob==NULL) {
+			cout << "'" << key << "' is unknown" << endl;
+			return;
+		}
+		if(plist::PrimitiveBase* pbp=dynamic_cast<plist::PrimitiveBase*>(ob)) {
+			try {
+				pbp->set(value);
+			} catch(const XMLLoadSave::bad_format& bf) {
+				cout << "'" << value << "' is a bad value for '" << key << "'" << endl;
+				cout << bf.what() << endl;
+			} catch(const std::exception& e) {
+				cout << "An exception occured: " << e.what() << endl;
+			}
+		} else {
+			cout << "Cannot assign to a dictionary" << endl;
+			return;
+		}
+	}
+}
+void Simulator::cmdRun(const std::vector<std::string>& args, SharedGlobals::runlevel_t /*curLevel*/, bool isRelative) {
+	if(args.size()<=1)
+		return;
+	if(isRelative)
+		globals->setAutoPauseTime(get_time()+atoi(args[1].c_str()));
+	else
+		globals->setAutoPauseTime(atoi(args[1].c_str()));
+}
+void Simulator::cmdRun(const std::vector<std::string>& /*args*/, SharedGlobals::runlevel_t /*curLevel*/) {
+	globals->timeScale=1;
+}
+void Simulator::cmdPause(const std::vector<std::string>& /*args*/, SharedGlobals::runlevel_t /*curLevel*/) {
+	globals->timeScale=0;
+}
+void Simulator::cmdHelp(const std::vector<std::string>& args) {
+	map<string,string> syntax;
+	syntax["load"]="[file]";
+	syntax["save"]="[file]";
+	syntax["runlevel"]="[";
+	for(unsigned int i=0; i<SharedGlobals::NUM_RUNLEVELS; i++) {
+		stringstream ss;
+		ss << i << "|" << SharedGlobals::runlevel_names[i];
+		if(i!=SharedGlobals::NUM_RUNLEVELS-1)
+			ss << " | ";
+		syntax["runlevel"]+=ss.str();
+	}
+	syntax["runlevel"]+="]";
+	syntax["get_time"]+="";
+	syntax["set"]+="[var=value]";
+	syntax["runto"]+="time";
+	syntax["runfor"]+="time";
+	syntax["run"]+="";
+	syntax["pause"]+="";
+	
+	map<string,string> help;
+	help["load"]="Load simulator configuration from file; if file unspecified, defaults to 'simulator.plist'.";
+	help["save"]="Save simulator configuration to file; if file unspecified, defaults to 'simulator.plist'.";
+	help["runlevel"]="You can specify a runlevel to move to, or if unspecified, the next one.\n"
+		"You can only move forward runlevels, not backward.  Usually you'll only need RUNNING,\n"
+		"unless you are debugging startup/shutdown code or the simulator itself.";
+	help["get_time"]="Displays the simulator time.";
+	help["set"]="Sets simulator configuration variables.  Without any arguments, displays\n"
+		"all available variables and their current values.  Type 'help set <variable>' to get\n"
+		"more information about a particular variable.";
+	help["runto"]="Will advance the simulator time to a the specified value and then set Speed to 0.";
+	help["runfor"]="Will advance the simulator time forward the specified number of milliseconds and then set Speed to 0.";
+	help["run"]="Equivalent to 'set Speed=1'";
+	help["pause"]="Equivalent to 'set Speed=0'";
+	
+	if(args.size()==1) {
+		cout << "Available commands: " << endl;
+		for(map<string,string>::const_iterator it=help.begin(); it!=help.end(); ++it) {
+			cout << '\t' << it->first << " " << syntax[it->first] << endl;
+		}
+		cout << "type 'help <command>' for more information" << endl;
+	} else {
+		if(help.find(args[1])==help.end()) {
+			cout << "The command '"<< args[1] << "' was not found" << endl;
+			return;
+		}
+		if(args.size()==2) {
+			cout << args[1] << " " << syntax[args[1]] << endl;
+			cout << help[args[1]] << endl;
+		} else {
+			if(args[1]=="set") {
+				plist::ObjectBase* ob=sim::config.findEntry(args[2]);
+				if(ob==NULL) {
+					cout << "'" << args[2] << "' is unknown" << endl;
+					return;
+				}
+				size_t n=args[2].rfind('.');
+				if(n==string::npos)
+					cout << sim::config.getComment(args[2]) << endl;
+				else {
+					ob=sim::config.findEntry(args[2].substr(0,n));
+					if(const plist::Dictionary * dict=dynamic_cast<const plist::Dictionary*>(ob))
+						cout << dict->getComment(args[2].substr(n+1)) << endl;
+					else
+						cout << "'" << args[2].substr(0,n) << "' is not a dictionary" << endl;
+				}
+			} else {
+				cout << args[1] << " " << syntax[args[1]] << endl;
+				cout << help[args[1]] << endl;
+			}
+		}
+	}
+}
+
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.9 $
+ * $State: Exp $
+ * $Date: 2005/08/03 06:37:41 $
+ */
+
diff -urdN ../Tekkotsu_2.3/local/sim/Simulator.h ./local/sim/Simulator.h
--- ../Tekkotsu_2.3/local/sim/Simulator.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/Simulator.h	Wed Aug  3 02:37:42 2005
@@ -0,0 +1,66 @@
+//-*-c++-*-
+#ifndef INCLUDED_Simulator_h_
+#define INCLUDED_Simulator_h_
+
+#include "Process.h"
+#include "sim.h"
+#include "IPC/SharedObject.h"
+#include "SharedGlobals.h"
+#include "Shared/plist.h"
+#include "LoadImageThread.h"
+
+class Simulator : public Process,  public plist::PrimitiveListener, public MessageQueueBase::StatusListener {
+public:
+	//! constructor
+	Simulator();
+	
+	~Simulator();
+
+	virtual void DoStart();
+	virtual void DoStop();
+	virtual void run();
+	
+	static const char * getClassName() { return "Simulator"; }
+	static ProcessID::ProcessID_t getID() { return ProcessID::SimulatorProcess; }
+	
+	static const char * getCameraQueueID() { return "CameraData"; }
+	static const char * getSensorQueueID() { return "SensorData"; }
+
+	virtual void plistValueChanged(const plist::PrimitiveBase& pl);
+
+	virtual void messagesRead(MessageQueueBase& mq, unsigned int n);
+
+protected:
+	void processRunlevel(SharedGlobals::runlevel_t curLevel);
+	void cmdLoad(const std::vector<std::string>& args);
+	void cmdSave(const std::vector<std::string>& args);
+	void cmdRunlevel(const std::vector<std::string>& args, SharedGlobals::runlevel_t curLevel);
+	void cmdSet(const std::vector<std::string>& args);
+	void cmdRun(const std::vector<std::string>& args, SharedGlobals::runlevel_t curLevel, bool isRelative);
+	void cmdRun(const std::vector<std::string>& args, SharedGlobals::runlevel_t curLevel);
+	void cmdPause(const std::vector<std::string>& args, SharedGlobals::runlevel_t curLevel);
+	void cmdHelp(const std::vector<std::string>& args);
+	
+	SharedObject<sim::CameraQueue_t> cameraQueue;
+	SharedObject<sim::SensorQueue_t> sensorQueue;
+	LoadImageThread vision;
+	LoadImageThread sensors;
+	plist::Primitive<int> visionLayer;
+
+private:
+	Simulator(const Simulator&); //!< don't call (copy constructor)
+	Simulator& operator=(const Simulator&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines Simulator, which DESCRIPTION
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
+ * $State: Exp $
+ * $Date: 2005/08/03 06:37:42 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/SoundPlay.cc ./local/sim/SoundPlay.cc
--- ../Tekkotsu_2.3/local/sim/SoundPlay.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/SoundPlay.cc	Wed Jun 29 18:06:41 2005
@@ -0,0 +1,65 @@
+#include "SoundPlay.h"
+#include "SharedGlobals.h"
+#include "Main.h"
+#include "IPC/RegionRegistry.h"
+#include "IPC/MessageReceiver.h"
+#include "Events/EventRouter.h"
+
+SoundPlay::SoundPlay()
+	: Process(getID(),getClassName()),
+		requests(ipc_setup->registerRegion(getSoundPlayID(),sizeof(sim::SoundPlayQueue_t))),
+		events(ipc_setup->registerRegion(Main::getEventsID(),sizeof(sim::EventQueue_t))),
+		soundmanager(ipc_setup->registerRegion(getSoundManagerID(),sizeof(SoundManager))),
+		etrans(NULL), sndrecv(NULL)
+{
+	new (&(*requests)) sim::SoundPlayQueue_t;
+	new (&(*soundmanager)) SoundManager();
+	sndman=&(*soundmanager);
+
+	//need to register any events which we might be sending
+	EventTranslator::registerPrototype<EventBase>(); //Sound only sends the basic event type
+}
+
+SoundPlay::~SoundPlay() {
+	delete etrans;
+	etrans=NULL;
+	MotionManager::setTranslator(NULL);
+}
+
+void SoundPlay::DoStart() {
+	Process::DoStart();
+	//These are constructed by other processes, so need to wait
+	//until the construction runlevel is complete before we access them
+	etrans=new IPCEventTranslator(*events);
+	MotionManager::setTranslator(etrans); //although SoundPlay shouldn't use any motions...
+
+	// Set up Event Translator to trap and send events to main process
+	//send everything over except erouter events
+	for(unsigned int i=0; i<EventBase::numEGIDs; i++)
+		if(i!=EventBase::erouterEGID)
+			erouter->addTrapper(etrans,static_cast<EventBase::EventGeneratorID_t>(i));
+	
+	sndrecv=new MessageReceiver(*requests,gotSnd);
+}
+
+void SoundPlay::DoStop() {
+	sndrecv->finish();
+	delete sndrecv;
+	sndrecv=NULL;
+	sndman->StopPlay();
+	erouter->removeTrapper(etrans);
+	Process::DoStop();
+}
+
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.3 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:06:41 $
+ */
+
diff -urdN ../Tekkotsu_2.3/local/sim/SoundPlay.h ./local/sim/SoundPlay.h
--- ../Tekkotsu_2.3/local/sim/SoundPlay.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/SoundPlay.h	Wed Jun 29 18:06:41 2005
@@ -0,0 +1,52 @@
+//-*-c++-*-
+#ifndef INCLUDED_SoundPlay_h_
+#define INCLUDED_SoundPlay_h_
+
+#include "Process.h"
+#include "sim.h"
+#include "IPC/ProcessID.h"
+#include "IPC/SharedObject.h"
+#include "SharedGlobals.h"
+#include "Sound/SoundManager.h"
+
+class SoundPlay : public Process {
+public:
+	//! constructor
+	SoundPlay();
+	//! destructor
+	~SoundPlay();
+
+	virtual void DoStart();
+	virtual void DoStop();
+
+	static const char * getClassName() { return "SoundPlay"; }
+	static ProcessID::ProcessID_t getID() { return ProcessID::SoundProcess; }
+	
+	static const char * getSoundPlayID() { return "Sounds"; }
+	static const char * getSoundManagerID() { return "SoundManager"; }
+
+protected:
+	SharedObject<sim::SoundPlayQueue_t> requests;
+	SharedObject<sim::EventQueue_t> events;
+	SharedObject<SoundManager> soundmanager;
+	IPCEventTranslator * etrans;
+	class MessageReceiver * sndrecv;
+	static bool gotSnd(RCRegion* msg) { sndman->ProcessMsg(msg); return true; }
+	
+private:
+	SoundPlay(const SoundPlay&); //!< don't call (copy constructor)
+	SoundPlay& operator=(const SoundPlay&); //!< don't call (assignment operator)
+};
+
+/*! @file
+ * @brief Defines SoundPlay, which DESCRIPTION
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.4 $
+ * $State: Exp $
+ * $Date: 2005/06/29 22:06:41 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/local/sim/sim.cc ./local/sim/sim.cc
--- ../Tekkotsu_2.3/local/sim/sim.cc	Wed Dec 31 19:00:00 1969
+++ ./local/sim/sim.cc	Thu Aug  4 17:30:07 2005
@@ -0,0 +1,373 @@
+#include "sim.h"
+#include "local/sim/SharedGlobals.h"
+#include "local/sim/Main.h"
+#include "local/sim/Motion.h"
+#include "local/sim/SoundPlay.h"
+#include "local/sim/SimConfig.h"
+#include "IPC/RegionRegistry.h"
+#include "local/sim/Simulator.h"
+#include "IPC/SharedObject.h"
+#include "Shared/Config.h"
+#include "IPC/SemaphoreManager.h"
+#include "Events/EventRouter.h"
+#include <iostream>
+#include <sstream>
+#include <iomanip>
+#include <sys/ipc.h>
+#include <signal.h>
+#include <unistd.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <errno.h>
+
+using namespace std;
+
+const char * const sim::usage=
+"[-h|--help] [-c|--config config-file] [var=val ...]";
+
+//only true for the first process -- children should set this to false when they fork
+bool sim::original=true;
+
+SimConfig sim::config;
+vector<string> sim::assignments;
+
+/* Although I generally dislike the "can't have main function without a class declaration" style of java,
+ * sometimes it does come in handy.  See the class notes for sim for more information. */
+int main(int argc, const char* argv[]) {
+	
+	//This should match the ID of the process sent to manage_process by sim::run()
+	// *must* be done before we create any shared regions to provide proper reference counting
+	ProcessID::setID(ProcessID::SimulatorProcess);
+	
+	sim s;
+	if(!s.processCommandLine(argc,argv))
+		return 2;
+	//now the real meat begins
+	if(!s.run()) //when this eventually returns, we're done (and all our children forks as well)
+		return 1;
+	return 0;
+
+}
+
+sim::sim() :
+	mutexSemMgr(),
+	glob(),
+	subj()
+{
+	//what's the granularity of usleep on this platform?
+	MutexLockBase::usleep_granularity=measure_usleep_cost();
+	//use our own custom get_time routine
+	project_get_time::get_time_callback=&sim_get_time;
+
+	//setup signal handlers
+	signal(SIGINT, handle_signal);
+	signal(SIGQUIT, handle_signal);
+	signal(SIGTERM, handle_signal);
+	signal(SIGSEGV, handle_signal);
+	signal(SIGBUS, handle_signal);
+	signal(SIGPIPE, handle_signal);
+	signal(SIGABRT, handle_signal);
+	signal(SIGFPE, handle_signal);
+	signal(SIGHUP, handle_signal);
+	atexit(handle_exit);
+	
+	//Set up mutex's semaphore manager
+	MutexLockBase::setSemaphoreManager(&(*mutexSemMgr));
+
+	//Set up shared global parameters -- e.g. clock and runlevel info
+	globals = &(*glob);
+	sim::config.addEntry("Speed",globals->timeScale,"The speed at which to run the simulation, as a multiple of \"real-time\".\nFor example, '1' is normal, '0.5' is half-speed, '0' is paused.\nAny negative value requests non-realtime mode, where the clock is moved as fast as processing (or manual control) allows.");
+	sim::config.addEntry("AdvanceOnAccess",globals->advanceOnAccess,"When running in non-realtime mode (see Speed), the simulator can either automatically advance to the next input after the previous input was accessed (if true), or wait until an explicit call to Main::advanceVision() (or manual change from the simulator command line) (if false)");
+	globals->simulatorTime=sim::config.initSimTime;
+	
+	//Set up the subject registration area
+	ipc_setup = &(*subj);
+	
+	//everyone uses config and erouter, might as well set it up here
+	::config = new Config("ms/config/tekkotsu.cfg");
+	::config->setFileSystemRoot("ms");
+	::erouter = new EventRouter;
+
+	//we won't have sensor values yet, but the system clock is good enough
+	if(::config->main.seed_rng) {
+		double t=TimeET().Value(); //current time with nanosecond resolution
+		unsigned int * tm=reinterpret_cast<unsigned int*>(&t);
+		unsigned int seed=tm[0]+tm[1];
+/*
+		for(unsigned int i=0; i<NumPIDJoints; i++) { //joint positions
+			unsigned int * x=reinterpret_cast<unsigned int*>(&state->outputs[i]);
+			seed+=(*x)<<((i%sizeof(unsigned int))*8);
+		}
+		for(unsigned int i=0; i<NumPIDJoints; i++) { //joint forces
+			unsigned int * x=reinterpret_cast<unsigned int*>(&state->pidduties[i]);
+			seed+=(*x)<<((i%sizeof(unsigned int))*8);
+		}
+		for(unsigned int i=0; i<NumSensors; i++) {
+			unsigned int * x=reinterpret_cast<unsigned int*>(&state->sensors[i]);
+			seed+=(*x)<<((i%sizeof(unsigned int))*8); //sensor values
+		}
+*/
+		cout << "RNG seed=" << seed << endl;;
+		srand(seed);
+	}
+
+}
+
+bool sim::processCommandLine(int argc, const char* argv[]) {
+	int i=0;
+
+	//try to load the default configuration file
+	const char * const defaultconfigfile="simulator.plist";
+	struct stat sb;
+	if(stat(defaultconfigfile,&sb)==0) {
+		if(!sim::config.LoadFile(defaultconfigfile)) {
+			cerr << "Error loading default configuration file, may be malformed." << endl;
+			return false;
+		}
+	} else
+		sim::config.setLastFile(defaultconfigfile);
+
+	//set the prompt from the binary name
+	config.cmdPrompt=argv[i];
+	if(config.cmdPrompt.rfind('/')!=string::npos)
+		config.cmdPrompt=config.cmdPrompt.substr(config.cmdPrompt.rfind('/')+1);
+	config.cmdPrompt+="> ";
+
+	//now run through the rest of the arguments
+	for(i++; i<argc; i++) {
+		if(!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help")) {
+			cerr << argv[0] << ": " << usage << endl;
+			return false;
+		} else if(!strcmp(argv[i],"-c") || !strcmp(argv[i],"--config")) {
+			if(!sim::config.LoadFile(argv[++i]))
+				return false;
+		} else if(strchr(argv[i],'=')!=NULL) {
+			assignments.push_back(argv[i]);
+		} else {
+			cerr << "Unknown argument '" << argv[i] << "': assignments must be of the form 'var=value'" << endl;
+			return false;
+		}
+	}
+	
+	return true;
+}
+
+bool sim::run() {
+	//this will force all of the processes to wait at the end of construction
+	//until we're done spawning all of them
+	globals->level_count[SharedGlobals::CREATED]++;
+	
+	cout << "Spawning processes..." << endl;
+	cout.setf(ios::left);
+	cout << "  Initializing runlevel " << setw(12) << SharedGlobals::runlevel_names[SharedGlobals::CONSTRUCTING] << endl;
+	cout.unsetf(ios::left);
+	if(fork_process<Main>()) ;
+	else if(fork_process<Motion>()) ;
+	else if(fork_process<SoundPlay>()) ;
+	else manage_process<Simulator>();
+	
+	//every process is going to pass through here on their way out
+	globals->level_count[SharedGlobals::DESTRUCTED]++;
+	
+	return true;
+}
+
+sim::~sim() {
+	config.removeEntry("TimeMultiplier");
+	MutexLockBase::setSemaphoreManager(NULL);
+	globals=NULL;
+	ipc_setup=NULL;
+	
+	if(original)
+		cout << "Waiting for children to exit..." << endl;
+	int res=wait(NULL);
+	if(res<0 && errno!=ECHILD)
+		perror("wait");
+}
+
+void sim::wait_runlevel(SharedGlobals::runlevel_t level) {
+	globals->lock.lock(ProcessID::getID());
+	globals->level_count[level]++;
+	if(globals->level_count[level]==1) {
+		cout.setf(ios::left);
+		cout << "Collecting for runlevel " << setw(12) << SharedGlobals::runlevel_names[level] << "  |=" << flush;
+		cout.unsetf(ios::left);
+	}
+	cout << Process::getName() << '=' << flush;
+	if(globals->level_count[level]==globals->level_count[SharedGlobals::CREATED])
+		cout << "|  done" << endl;
+	globals->lock.unlock();
+	while(globals->level_count[level]!=globals->level_count[SharedGlobals::CREATED])
+		usleep(1000);
+	globals->lock.lock(ProcessID::getID());
+	globals->lock.unlock();
+}
+
+template<class T>
+void sim::manage_process() {
+	//initialize the first runlevel
+	globals->lock.lock(T::getID());
+	globals->level_count[SharedGlobals::CONSTRUCTING]++;
+	cout << setw(35) << T::getClassName() << ":  ProcessID::getID()=" << T::getID() << "   pid=" << getpid() << endl;
+	T t;
+	ASSERT(T::getID()==ProcessID::getID(),"Process ID set incorrectly!");
+	globals->lock.unlock();
+	while(globals->level_count[SharedGlobals::CONSTRUCTING]!=globals->level_count[SharedGlobals::CREATED])
+		usleep(500);
+	globals->lock.lock(ProcessID::getID());
+	globals->lock.unlock();
+
+	//now just walk through each of the other steps
+	wait_runlevel(SharedGlobals::STARTING);
+	t.DoStart();
+	wait_runlevel(SharedGlobals::RUNNING);
+	t.run(); //should return if/when SharedGlobals::shutdown flag is set
+	wait_runlevel(SharedGlobals::STOPPING);
+	t.DoStop();
+	wait_runlevel(SharedGlobals::DESTRUCTING);
+}
+
+template<class T>
+bool sim::fork_process() {
+	RCRegion::aboutToFork(T::getID());
+	MutexLockBase::aboutToFork();
+	//increment this *before* the fork to guarantee everyone knows to wait for the new process
+	globals->level_count[SharedGlobals::CREATED]++;
+	if(fork()) {
+		manage_process<T>();
+		return true;
+	}
+	original=false;
+	return false;
+}
+
+void sim::handle_signal(int sig) {
+//	sigset_t mask_set;  /* used to set a signal masking set. */
+//	sigset_t old_set;   /* used to store the old mask set.   */
+	
+	/* reset the signal handler for next time */
+//	signal(sig, handle_signal);
+	/* mask any further signals while we're inside the handler. */
+//	sigfillset(&mask_set);
+//	sigprocmask(SIG_SETMASK, &mask_set, &old_set);
+	
+	char * name=NULL;
+	char defBuf[30];
+	switch(sig) {
+		case SIGINT: name="SIGINT"; break;
+		case SIGQUIT: name="SIGQUIT"; break;
+		case SIGBUS: name="SIGBUS"; break;
+		case SIGSEGV: name="SIGSEGV"; break;
+		case SIGTERM: name="SIGTERM"; break;
+		case SIGABRT: name="SIGABRT"; break;
+		case SIGFPE: name="SIGFPE"; break;
+		case SIGPIPE: name="SIGPIPE"; break;
+		case SIGHUP: name="SIGHUP"; break;
+		default:
+    		name=defBuf;
+    		snprintf(name,30,"signal %d",sig);
+    		break;
+	}
+	cout << "*** ERROR " << Process::getName() << ": Received " << name << endl;
+
+	static bool firstCall=true;
+	if(!firstCall) {
+		cerr << "Signal handler was recursively called, may be leaked IPC resources :(" << endl;
+		cerr << "The 'ipcs' tool can be used to manually free these, if it becomes a problem. " << endl;
+		cerr << "However, simply re-running will generally reclaim the previous buffers for you." << endl;
+		exit(EXIT_FAILURE);
+		return;
+	}
+	firstCall=false;
+
+	cout << "*** ERROR " << Process::getName() << ": Engaging fault shutdown..." << endl;
+	if(globals!=NULL && !globals->hadFault()) {
+		if(!MutexLockBase::getSemaphoreManager()->hadFault())
+			globals->lock.lock(ProcessID::getID());
+		if(globals->level_count[SharedGlobals::CREATED]>0)
+			globals->level_count[SharedGlobals::CREATED]--;
+		else
+			cout << "*** ERROR " << Process::getName() << ": level_count[CREATED] underflow" << endl;
+		globals->signalShutdown();
+		if(!MutexLockBase::getSemaphoreManager()->hadFault())
+			globals->lock.unlock();
+		globals->faultShutdown();
+	}
+	if(MutexLockBase::getSemaphoreManager()!=NULL && !MutexLockBase::getSemaphoreManager()->hadFault()) {
+		cout << "*** ERROR " << Process::getName() << ": Dereferencing mutex SemaphoreManager" << endl;
+		MutexLockBase::setSemaphoreManager(NULL); //reset to preallocated instance
+		MutexLockBase::getSemaphoreManager()->faultShutdown();
+	}
+	cout << "*** ERROR " << Process::getName() << ": Dereferencing shared memory regions" << endl;
+	RCRegion::faultShutdown();
+	cout << "*** ERROR " << Process::getName() << ": Exiting..." << endl;
+	exit(EXIT_FAILURE);
+}
+
+void sim::handle_exit() {
+	static bool firstCall=true;
+	if(!firstCall) {
+		cerr << "handle_exit was recursively called" << endl;
+		return;
+	}
+	firstCall=false;
+	cout << Process::getName() << ": Exiting..." << endl;
+	if(RCRegion::NumberOfAttach()==0) {
+		if(original)
+			cout << "Clean shutdown complete.  Have a nice day." << endl;
+		return;
+	}
+	cout << "*** ERROR " << Process::getName() << ": Exit with attached memory regions" << endl;
+	cout << "*** ERROR " << Process::getName() << ": Engaging fault shutdown..." << endl;
+	if(globals!=NULL && !globals->hadFault()) {
+		if(!MutexLockBase::getSemaphoreManager()->hadFault())
+			globals->lock.lock(ProcessID::getID());
+		if(globals->level_count[SharedGlobals::CREATED]>0)
+			globals->level_count[SharedGlobals::CREATED]--;
+		else
+			cout << "*** ERROR " << Process::getName() << ": level_count[CREATED] underflow" << endl;
+		globals->signalShutdown();
+		if(!MutexLockBase::getSemaphoreManager()->hadFault())
+			globals->lock.unlock();
+		globals->faultShutdown();
+	} else {
+		cerr << "*** ERROR " << Process::getName() << ": exit with previous global fault" << endl;
+	}
+	if(MutexLockBase::getSemaphoreManager()!=NULL && !MutexLockBase::getSemaphoreManager()->hadFault()) {
+		cout << "*** ERROR " << Process::getName() << ": Dereferencing mutex SemaphoreManager" << endl;
+		MutexLockBase::setSemaphoreManager(NULL); //reset to preallocated instance
+		MutexLockBase::getSemaphoreManager()->faultShutdown();
+	} else {
+		cerr << "*** ERROR " << Process::getName() << ": exit with previous mutex fault" << endl;
+	}
+	cout << "*** ERROR " << Process::getName() << ": Dereferencing shared memory regions" << endl;
+	RCRegion::faultShutdown();
+	cout << "*** ERROR " << Process::getName() << ": Exiting..." << endl;
+}
+
+unsigned int sim::measure_usleep_cost() {
+	usleep(5000); //to hopefully clear out the scheduler for the duration of our test
+	const unsigned int TRIALS=50;
+	TimeET mintime(1.0); //should definitely be less than a second
+	for(unsigned int i=0; i<TRIALS; i++) {
+		//measure usleep (plus overhead)
+		TimeET cur;
+		usleep(0);
+		TimeET elapsed(cur.Age());
+		if(elapsed<mintime)
+			mintime=elapsed;
+	}
+	usleep(5000); //to hopefully clear out the scheduler for the duration of our test
+	TimeET minover(1.0); //should definitely be less than a second
+	for(unsigned int i=0; i<TRIALS; i++) {
+		//measure overhead
+		TimeET cur;
+		TimeET elapsed(cur.Age());
+		if(elapsed<minover)
+			minover=elapsed;
+	}
+	//subtract overhead
+	mintime-=minover;
+	cout << "usleep granularity is " << mintime.Value()*1.0e6 << "us" << endl;
+	return static_cast<unsigned>(mintime.Value()*1.0e6);
+}
diff -urdN ../Tekkotsu_2.3/local/sim/sim.h ./local/sim/sim.h
--- ../Tekkotsu_2.3/local/sim/sim.h	Wed Dec 31 19:00:00 1969
+++ ./local/sim/sim.h	Mon Aug  1 19:18:00 2005
@@ -0,0 +1,71 @@
+//-*-c++-*-
+#ifndef INCLUDED_sim_h_
+#define INCLUDED_sim_h_
+
+#include "Events/EventTranslator.h"
+#include "IPC/MessageQueue.h"
+#include "SharedGlobals.h"
+#include "IPC/SharedObject.h"
+#include "IPC/Thread.h"
+#include "Wireless/Wireless.h"
+#include <vector>
+class SimConfig;
+
+class sim {
+public:
+	sim();
+	bool processCommandLine(int argc, const char* argv[]);
+	bool run();
+	~sim();
+	
+	typedef MessageQueue<50> EventQueue_t;
+	typedef MessageQueue<50> MotionCommandQueue_t;
+	typedef MessageQueue<50> SoundPlayQueue_t;
+	typedef MessageQueue<1> CameraQueue_t;
+	typedef MessageQueue<1> SensorQueue_t;
+	
+	static SimConfig config;
+	static std::vector<std::string> assignments;
+	
+protected:
+	unsigned int measure_usleep_cost();
+	void wait_runlevel(SharedGlobals::runlevel_t level);
+	template<class T> void manage_process();
+	template<class T> bool fork_process();
+
+	static unsigned int sim_get_time() { return globals?globals->get_time():0; }
+	
+	static void handle_signal(int sig);
+	static void handle_exit();
+
+	SharedObject<SemaphoreManager> mutexSemMgr;
+	SharedObject<SharedGlobals> glob;
+	SharedObject<ipc_setup_t> subj;
+	static bool original;
+	static const char * const usage;
+};
+
+class WirelessThread : public Thread {
+public:
+	virtual unsigned int runloop() {
+		// initial setup done by wireless's own constructor
+		wireless->pollTest(NULL); // by passing NULL, we wait indefinitely, so no need to usleep in the Thread code
+		wireless->pollProcess();
+		wireless->pollSetup(); // reinitialize for next test
+		return 0; //no sleep time because pollTest blocks
+	}
+};
+
+
+/*! @file
+ * @brief 
+ * @author ejt (Creator)
+ *
+ * $Author: ejt $
+ * $Name: tekkotsu-2_4 $
+ * $Revision: 1.5 $
+ * $State: Exp $
+ * $Date: 2005/08/01 23:18:00 $
+ */
+
+#endif
diff -urdN ../Tekkotsu_2.3/project/CVS/Entries ./project/CVS/Entries
--- ../Tekkotsu_2.3/project/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,17 @@
+/Environment.conf/1.11/Tue Jul 26 03:09:20 2005//Ttekkotsu-2_4
+/Makefile/1.105/Wed Jul  6 22:53:29 2005//Ttekkotsu-2_4
+/StartupBehavior.cc/1.69/Fri Jun 10 17:26:04 2005//Ttekkotsu-2_4
+/StartupBehavior.h/1.13/Wed Jun  1 05:48:07 2005//Ttekkotsu-2_4
+/StartupBehavior_SetupBackgroundBehaviors.cc/1.18/Wed Jun  1 05:48:07 2005//Ttekkotsu-2_4
+/StartupBehavior_SetupFileAccess.cc/1.7/Mon Jun  6 23:05:59 2005//Ttekkotsu-2_4
+/StartupBehavior_SetupModeSwitch.cc/1.45/Tue Aug  9 23:15:47 2005//Ttekkotsu-2_4
+/StartupBehavior_SetupStatusReports.cc/1.4/Wed Jan 12 22:37:26 2005//Ttekkotsu-2_4
+/StartupBehavior_SetupTekkotsuMon.cc/1.21/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/StartupBehavior_SetupVision.cc/1.23/Sun Jul 10 20:03:11 2005//Ttekkotsu-2_4
+/StartupBehavior_SetupWalkEdit.cc/1.8/Fri May 14 07:18:19 2004//Ttekkotsu-2_4
+/entry.h/1.1/Sat Mar  1 20:53:46 2003//Ttekkotsu-2_4
+D/Make.xcodeproj////
+D/aperios////
+D/local////
+D/ms////
+D/templates////
diff -urdN ../Tekkotsu_2.3/project/CVS/Repository ./project/CVS/Repository
--- ../Tekkotsu_2.3/project/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/CVS/Repository	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Tekkotsu/project
diff -urdN ../Tekkotsu_2.3/project/CVS/Root ./project/CVS/Root
--- ../Tekkotsu_2.3/project/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/CVS/Root	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/CVS/Tag ./project/CVS/Tag
--- ../Tekkotsu_2.3/project/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/CVS/Tag	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/Environment.conf ./project/Environment.conf
--- ../Tekkotsu_2.3/project/Environment.conf	Tue Nov 30 16:13:16 2004
+++ ./project/Environment.conf	Mon Jul 25 23:09:20 2005
@@ -1,17 +1,23 @@
 ############  ENVIRONMENT VARIABLES  ##############
-############# $Name: tekkotsu-2_3 $ ###############
-############### $Revision: 1.7 $ #################
-########## $Date: 2004/11/30 21:13:16 $ ###########
-# If you need to modify these, you should set them as environment
-# variables instead of changing them here - that way other tools (such
-# as mntmem and crashDebug) can use these as well.
+############# $Name: tekkotsu-2_4 $ ###############
+############### $Revision: 1.11 $ #################
+########## $Date: 2005/07/26 03:09:20 $ ###########
+# These variables will control portions of the build process.
+# For further configuration, see ms/config/tekkotsu.cfg, which
+# specifies run-time configuration.
 
 # Directory the Tekkotsu framework is stored
 TEKKOTSU_ROOT ?= /usr/local/Tekkotsu
 
 # Location where the memstick will be mounted
 # If you're using cygwin, you probably want something like
-# '/cygdrive/e' instead. 
+# '/cygdrive/e' instead.
+# Mac OS users would want to use something like '/Volumes/xxx',
+# where 'xxx' is the name of the memory stick, often initially
+# 'Unlabeled' or 'Untitled'
+# You may wish to override this as an environment variable
+# instead of changing it here, as the former will allow you to run
+# tools/mntmem and tools/umntmem manually.
 MEMSTICK_ROOT ?= /mnt/memstick
 
 # Directory where the OPEN-R SDK was installed
@@ -19,16 +25,6 @@
 # or the OPEN-R website: http://openr.aibo.com/
 OPENRSDK_ROOT ?= /usr/local/OPEN_R_SDK
 
-# in case your memory stick drivers use uppercase, you'll need to
-# set 'FILENAME_CASE' to 'upper'
-FILENAME_CASE ?= lower
-
-# this will delete files from the memory stick that aren't also in
-# your build image - except files at the root level of the memstick,
-# like memstick.ind
-# default: OFF (empty string) - any non-empty string is ON
-STRICT_MEMSTICK_IMAGE ?=
-
 # What model are you targeting?  This will look at the
 # $TEKKOTSU_ROOT/TARGET_MODEL file to find out.  If the file is not
 # found, it is created with the default setting TGT_ERS2xx.  change
@@ -46,11 +42,32 @@
 # environment.  Note that non-Aperios implies no OPEN-R headers.
 TEKKOTSU_TARGET_PLATFORM ?= PLATFORM_APERIOS
 
+# This will trigger the project's Makefile to always attempt to make
+# the framework as well.  This is useful if you are hacking the
+# framework itself, and thus want any changes made there to be 
+# compiled automatically.
+# default: ON (non-empty string) - any non-empty string is ON
+TEKKOTSU_ALWAYS_BUILD ?= true
+
+# in case your memory stick drivers use uppercase, you'll need to
+# set 'FILENAME_CASE' to 'upper'
+FILENAME_CASE ?= lower
+
+# this will delete files from the memory stick that aren't also in
+# your build image - except files at the root level of the memstick,
+# like memstick.ind
+# default: OFF (empty string) - any non-empty string is ON
+STRICT_MEMSTICK_IMAGE ?=
+
+# This will control the debug flags such as -g and -DDEBUG
+TEKKOTSU_DEBUG ?= ON
+
 # This can be nice if you want to use 'more' to page through errors
-# if they occur.  Otherwise, try using 'cat' instead.
-# The default value below uses 'more', except on Mac OS X which uses 'cat'
-# since 'more' on OS X doesn't handle the console colors.
-TEKKOTSU_LOGVIEW ?= $(if $(findstring Darwin,$(shell uname)),cat,more)
+# if they occur.  Otherwise, try using 'cat' instead.  Cygwin users
+# may need to explicitly install the 'more' package
+# This default value will test for the availability of 'more', and
+# fall back to using 'cat'.
+TEKKOTSU_LOGVIEW ?= ( if which more > /dev/null ; then more $(if $(findstring Darwin,$(shell uname)),-R); else cat ; fi )
 
 # These control the location that the temporary object files will
 # be stored.
@@ -65,17 +82,18 @@
 
 ##########  TOOL SELECTION VARIABLES  #############
 # You probably don't really want to edit these unless you've
-# got something better in mind.
+# got an "interesting" system configuration
 ifeq ($(TEKKOTSU_TARGET_PLATFORM),PLATFORM_APERIOS)
   CC=$(OPENRSDK_ROOT)/bin/mipsel-linux-gcc
   CXX=$(OPENRSDK_ROOT)/bin/mipsel-linux-g++
   LD=$(OPENRSDK_ROOT)/bin/mipsel-linux-ld
   STRIP=$(OPENRSDK_ROOT)/bin/mipsel-linux-strip
   MKBIN=$(OPENRSDK_ROOT)/OPEN_R/bin/mkbin
-  MKBINFLAGS=-p $(OPENRSDK_ROOT)
+  MKBINFLAGS=-p $(OPENRSDK_ROOT) -L$(TEKKOTSU_ROOT)/aperios/lib
   AR=$(OPENRSDK_ROOT)/bin/mipsel-linux-ar rcs
   AR2=touch
   FILTERSYSWARN=$(TEKKOTSU_ROOT)/tools/filtersyswarn/filtersyswarn $(OPEN_R_SDK)
+  STUBGEN=$(OPENRSDK_ROOT)/OPEN_R/bin/stubgen2
 else
   CC=gcc
   CXX=g++
@@ -85,15 +103,26 @@
   AR2=touch
   FILTERSYSWARN=$(TEKKOTSU_ROOT)/tools/filtersyswarn/filtersyswarn /usr/include
 endif
-STUBGEN=$(OPENRSDK_ROOT)/OPEN_R/bin/stubgen2
 COLORFILT=$(TEKKOTSU_ROOT)/tools/colorfilt
 
+# This can speed up the compilation process, but is currently only
+# supported by the 3.4 branch of gcc, or 3.3 of the gcc from Apple
+TEST_CXX_MAJOR:=$(shell $(CXX) --version | sed -n 's/^.* (GCC) \([0-9]*\)\.\([0-9]*\).*/\1/p')
+TEST_CXX_MINOR:=$(shell $(CXX) --version | sed -n 's/^.* (GCC) \([0-9]*\)\.\([0-9]*\).*/\2/p')
+TEST_CXX_APPLE:=$(findstring Apple,$(shell $(CXX) --version))
+TEKKOTSU_PCH ?= $(shell if [ $(TEST_CXX_MAJOR) -ge 4 -o $(TEST_CXX_MAJOR) -ge 3 -a \( $(TEST_CXX_MINOR) -ge 4 -o -n "$(TEST_CXX_APPLE)" \) ] ; then echo "common.h"; fi)
+
 #These will be the actual build directories used for the current target
-TGT_BD:=$(TEKKOTSU_TARGET_PLATFORM)_$(TEKKOTSU_TARGET_MODEL)
-TK_BD:=$(TEKKOTSU_BUILDDIR)/$(TGT_BD)
-PROJ_BD:=$(PROJECT_BUILDDIR)/$(TGT_BD)
+TK_LIB_BD:=$(TEKKOTSU_BUILDDIR)/$(TEKKOTSU_TARGET_PLATFORM)
+TK_BD:=$(TEKKOTSU_BUILDDIR)/$(TEKKOTSU_TARGET_PLATFORM)/$(TEKKOTSU_TARGET_MODEL)
+PROJ_BD:=$(PROJECT_BUILDDIR)/$(TEKKOTSU_TARGET_PLATFORM)/$(TEKKOTSU_TARGET_MODEL)
 $(shell mkdir -p $(TK_BD))
 
+#For debugging:
 #test:=$(shell echo "TEKKOTSU_BUILDDIR: $(TEKKOTSU_BUILDDIR)" > /dev/tty)
 #test:=$(shell echo "PROJECT_BUILDDIR: $(PROJECT_BUILDDIR)" > /dev/tty)
+#test:=$(shell echo "TEST_CXX_MAJOR: $(TEST_CXX_MAJOR)" > /dev/tty)
+#test:=$(shell echo "TEST_CXX_MINOR: $(TEST_CXX_MINOR)" > /dev/tty)
+#test:=$(shell echo "TEST_CXX_APPLE: $(TEST_CXX_APPLE)" > /dev/tty)
+#test:=$(shell echo "TEKKOTSU_PCH: $(TEKKOTSU_PCH)" > /dev/tty)
 #$(error that's all folks)
diff -urdN ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Entries ./project/Make.xcodeproj/CVS/Entries
--- ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/Make.xcodeproj/CVS/Entries	Wed Aug 10 11:03:26 2005
@@ -0,0 +1,2 @@
+/project.pbxproj/1.3/Fri Jul 29 18:36:47 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Repository ./project/Make.xcodeproj/CVS/Repository
--- ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/Make.xcodeproj/CVS/Repository	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Tekkotsu/project/Make.xcodeproj
diff -urdN ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Root ./project/Make.xcodeproj/CVS/Root
--- ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/Make.xcodeproj/CVS/Root	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Tag ./project/Make.xcodeproj/CVS/Tag
--- ../Tekkotsu_2.3/project/Make.xcodeproj/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/Make.xcodeproj/CVS/Tag	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/Make.xcodeproj/project.pbxproj ./project/Make.xcodeproj/project.pbxproj
--- ../Tekkotsu_2.3/project/Make.xcodeproj/project.pbxproj	Wed Dec 31 19:00:00 1969
+++ ./project/Make.xcodeproj/project.pbxproj	Fri Jul 29 14:36:47 2005
@@ -0,0 +1,2517 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 42;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		691C805608255F6300E8E256 /* Base64.cc in Sources */ = {isa = PBXBuildFile; fileRef = 691C805508255F6300E8E256 /* Base64.cc */; };
+		691C805708255F6300E8E256 /* Base64.cc in Sources */ = {isa = PBXBuildFile; fileRef = 691C805508255F6300E8E256 /* Base64.cc */; };
+		692CD63507F8C46B00604100 /* sim.cc in Sources */ = {isa = PBXBuildFile; fileRef = 692CD63407F8C46B00604100 /* sim.cc */; };
+		692CD63607F8C46B00604100 /* sim.cc in Sources */ = {isa = PBXBuildFile; fileRef = 692CD63407F8C46B00604100 /* sim.cc */; };
+		692CD63707F8C46B00604100 /* sim.cc in Sources */ = {isa = PBXBuildFile; fileRef = 692CD63407F8C46B00604100 /* sim.cc */; };
+		692CD99607F9F05500604100 /* LoadFileThread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 692CD99407F9F05500604100 /* LoadFileThread.cc */; };
+		692CD99707F9F05500604100 /* LoadFileThread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 692CD99407F9F05500604100 /* LoadFileThread.cc */; };
+		692CD99807F9F05500604100 /* LoadFileThread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 692CD99407F9F05500604100 /* LoadFileThread.cc */; };
+		6942757807E0DCDD003DE3D9 /* MutexLock.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6942757707E0DCDD003DE3D9 /* MutexLock.cc */; };
+		6942757907E0DCDD003DE3D9 /* MutexLock.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6942757707E0DCDD003DE3D9 /* MutexLock.cc */; };
+		6942779107E164EA003DE3D9 /* Thread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6942779007E164EA003DE3D9 /* Thread.cc */; };
+		6942779207E164EA003DE3D9 /* Thread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6942779007E164EA003DE3D9 /* Thread.cc */; };
+		694AB43707F48A860071A2AE /* libjpeg.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 694AB43507F48A860071A2AE /* libjpeg.dylib */; };
+		694AB43807F48A860071A2AE /* libpng12.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 694AB43607F48A860071A2AE /* libpng12.dylib */; };
+		694AB43907F48A860071A2AE /* libjpeg.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 694AB43507F48A860071A2AE /* libjpeg.dylib */; };
+		694AB43A07F48A860071A2AE /* libpng12.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 694AB43607F48A860071A2AE /* libpng12.dylib */; };
+		694AB43B07F48A860071A2AE /* libjpeg.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 694AB43507F48A860071A2AE /* libjpeg.dylib */; };
+		694AB43C07F48A860071A2AE /* libpng12.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 694AB43607F48A860071A2AE /* libpng12.dylib */; };
+		695967E207FF3DCF004FABFF /* LoadImageThread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 695967E007FF3DCF004FABFF /* LoadImageThread.cc */; };
+		695967E307FF3DCF004FABFF /* LoadImageThread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 695967E007FF3DCF004FABFF /* LoadImageThread.cc */; };
+		695967E407FF3DCF004FABFF /* LoadImageThread.cc in Sources */ = {isa = PBXBuildFile; fileRef = 695967E007FF3DCF004FABFF /* LoadImageThread.cc */; };
+		695F1ACA0804A81800ACB3D7 /* BufferedImageGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 695F1AC80804A81800ACB3D7 /* BufferedImageGenerator.cc */; };
+		695F1ACB0804A81800ACB3D7 /* BufferedImageGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 695F1AC80804A81800ACB3D7 /* BufferedImageGenerator.cc */; };
+		6994F3D907D4D35F003A7628 /* SemaphoreManager.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3CF07D4D35F003A7628 /* SemaphoreManager.cc */; };
+		6994F3DA07D4D35F003A7628 /* ProcessID.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3D107D4D35F003A7628 /* ProcessID.cc */; };
+		6994F3DB07D4D35F003A7628 /* RCRegion.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3D307D4D35F003A7628 /* RCRegion.cc */; };
+		6994F3DC07D4D35F003A7628 /* SharedObject.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3D607D4D35F003A7628 /* SharedObject.cc */; };
+		6994F3DD07D4D35F003A7628 /* SemaphoreManager.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3CF07D4D35F003A7628 /* SemaphoreManager.cc */; };
+		6994F3DE07D4D35F003A7628 /* ProcessID.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3D107D4D35F003A7628 /* ProcessID.cc */; };
+		6994F3DF07D4D35F003A7628 /* RCRegion.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3D307D4D35F003A7628 /* RCRegion.cc */; };
+		6994F3E007D4D35F003A7628 /* SharedObject.cc in Sources */ = {isa = PBXBuildFile; fileRef = 6994F3D607D4D35F003A7628 /* SharedObject.cc */; };
+		69970AC1083DB2760069D95C /* StewartPlatformBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69970AC0083DB2760069D95C /* StewartPlatformBehavior.cc */; };
+		69970AC2083DB2760069D95C /* StewartPlatformBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69970AC0083DB2760069D95C /* StewartPlatformBehavior.cc */; };
+		69A1995F080ED8A200540970 /* EchoBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69A1995E080ED8A200540970 /* EchoBehavior.cc */; };
+		69A19960080ED8A200540970 /* EchoBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69A1995E080ED8A200540970 /* EchoBehavior.cc */; };
+		69A323C207E3564F009D94E1 /* write_jpeg.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69A323C007E35646009D94E1 /* write_jpeg.cc */; };
+		69A323C507E35665009D94E1 /* write_jpeg.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69A323C007E35646009D94E1 /* write_jpeg.cc */; };
+		69A6D6DB07CD7C9500CB4720 /* libstdc++.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 0249A663FF388D9811CA2CEA /* libstdc++.a */; };
+		69AA7D6B0860898300185BA2 /* MessageReceiver.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69AA7D690860898300185BA2 /* MessageReceiver.cc */; };
+		69AA7D6C0860898300185BA2 /* MessageReceiver.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69AA7D690860898300185BA2 /* MessageReceiver.cc */; };
+		69B4E446089409D900832D58 /* StareAtPawBehavior2.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69B4E445089409D800832D58 /* StareAtPawBehavior2.cc */; };
+		69B4E447089409D900832D58 /* StareAtPawBehavior2.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69B4E445089409D800832D58 /* StareAtPawBehavior2.cc */; };
+		69B4E6D50895E34F00832D58 /* robot.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88407CBD6C0008493CA /* robot.cpp */; };
+		69E0A76407CBD4F9008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75907CBD4F9008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc */; };
+		69E0A76507CBD4F9008493CA /* StartupBehavior_SetupFileAccess.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75A07CBD4F9008493CA /* StartupBehavior_SetupFileAccess.cc */; };
+		69E0A76607CBD4F9008493CA /* StartupBehavior_SetupModeSwitch.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75B07CBD4F9008493CA /* StartupBehavior_SetupModeSwitch.cc */; };
+		69E0A76707CBD4F9008493CA /* StartupBehavior_SetupStatusReports.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75C07CBD4F9008493CA /* StartupBehavior_SetupStatusReports.cc */; };
+		69E0A76807CBD4F9008493CA /* StartupBehavior_SetupTekkotsuMon.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75D07CBD4F9008493CA /* StartupBehavior_SetupTekkotsuMon.cc */; };
+		69E0A76907CBD4F9008493CA /* StartupBehavior_SetupVision.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75E07CBD4F9008493CA /* StartupBehavior_SetupVision.cc */; };
+		69E0A76A07CBD4F9008493CA /* StartupBehavior_SetupWalkEdit.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75F07CBD4F9008493CA /* StartupBehavior_SetupWalkEdit.cc */; };
+		69E0A76B07CBD4F9008493CA /* StartupBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A76007CBD4F9008493CA /* StartupBehavior.cc */; };
+		69E0A77D07CBD52D008493CA /* Main.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A76F07CBD52D008493CA /* Main.cc */; };
+		69E0A77F07CBD52D008493CA /* Motion.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77107CBD52D008493CA /* Motion.cc */; };
+		69E0A78107CBD52D008493CA /* Process.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77307CBD52D008493CA /* Process.cc */; };
+		69E0A78407CBD52D008493CA /* SharedGlobals.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77607CBD52D008493CA /* SharedGlobals.cc */; };
+		69E0A78607CBD52D008493CA /* Simulator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77807CBD52D008493CA /* Simulator.cc */; };
+		69E0A78807CBD52D008493CA /* SoundPlay.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77A07CBD52D008493CA /* SoundPlay.cc */; };
+		69E0A99507CBD6C1008493CA /* BehaviorBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A78C07CBD6BF008493CA /* BehaviorBase.cc */; };
+		69E0A99807CBD6C1008493CA /* Controller.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A78F07CBD6BF008493CA /* Controller.cc */; };
+		69E0A99F07CBD6C1008493CA /* ControlBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79707CBD6BF008493CA /* ControlBase.cc */; };
+		69E0A9A207CBD6C1008493CA /* EventLogger.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79A07CBD6C0008493CA /* EventLogger.cc */; };
+		69E0A9A407CBD6C1008493CA /* FileBrowserControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79C07CBD6C0008493CA /* FileBrowserControl.cc */; };
+		69E0A9A707CBD6C1008493CA /* FreeMemReportControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79F07CBD6C0008493CA /* FreeMemReportControl.cc */; };
+		69E0A9A907CBD6C1008493CA /* HelpControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7A107CBD6C0008493CA /* HelpControl.cc */; };
+		69E0A9B207CBD6C1008493CA /* PostureEditor.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7AA07CBD6C0008493CA /* PostureEditor.cc */; };
+		69E0A9B507CBD6C1008493CA /* RebootControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7AD07CBD6C0008493CA /* RebootControl.cc */; };
+		69E0A9BA07CBD6C1008493CA /* SensorObserverControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7B207CBD6C0008493CA /* SensorObserverControl.cc */; };
+		69E0A9BC07CBD6C1008493CA /* ShutdownControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7B407CBD6C0008493CA /* ShutdownControl.cc */; };
+		69E0A9BE07CBD6C1008493CA /* StringInputControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7B607CBD6C0008493CA /* StringInputControl.cc */; };
+		69E0A9C307CBD6C1008493CA /* WalkCalibration.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7BB07CBD6C0008493CA /* WalkCalibration.cc */; };
+		69E0A9C507CBD6C1008493CA /* WaypointWalkControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7BD07CBD6C0008493CA /* WaypointWalkControl.cc */; };
+		69E0A9C807CBD6C1008493CA /* ASCIIVisionBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7C107CBD6C0008493CA /* ASCIIVisionBehavior.cc */; };
+		69E0A9CD07CBD6C1008493CA /* CameraBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7C607CBD6C0008493CA /* CameraBehavior.cc */; };
+		69E0A9CF07CBD6C1008493CA /* ChaseBallBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7C807CBD6C0008493CA /* ChaseBallBehavior.cc */; };
+		69E0A9D207CBD6C1008493CA /* DriveMeBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7CB07CBD6C0008493CA /* DriveMeBehavior.cc */; };
+		69E0A9D407CBD6C1008493CA /* ExploreMachine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7CD07CBD6C0008493CA /* ExploreMachine.cc */; };
+		69E0A9D607CBD6C1008493CA /* FlashIPAddrBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7CF07CBD6C0008493CA /* FlashIPAddrBehavior.cc */; };
+		69E0A9D807CBD6C1008493CA /* FollowHeadBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7D107CBD6C0008493CA /* FollowHeadBehavior.cc */; };
+		69E0A9E407CBD6C1008493CA /* PaceTargetsMachine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7DD07CBD6C0008493CA /* PaceTargetsMachine.cc */; };
+		69E0A9E907CBD6C1008493CA /* StareAtBallBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7E207CBD6C0008493CA /* StareAtBallBehavior.cc */; };
+		69E0A9EE07CBD6C1008493CA /* WallTestBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7E707CBD6C0008493CA /* WallTestBehavior.cc */; };
+		69E0A9F207CBD6C1008493CA /* EStopControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7EC07CBD6C0008493CA /* EStopControllerBehavior.cc */; };
+		69E0A9F407CBD6C1008493CA /* HeadPointControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7EE07CBD6C0008493CA /* HeadPointControllerBehavior.cc */; };
+		69E0A9F607CBD6C1008493CA /* MicrophoneServer.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F007CBD6C0008493CA /* MicrophoneServer.cc */; };
+		69E0A9F807CBD6C1008493CA /* RawCamBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F207CBD6C0008493CA /* RawCamBehavior.cc */; };
+		69E0A9FA07CBD6C1008493CA /* SegCamBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F407CBD6C0008493CA /* SegCamBehavior.cc */; };
+		69E0A9FC07CBD6C1008493CA /* SpeakerServer.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F607CBD6C0008493CA /* SpeakerServer.cc */; };
+		69E0A9FE07CBD6C1008493CA /* SpiderMachineBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F807CBD6C0008493CA /* SpiderMachineBehavior.cc */; };
+		69E0AA0107CBD6C2008493CA /* WalkControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7FB07CBD6C0008493CA /* WalkControllerBehavior.cc */; };
+		69E0AA0307CBD6C2008493CA /* WMMonitorBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7FD07CBD6C0008493CA /* WMMonitorBehavior.cc */; };
+		69E0AA0507CBD6C2008493CA /* WorldStateSerializerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7FF07CBD6C0008493CA /* WorldStateSerializerBehavior.cc */; };
+		69E0AA1007CBD6C2008493CA /* WalkToTargetNode.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A80B07CBD6C0008493CA /* WalkToTargetNode.cc */; };
+		69E0AA1307CBD6C2008493CA /* StateNode.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A80E07CBD6C0008493CA /* StateNode.cc */; };
+		69E0AA1507CBD6C2008493CA /* Transition.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A81007CBD6C0008493CA /* Transition.cc */; };
+		69E0AA1C07CBD6C2008493CA /* RandomTrans.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A81807CBD6C0008493CA /* RandomTrans.cc */; };
+		69E0AA2307CBD6C2008493CA /* EventBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82007CBD6C0008493CA /* EventBase.cc */; };
+		69E0AA2507CBD6C2008493CA /* EventGeneratorBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82207CBD6C0008493CA /* EventGeneratorBase.cc */; };
+		69E0AA2807CBD6C2008493CA /* EventRouter.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82507CBD6C0008493CA /* EventRouter.cc */; };
+		69E0AA2A07CBD6C2008493CA /* EventTranslator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82707CBD6C0008493CA /* EventTranslator.cc */; };
+		69E0AA2E07CBD6C2008493CA /* LocomotionEvent.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82B07CBD6C0008493CA /* LocomotionEvent.cc */; };
+		69E0AA3107CBD6C2008493CA /* TextMsgEvent.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82E07CBD6C0008493CA /* TextMsgEvent.cc */; };
+		69E0AA3307CBD6C2008493CA /* VisionObjectEvent.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83007CBD6C0008493CA /* VisionObjectEvent.cc */; };
+		69E0AA3607CBD6C2008493CA /* EmergencyStopMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83407CBD6C0008493CA /* EmergencyStopMC.cc */; };
+		69E0AA3A07CBD6C2008493CA /* HeadPointerMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83807CBD6C0008493CA /* HeadPointerMC.cc */; };
+		69E0AA3C07CBD6C2008493CA /* Kinematics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83A07CBD6C0008493CA /* Kinematics.cc */; };
+		69E0AA3E07CBD6C2008493CA /* LedEngine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83C07CBD6C0008493CA /* LedEngine.cc */; };
+		69E0AA4207CBD6C2008493CA /* MotionCommand.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84007CBD6C0008493CA /* MotionCommand.cc */; };
+		69E0AA4407CBD6C2008493CA /* MotionManager.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84207CBD6C0008493CA /* MotionManager.cc */; };
+		69E0AA4707CBD6C2008493CA /* MotionSequenceEngine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84507CBD6C0008493CA /* MotionSequenceEngine.cc */; };
+		69E0AA4A07CBD6C2008493CA /* OldHeadPointerMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84807CBD6C0008493CA /* OldHeadPointerMC.cc */; };
+		69E0AA4C07CBD6C2008493CA /* OldKinematics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84A07CBD6C0008493CA /* OldKinematics.cc */; };
+		69E0AA4E07CBD6C2008493CA /* OutputCmd.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84C07CBD6C0008493CA /* OutputCmd.cc */; };
+		69E0AA5307CBD6C2008493CA /* PostureEngine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85107CBD6C0008493CA /* PostureEngine.cc */; };
+		69E0AA5507CBD6C2008493CA /* PostureMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85307CBD6C0008493CA /* PostureMC.cc */; };
+		69E0AA5807CBD6C2008493CA /* clik.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85707CBD6C0008493CA /* clik.cpp */; };
+		69E0AA5A07CBD6C2008493CA /* comp_dq.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85907CBD6C0008493CA /* comp_dq.cpp */; };
+		69E0AA5B07CBD6C2008493CA /* comp_dqp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85A07CBD6C0008493CA /* comp_dqp.cpp */; };
+		69E0AA5C07CBD6C2008493CA /* config.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85B07CBD6C0008493CA /* config.cpp */; };
+		69E0AA5E07CBD6C2008493CA /* control_select.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85D07CBD6C0008493CA /* control_select.cpp */; };
+		69E0AA6007CBD6C2008493CA /* controller.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85F07CBD6C0008493CA /* controller.cpp */; };
+		69E0AA6207CBD6C2008493CA /* delta_t.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A86107CBD6C0008493CA /* delta_t.cpp */; };
+		69E0AA6307CBD6C2008493CA /* dynamics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A86207CBD6C0008493CA /* dynamics.cpp */; };
+		69E0AA6407CBD6C2008493CA /* dynamics_sim.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A86307CBD6C0008493CA /* dynamics_sim.cpp */; };
+		69E0AA7807CBD6C2008493CA /* gnugraph.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87907CBD6C0008493CA /* gnugraph.cpp */; };
+		69E0AA7A07CBD6C2008493CA /* homogen.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87B07CBD6C0008493CA /* homogen.cpp */; };
+		69E0AA7B07CBD6C2008493CA /* invkine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87C07CBD6C0008493CA /* invkine.cpp */; };
+		69E0AA7C07CBD6C2008493CA /* kinemat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87D07CBD6C0008493CA /* kinemat.cpp */; };
+		69E0AA7E07CBD6C2008493CA /* quaternion.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87F07CBD6C0008493CA /* quaternion.cpp */; };
+		69E0AA8507CBD6C2008493CA /* sensitiv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88607CBD6C0008493CA /* sensitiv.cpp */; };
+		69E0AA8607CBD6C2008493CA /* trajectory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88707CBD6C0008493CA /* trajectory.cpp */; };
+		69E0AA8807CBD6C2008493CA /* utils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88907CBD6C0008493CA /* utils.cpp */; };
+		69E0AA8C07CBD6C2008493CA /* WalkMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88D07CBD6C0008493CA /* WalkMC.cc */; };
+		69E0AA9007CBD6C2008493CA /* Buffer.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A89207CBD6C0008493CA /* Buffer.cc */; };
+		69E0AA9307CBD6C2008493CA /* Config.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A89507CBD6C0008493CA /* Config.cc */; };
+		69E0AA9B07CBD6C2008493CA /* get_time.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A89D07CBD6C0008493CA /* get_time.cc */; };
+		69E0AADB07CBD6C2008493CA /* jpeg_mem_dest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A8DE07CBD6C1008493CA /* jpeg_mem_dest.cc */; };
+		69E0AAF507CBD6C2008493CA /* LoadSave.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A8F807CBD6C1008493CA /* LoadSave.cc */; };
+		69E0AAFA07CBD6C2008493CA /* bandmat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A8FE07CBD6C1008493CA /* bandmat.cpp */; };
+		69E0AAFC07CBD6C2008493CA /* cholesky.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A90007CBD6C1008493CA /* cholesky.cpp */; };
+		69E0AB0107CBD6C2008493CA /* evalue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A90707CBD6C1008493CA /* evalue.cpp */; };
+		69E0AB3107CBD6C2008493CA /* fft.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93807CBD6C1008493CA /* fft.cpp */; };
+		69E0AB3207CBD6C2008493CA /* hholder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93907CBD6C1008493CA /* hholder.cpp */; };
+		69E0AB3407CBD6C2008493CA /* jacobi.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93B07CBD6C1008493CA /* jacobi.cpp */; };
+		69E0AB3607CBD6C2008493CA /* myexcept.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93D07CBD6C1008493CA /* myexcept.cpp */; };
+		69E0AB3807CBD6C2008493CA /* newfft.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93F07CBD6C1008493CA /* newfft.cpp */; };
+		69E0AB3A07CBD6C2008493CA /* newmat1.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94107CBD6C1008493CA /* newmat1.cpp */; };
+		69E0AB3B07CBD6C2008493CA /* newmat2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94207CBD6C1008493CA /* newmat2.cpp */; };
+		69E0AB3C07CBD6C2008493CA /* newmat3.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94307CBD6C1008493CA /* newmat3.cpp */; };
+		69E0AB3D07CBD6C2008493CA /* newmat4.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94407CBD6C1008493CA /* newmat4.cpp */; };
+		69E0AB3E07CBD6C2008493CA /* newmat5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94507CBD6C1008493CA /* newmat5.cpp */; };
+		69E0AB3F07CBD6C2008493CA /* newmat6.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94607CBD6C1008493CA /* newmat6.cpp */; };
+		69E0AB4007CBD6C2008493CA /* newmat7.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94707CBD6C1008493CA /* newmat7.cpp */; };
+		69E0AB4107CBD6C2008493CA /* newmat8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94807CBD6C1008493CA /* newmat8.cpp */; };
+		69E0AB4207CBD6C2008493CA /* newmat9.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94907CBD6C1008493CA /* newmat9.cpp */; };
+		69E0AB4407CBD6C2008493CA /* newmatex.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94B07CBD6C1008493CA /* newmatex.cpp */; };
+		69E0AB4607CBD6C2008493CA /* newmatnl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94D07CBD6C1008493CA /* newmatnl.cpp */; };
+		69E0AB4907CBD6C2008493CA /* newmatrm.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95007CBD6C1008493CA /* newmatrm.cpp */; };
+		69E0AB4D07CBD6C2008493CA /* sort.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95407CBD6C1008493CA /* sort.cpp */; };
+		69E0AB4E07CBD6C2008493CA /* submat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95507CBD6C1008493CA /* submat.cpp */; };
+		69E0AB4F07CBD6C2008493CA /* svd.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95607CBD6C1008493CA /* svd.cpp */; };
+		69E0AB5307CBD6C2008493CA /* Profiler.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95A07CBD6C1008493CA /* Profiler.cc */; };
+		69E0AB5507CBD6C2008493CA /* ProjectInterface.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95C07CBD6C1008493CA /* ProjectInterface.cc */; };
+		69E0AB5E07CBD6C2008493CA /* string_util.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96507CBD6C1008493CA /* string_util.cc */; };
+		69E0AB6107CBD6C2008493CA /* TimeET.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96807CBD6C1008493CA /* TimeET.cc */; };
+		69E0AB6407CBD6C2008493CA /* WMclass.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96B07CBD6C1008493CA /* WMclass.cc */; };
+		69E0AB6607CBD6C2008493CA /* WorldState.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96D07CBD6C1008493CA /* WorldState.cc */; };
+		69E0AB6807CBD6C2008493CA /* SoundManager.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97007CBD6C1008493CA /* SoundManager.cc */; };
+		69E0AB6B07CBD6C2008493CA /* WAV.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97307CBD6C1008493CA /* WAV.cc */; };
+		69E0AB6D07CBD6C2008493CA /* BallDetectionGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97607CBD6C1008493CA /* BallDetectionGenerator.cc */; };
+		69E0AB6F07CBD6C2008493CA /* CDTGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97807CBD6C1008493CA /* CDTGenerator.cc */; };
+		69E0AB7607CBD6C2008493CA /* FilterBankGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97F07CBD6C1008493CA /* FilterBankGenerator.cc */; };
+		69E0AB7807CBD6C2008493CA /* InterleavedYUVGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98107CBD6C1008493CA /* InterleavedYUVGenerator.cc */; };
+		69E0AB7A07CBD6C2008493CA /* JPEGGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98307CBD6C1008493CA /* JPEGGenerator.cc */; };
+		69E0AB7D07CBD6C2008493CA /* RawCameraGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98607CBD6C1008493CA /* RawCameraGenerator.cc */; };
+		69E0AB7F07CBD6C2008493CA /* RegionGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98807CBD6C1008493CA /* RegionGenerator.cc */; };
+		69E0AB8107CBD6C2008493CA /* RLEGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98A07CBD6C1008493CA /* RLEGenerator.cc */; };
+		69E0AB8307CBD6C2008493CA /* SegmentedColorGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98C07CBD6C1008493CA /* SegmentedColorGenerator.cc */; };
+		69E0AB8707CBD6C2008493CA /* Socket.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A99107CBD6C1008493CA /* Socket.cc */; };
+		69E0AB8907CBD6C2008493CA /* Wireless.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A99307CBD6C1008493CA /* Wireless.cc */; };
+		69E0AB9C07CBDE11008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75907CBD4F9008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc */; };
+		69E0AB9D07CBDE11008493CA /* StartupBehavior_SetupFileAccess.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75A07CBD4F9008493CA /* StartupBehavior_SetupFileAccess.cc */; };
+		69E0AB9E07CBDE11008493CA /* StartupBehavior_SetupModeSwitch.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75B07CBD4F9008493CA /* StartupBehavior_SetupModeSwitch.cc */; };
+		69E0AB9F07CBDE11008493CA /* StartupBehavior_SetupStatusReports.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75C07CBD4F9008493CA /* StartupBehavior_SetupStatusReports.cc */; };
+		69E0ABA007CBDE11008493CA /* StartupBehavior_SetupTekkotsuMon.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75D07CBD4F9008493CA /* StartupBehavior_SetupTekkotsuMon.cc */; };
+		69E0ABA107CBDE11008493CA /* StartupBehavior_SetupVision.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75E07CBD4F9008493CA /* StartupBehavior_SetupVision.cc */; };
+		69E0ABA207CBDE11008493CA /* StartupBehavior_SetupWalkEdit.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75F07CBD4F9008493CA /* StartupBehavior_SetupWalkEdit.cc */; };
+		69E0ABA307CBDE11008493CA /* StartupBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A76007CBD4F9008493CA /* StartupBehavior.cc */; };
+		69E0ABA507CBDE11008493CA /* Main.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A76F07CBD52D008493CA /* Main.cc */; };
+		69E0ABA607CBDE11008493CA /* Motion.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77107CBD52D008493CA /* Motion.cc */; };
+		69E0ABA707CBDE11008493CA /* Process.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77307CBD52D008493CA /* Process.cc */; };
+		69E0ABA807CBDE11008493CA /* SharedGlobals.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77607CBD52D008493CA /* SharedGlobals.cc */; };
+		69E0ABA907CBDE11008493CA /* Simulator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77807CBD52D008493CA /* Simulator.cc */; };
+		69E0ABAA07CBDE11008493CA /* SoundPlay.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77A07CBD52D008493CA /* SoundPlay.cc */; };
+		69E0ABAB07CBDE11008493CA /* BehaviorBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A78C07CBD6BF008493CA /* BehaviorBase.cc */; };
+		69E0ABAC07CBDE11008493CA /* Controller.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A78F07CBD6BF008493CA /* Controller.cc */; };
+		69E0ABAD07CBDE11008493CA /* ControlBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79707CBD6BF008493CA /* ControlBase.cc */; };
+		69E0ABAE07CBDE11008493CA /* EventLogger.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79A07CBD6C0008493CA /* EventLogger.cc */; };
+		69E0ABAF07CBDE11008493CA /* FileBrowserControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79C07CBD6C0008493CA /* FileBrowserControl.cc */; };
+		69E0ABB007CBDE11008493CA /* FreeMemReportControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A79F07CBD6C0008493CA /* FreeMemReportControl.cc */; };
+		69E0ABB107CBDE11008493CA /* HelpControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7A107CBD6C0008493CA /* HelpControl.cc */; };
+		69E0ABB207CBDE11008493CA /* PostureEditor.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7AA07CBD6C0008493CA /* PostureEditor.cc */; };
+		69E0ABB307CBDE11008493CA /* RebootControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7AD07CBD6C0008493CA /* RebootControl.cc */; };
+		69E0ABB407CBDE11008493CA /* SensorObserverControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7B207CBD6C0008493CA /* SensorObserverControl.cc */; };
+		69E0ABB507CBDE11008493CA /* ShutdownControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7B407CBD6C0008493CA /* ShutdownControl.cc */; };
+		69E0ABB607CBDE11008493CA /* StringInputControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7B607CBD6C0008493CA /* StringInputControl.cc */; };
+		69E0ABB707CBDE11008493CA /* WalkCalibration.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7BB07CBD6C0008493CA /* WalkCalibration.cc */; };
+		69E0ABB807CBDE11008493CA /* WaypointWalkControl.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7BD07CBD6C0008493CA /* WaypointWalkControl.cc */; };
+		69E0ABB907CBDE11008493CA /* ASCIIVisionBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7C107CBD6C0008493CA /* ASCIIVisionBehavior.cc */; };
+		69E0ABBA07CBDE11008493CA /* CameraBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7C607CBD6C0008493CA /* CameraBehavior.cc */; };
+		69E0ABBB07CBDE11008493CA /* ChaseBallBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7C807CBD6C0008493CA /* ChaseBallBehavior.cc */; };
+		69E0ABBC07CBDE11008493CA /* DriveMeBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7CB07CBD6C0008493CA /* DriveMeBehavior.cc */; };
+		69E0ABBD07CBDE11008493CA /* ExploreMachine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7CD07CBD6C0008493CA /* ExploreMachine.cc */; };
+		69E0ABBE07CBDE11008493CA /* FlashIPAddrBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7CF07CBD6C0008493CA /* FlashIPAddrBehavior.cc */; };
+		69E0ABBF07CBDE11008493CA /* FollowHeadBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7D107CBD6C0008493CA /* FollowHeadBehavior.cc */; };
+		69E0ABC007CBDE11008493CA /* PaceTargetsMachine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7DD07CBD6C0008493CA /* PaceTargetsMachine.cc */; };
+		69E0ABC107CBDE11008493CA /* StareAtBallBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7E207CBD6C0008493CA /* StareAtBallBehavior.cc */; };
+		69E0ABC207CBDE11008493CA /* WallTestBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7E707CBD6C0008493CA /* WallTestBehavior.cc */; };
+		69E0ABC307CBDE11008493CA /* EStopControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7EC07CBD6C0008493CA /* EStopControllerBehavior.cc */; };
+		69E0ABC407CBDE11008493CA /* HeadPointControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7EE07CBD6C0008493CA /* HeadPointControllerBehavior.cc */; };
+		69E0ABC507CBDE11008493CA /* MicrophoneServer.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F007CBD6C0008493CA /* MicrophoneServer.cc */; };
+		69E0ABC607CBDE11008493CA /* RawCamBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F207CBD6C0008493CA /* RawCamBehavior.cc */; };
+		69E0ABC707CBDE11008493CA /* SegCamBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F407CBD6C0008493CA /* SegCamBehavior.cc */; };
+		69E0ABC807CBDE11008493CA /* SpeakerServer.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F607CBD6C0008493CA /* SpeakerServer.cc */; };
+		69E0ABC907CBDE11008493CA /* SpiderMachineBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7F807CBD6C0008493CA /* SpiderMachineBehavior.cc */; };
+		69E0ABCA07CBDE11008493CA /* WalkControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7FB07CBD6C0008493CA /* WalkControllerBehavior.cc */; };
+		69E0ABCB07CBDE11008493CA /* WMMonitorBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7FD07CBD6C0008493CA /* WMMonitorBehavior.cc */; };
+		69E0ABCC07CBDE11008493CA /* WorldStateSerializerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A7FF07CBD6C0008493CA /* WorldStateSerializerBehavior.cc */; };
+		69E0ABCD07CBDE11008493CA /* WalkToTargetNode.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A80B07CBD6C0008493CA /* WalkToTargetNode.cc */; };
+		69E0ABCE07CBDE11008493CA /* StateNode.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A80E07CBD6C0008493CA /* StateNode.cc */; };
+		69E0ABCF07CBDE11008493CA /* Transition.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A81007CBD6C0008493CA /* Transition.cc */; };
+		69E0ABD007CBDE11008493CA /* RandomTrans.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A81807CBD6C0008493CA /* RandomTrans.cc */; };
+		69E0ABD107CBDE11008493CA /* EventBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82007CBD6C0008493CA /* EventBase.cc */; };
+		69E0ABD207CBDE11008493CA /* EventGeneratorBase.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82207CBD6C0008493CA /* EventGeneratorBase.cc */; };
+		69E0ABD307CBDE11008493CA /* EventRouter.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82507CBD6C0008493CA /* EventRouter.cc */; };
+		69E0ABD407CBDE11008493CA /* EventTranslator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82707CBD6C0008493CA /* EventTranslator.cc */; };
+		69E0ABD507CBDE11008493CA /* LocomotionEvent.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82B07CBD6C0008493CA /* LocomotionEvent.cc */; };
+		69E0ABD607CBDE11008493CA /* TextMsgEvent.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A82E07CBD6C0008493CA /* TextMsgEvent.cc */; };
+		69E0ABD707CBDE11008493CA /* VisionObjectEvent.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83007CBD6C0008493CA /* VisionObjectEvent.cc */; };
+		69E0ABD807CBDE11008493CA /* EmergencyStopMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83407CBD6C0008493CA /* EmergencyStopMC.cc */; };
+		69E0ABD907CBDE11008493CA /* HeadPointerMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83807CBD6C0008493CA /* HeadPointerMC.cc */; };
+		69E0ABDA07CBDE11008493CA /* Kinematics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83A07CBD6C0008493CA /* Kinematics.cc */; };
+		69E0ABDB07CBDE11008493CA /* LedEngine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A83C07CBD6C0008493CA /* LedEngine.cc */; };
+		69E0ABDC07CBDE11008493CA /* MotionCommand.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84007CBD6C0008493CA /* MotionCommand.cc */; };
+		69E0ABDD07CBDE11008493CA /* MotionManager.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84207CBD6C0008493CA /* MotionManager.cc */; };
+		69E0ABDE07CBDE11008493CA /* MotionSequenceEngine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84507CBD6C0008493CA /* MotionSequenceEngine.cc */; };
+		69E0ABDF07CBDE11008493CA /* OldHeadPointerMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84807CBD6C0008493CA /* OldHeadPointerMC.cc */; };
+		69E0ABE007CBDE11008493CA /* OldKinematics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84A07CBD6C0008493CA /* OldKinematics.cc */; };
+		69E0ABE107CBDE11008493CA /* OutputCmd.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A84C07CBD6C0008493CA /* OutputCmd.cc */; };
+		69E0ABE207CBDE11008493CA /* PostureEngine.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85107CBD6C0008493CA /* PostureEngine.cc */; };
+		69E0ABE307CBDE11008493CA /* PostureMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85307CBD6C0008493CA /* PostureMC.cc */; };
+		69E0ABE407CBDE11008493CA /* clik.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85707CBD6C0008493CA /* clik.cpp */; };
+		69E0ABE507CBDE11008493CA /* comp_dq.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85907CBD6C0008493CA /* comp_dq.cpp */; };
+		69E0ABE607CBDE11008493CA /* comp_dqp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85A07CBD6C0008493CA /* comp_dqp.cpp */; };
+		69E0ABE707CBDE11008493CA /* config.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85B07CBD6C0008493CA /* config.cpp */; };
+		69E0ABE807CBDE11008493CA /* control_select.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85D07CBD6C0008493CA /* control_select.cpp */; };
+		69E0ABE907CBDE11008493CA /* controller.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A85F07CBD6C0008493CA /* controller.cpp */; };
+		69E0ABEA07CBDE11008493CA /* delta_t.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A86107CBD6C0008493CA /* delta_t.cpp */; };
+		69E0ABEB07CBDE11008493CA /* dynamics.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A86207CBD6C0008493CA /* dynamics.cpp */; };
+		69E0ABEC07CBDE11008493CA /* dynamics_sim.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A86307CBD6C0008493CA /* dynamics_sim.cpp */; };
+		69E0ABED07CBDE11008493CA /* gnugraph.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87907CBD6C0008493CA /* gnugraph.cpp */; };
+		69E0ABEE07CBDE11008493CA /* homogen.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87B07CBD6C0008493CA /* homogen.cpp */; };
+		69E0ABEF07CBDE11008493CA /* invkine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87C07CBD6C0008493CA /* invkine.cpp */; };
+		69E0ABF007CBDE11008493CA /* kinemat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87D07CBD6C0008493CA /* kinemat.cpp */; };
+		69E0ABF207CBDE11008493CA /* quaternion.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A87F07CBD6C0008493CA /* quaternion.cpp */; };
+		69E0ABF307CBDE11008493CA /* robot.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88407CBD6C0008493CA /* robot.cpp */; };
+		69E0ABF407CBDE11008493CA /* sensitiv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88607CBD6C0008493CA /* sensitiv.cpp */; };
+		69E0ABF507CBDE11008493CA /* trajectory.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88707CBD6C0008493CA /* trajectory.cpp */; };
+		69E0ABF607CBDE11008493CA /* utils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88907CBD6C0008493CA /* utils.cpp */; };
+		69E0ABF707CBDE11008493CA /* WalkMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A88D07CBD6C0008493CA /* WalkMC.cc */; };
+		69E0ABF807CBDE11008493CA /* Buffer.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A89207CBD6C0008493CA /* Buffer.cc */; };
+		69E0ABF907CBDE11008493CA /* Config.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A89507CBD6C0008493CA /* Config.cc */; };
+		69E0ABFA07CBDE11008493CA /* get_time.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A89D07CBD6C0008493CA /* get_time.cc */; };
+		69E0AC2607CBDE11008493CA /* jpeg_mem_dest.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A8DE07CBD6C1008493CA /* jpeg_mem_dest.cc */; };
+		69E0AC2B07CBDE11008493CA /* LoadSave.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A8F807CBD6C1008493CA /* LoadSave.cc */; };
+		69E0AC2C07CBDE11008493CA /* bandmat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A8FE07CBD6C1008493CA /* bandmat.cpp */; };
+		69E0AC2D07CBDE11008493CA /* cholesky.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A90007CBD6C1008493CA /* cholesky.cpp */; };
+		69E0AC2E07CBDE11008493CA /* evalue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A90707CBD6C1008493CA /* evalue.cpp */; };
+		69E0AC2F07CBDE11008493CA /* fft.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93807CBD6C1008493CA /* fft.cpp */; };
+		69E0AC3007CBDE11008493CA /* hholder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93907CBD6C1008493CA /* hholder.cpp */; };
+		69E0AC3107CBDE11008493CA /* jacobi.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93B07CBD6C1008493CA /* jacobi.cpp */; };
+		69E0AC3307CBDE11008493CA /* myexcept.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93D07CBD6C1008493CA /* myexcept.cpp */; };
+		69E0AC3407CBDE11008493CA /* newfft.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A93F07CBD6C1008493CA /* newfft.cpp */; };
+		69E0AC3507CBDE11008493CA /* newmat1.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94107CBD6C1008493CA /* newmat1.cpp */; };
+		69E0AC3607CBDE11008493CA /* newmat2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94207CBD6C1008493CA /* newmat2.cpp */; };
+		69E0AC3707CBDE11008493CA /* newmat3.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94307CBD6C1008493CA /* newmat3.cpp */; };
+		69E0AC3807CBDE11008493CA /* newmat4.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94407CBD6C1008493CA /* newmat4.cpp */; };
+		69E0AC3907CBDE11008493CA /* newmat5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94507CBD6C1008493CA /* newmat5.cpp */; };
+		69E0AC3A07CBDE11008493CA /* newmat6.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94607CBD6C1008493CA /* newmat6.cpp */; };
+		69E0AC3B07CBDE11008493CA /* newmat7.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94707CBD6C1008493CA /* newmat7.cpp */; };
+		69E0AC3C07CBDE11008493CA /* newmat8.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94807CBD6C1008493CA /* newmat8.cpp */; };
+		69E0AC3D07CBDE11008493CA /* newmat9.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94907CBD6C1008493CA /* newmat9.cpp */; };
+		69E0AC3E07CBDE11008493CA /* newmatex.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94B07CBD6C1008493CA /* newmatex.cpp */; };
+		69E0AC3F07CBDE11008493CA /* newmatnl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A94D07CBD6C1008493CA /* newmatnl.cpp */; };
+		69E0AC4007CBDE11008493CA /* newmatrm.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95007CBD6C1008493CA /* newmatrm.cpp */; };
+		69E0AC4107CBDE11008493CA /* sort.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95407CBD6C1008493CA /* sort.cpp */; };
+		69E0AC4207CBDE11008493CA /* submat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95507CBD6C1008493CA /* submat.cpp */; };
+		69E0AC4307CBDE11008493CA /* svd.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95607CBD6C1008493CA /* svd.cpp */; };
+		69E0AC4507CBDE11008493CA /* Profiler.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95A07CBD6C1008493CA /* Profiler.cc */; };
+		69E0AC4607CBDE11008493CA /* ProjectInterface.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A95C07CBD6C1008493CA /* ProjectInterface.cc */; };
+		69E0AC4907CBDE11008493CA /* string_util.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96507CBD6C1008493CA /* string_util.cc */; };
+		69E0AC4A07CBDE11008493CA /* TimeET.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96807CBD6C1008493CA /* TimeET.cc */; };
+		69E0AC4B07CBDE11008493CA /* WMclass.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96B07CBD6C1008493CA /* WMclass.cc */; };
+		69E0AC4C07CBDE11008493CA /* WorldState.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A96D07CBD6C1008493CA /* WorldState.cc */; };
+		69E0AC4D07CBDE11008493CA /* SoundManager.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97007CBD6C1008493CA /* SoundManager.cc */; };
+		69E0AC4E07CBDE11008493CA /* WAV.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97307CBD6C1008493CA /* WAV.cc */; };
+		69E0AC4F07CBDE11008493CA /* BallDetectionGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97607CBD6C1008493CA /* BallDetectionGenerator.cc */; };
+		69E0AC5007CBDE11008493CA /* CDTGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97807CBD6C1008493CA /* CDTGenerator.cc */; };
+		69E0AC5107CBDE11008493CA /* FilterBankGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A97F07CBD6C1008493CA /* FilterBankGenerator.cc */; };
+		69E0AC5207CBDE11008493CA /* InterleavedYUVGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98107CBD6C1008493CA /* InterleavedYUVGenerator.cc */; };
+		69E0AC5307CBDE11008493CA /* JPEGGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98307CBD6C1008493CA /* JPEGGenerator.cc */; };
+		69E0AC5407CBDE11008493CA /* RawCameraGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98607CBD6C1008493CA /* RawCameraGenerator.cc */; };
+		69E0AC5507CBDE11008493CA /* RegionGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98807CBD6C1008493CA /* RegionGenerator.cc */; };
+		69E0AC5607CBDE11008493CA /* RLEGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98A07CBD6C1008493CA /* RLEGenerator.cc */; };
+		69E0AC5707CBDE11008493CA /* SegmentedColorGenerator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A98C07CBD6C1008493CA /* SegmentedColorGenerator.cc */; };
+		69E0AC5807CBDE11008493CA /* Socket.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A99107CBD6C1008493CA /* Socket.cc */; };
+		69E0AC5907CBDE11008493CA /* Wireless.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A99307CBD6C1008493CA /* Wireless.cc */; };
+		69E0AC5B07CBDE11008493CA /* libstdc++.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 0249A663FF388D9811CA2CEA /* libstdc++.a */; };
+		69E0AFAA07CBF84A008493CA /* StartupBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A76007CBD4F9008493CA /* StartupBehavior.cc */; };
+		69E0AFAB07CBF84B008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75907CBD4F9008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc */; };
+		69E0AFAC07CBF84C008493CA /* StartupBehavior_SetupFileAccess.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75A07CBD4F9008493CA /* StartupBehavior_SetupFileAccess.cc */; };
+		69E0AFAD07CBF84D008493CA /* StartupBehavior_SetupModeSwitch.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75B07CBD4F9008493CA /* StartupBehavior_SetupModeSwitch.cc */; };
+		69E0AFAE07CBF84E008493CA /* StartupBehavior_SetupStatusReports.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75C07CBD4F9008493CA /* StartupBehavior_SetupStatusReports.cc */; };
+		69E0AFAF07CBF84E008493CA /* StartupBehavior_SetupTekkotsuMon.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75D07CBD4F9008493CA /* StartupBehavior_SetupTekkotsuMon.cc */; };
+		69E0AFB007CBF84F008493CA /* StartupBehavior_SetupVision.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75E07CBD4F9008493CA /* StartupBehavior_SetupVision.cc */; };
+		69E0AFB107CBF850008493CA /* StartupBehavior_SetupWalkEdit.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A75F07CBD4F9008493CA /* StartupBehavior_SetupWalkEdit.cc */; };
+		69E0AFB307CBF85E008493CA /* Main.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A76F07CBD52D008493CA /* Main.cc */; };
+		69E0AFB407CBF85F008493CA /* Motion.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77107CBD52D008493CA /* Motion.cc */; };
+		69E0AFB507CBF860008493CA /* Process.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77307CBD52D008493CA /* Process.cc */; };
+		69E0AFB607CBF862008493CA /* SharedGlobals.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77607CBD52D008493CA /* SharedGlobals.cc */; };
+		69E0AFB707CBF862008493CA /* Simulator.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77807CBD52D008493CA /* Simulator.cc */; };
+		69E0AFB807CBF863008493CA /* SoundPlay.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E0A77A07CBD52D008493CA /* SoundPlay.cc */; };
+		69E0AFB907CBF881008493CA /* libtekkotsu.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 69E0ADC407CBF382008493CA /* libtekkotsu.a */; };
+		69E0AFBA07CBF881008493CA /* libroboop.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 69E0ADB607CBF0AB008493CA /* libroboop.a */; };
+		69E0AFBB07CBF881008493CA /* libnewmat.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 69E0ADBD07CBF0F8008493CA /* libnewmat.a */; };
+		69E666BC07F0CE51005F4FA9 /* plist.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E666BB07F0CE51005F4FA9 /* plist.cc */; };
+		69E666BD07F0CE51005F4FA9 /* plist.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E666BB07F0CE51005F4FA9 /* plist.cc */; };
+		69E6674907F1E23A005F4FA9 /* XMLLoadSave.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E6674707F1E23A005F4FA9 /* XMLLoadSave.cc */; };
+		69E6674A07F1E23A005F4FA9 /* XMLLoadSave.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E6674707F1E23A005F4FA9 /* XMLLoadSave.cc */; };
+		69E6696507F3398F005F4FA9 /* SimConfig.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E6696307F3398F005F4FA9 /* SimConfig.cc */; };
+		69E6696607F3398F005F4FA9 /* SimConfig.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69E6696307F3398F005F4FA9 /* SimConfig.cc */; };
+		69EA8B9507EB57480047DA8D /* libiconv.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9207EB57480047DA8D /* libiconv.dylib */; };
+		69EA8B9607EB57480047DA8D /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9307EB57480047DA8D /* libxml2.dylib */; };
+		69EA8B9707EB57480047DA8D /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9407EB57480047DA8D /* libz.dylib */; };
+		69EA8B9807EB57480047DA8D /* libiconv.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9207EB57480047DA8D /* libiconv.dylib */; };
+		69EA8B9907EB57480047DA8D /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9307EB57480047DA8D /* libxml2.dylib */; };
+		69EA8B9A07EB57480047DA8D /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9407EB57480047DA8D /* libz.dylib */; };
+		69EA8B9B07EB57480047DA8D /* libiconv.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9207EB57480047DA8D /* libiconv.dylib */; };
+		69EA8B9C07EB57480047DA8D /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9307EB57480047DA8D /* libxml2.dylib */; };
+		69EA8B9D07EB57480047DA8D /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 69EA8B9407EB57480047DA8D /* libz.dylib */; };
+		69FA48F7084C389E0003A261 /* UPennWalkMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA48F5084C389D0003A261 /* UPennWalkMC.cc */; };
+		69FA48F8084C389E0003A261 /* UPennWalkMC.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA48F5084C389D0003A261 /* UPennWalkMC.cc */; };
+		69FA48FD084C38E80003A261 /* Graphics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA48F9084C38E80003A261 /* Graphics.cc */; };
+		69FA48FE084C38E80003A261 /* RLEGraphics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA48FB084C38E80003A261 /* RLEGraphics.cc */; };
+		69FA48FF084C38E80003A261 /* Graphics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA48F9084C38E80003A261 /* Graphics.cc */; };
+		69FA4900084C38E80003A261 /* RLEGraphics.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA48FB084C38E80003A261 /* RLEGraphics.cc */; };
+		69FA4903084C39230003A261 /* UPennWalkControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA4901084C39230003A261 /* UPennWalkControllerBehavior.cc */; };
+		69FA4904084C39230003A261 /* UPennWalkControllerBehavior.cc in Sources */ = {isa = PBXBuildFile; fileRef = 69FA4901084C39230003A261 /* UPennWalkControllerBehavior.cc */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXBuildStyle section */
+		014CEA460018CE2711CA2923 /* Development */ = {
+			isa = PBXBuildStyle;
+			buildSettings = {
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					PLATFORM_LOCAL,
+					DEBUG,
+					HAVE_READDIR_R,
+				);
+				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
+				GCC_WARN_CHECK_SWITCH_STATEMENTS = YES;
+				GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES;
+				GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
+				GCC_WARN_MISSING_PARENTHESES = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_SHADOW = NO;
+				GCC_WARN_SIGN_COMPARE = YES;
+				GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_LABEL = YES;
+				GCC_WARN_UNUSED_PARAMETER = YES;
+				GCC_WARN_UNUSED_VALUE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				GENERATE_PROFILING_CODE = YES;
+				HEADER_SEARCH_PATHS = (
+					"$(TEKKOTSU_ROOT)",
+					/usr/include/libxml2,
+				);
+				OBJROOT = build;
+				PREBINDING = NO;
+				SYMROOT = "";
+				WARNING_CFLAGS = (
+					"-Wall",
+					"-W",
+					"-Wpointer-arith",
+					"-Wcast-qual",
+					"-Woverloaded-virtual",
+					"-Wdeprecated",
+				);
+			};
+			name = Development;
+		};
+		014CEA470018CE2711CA2923 /* Deployment */ = {
+			isa = PBXBuildStyle;
+			buildSettings = {
+				COPY_PHASE_STRIP = YES;
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = PLATFORM_LOCAL;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES;
+				HEADER_SEARCH_PATHS = "$(TEKKOTSU_ROOT)";
+				ZERO_LINK = NO;
+			};
+			name = Deployment;
+		};
+/* End PBXBuildStyle section */
+
+/* Begin PBXFileReference section */
+		0249A663FF388D9811CA2CEA /* libstdc++.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libstdc++.a"; path = "/usr/lib/libstdc++.a"; sourceTree = "<absolute>"; };
+		690564F20819531A00613A0E /* minisim.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = minisim.h; path = /Users/ejt/todo/Tekkotsu/local/minisim.h; sourceTree = "<absolute>"; };
+		691C805508255F6300E8E256 /* Base64.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Base64.cc; sourceTree = "<group>"; };
+		691C805C08255F6D00E8E256 /* Base64.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Base64.h; sourceTree = "<group>"; };
+		692CD63407F8C46B00604100 /* sim.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = sim.cc; sourceTree = "<group>"; };
+		692CD99407F9F05500604100 /* LoadFileThread.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LoadFileThread.cc; sourceTree = "<group>"; };
+		692CD99507F9F05500604100 /* LoadFileThread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LoadFileThread.h; sourceTree = "<group>"; };
+		6934224207D408E600BB3331 /* sim.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = sim.h; sourceTree = "<group>"; };
+		6942757707E0DCDD003DE3D9 /* MutexLock.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MutexLock.cc; sourceTree = "<group>"; };
+		6942779007E164EA003DE3D9 /* Thread.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Thread.cc; sourceTree = "<group>"; };
+		694AB43507F48A860071A2AE /* libjpeg.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libjpeg.dylib; path = /usr/local/lib/libjpeg.dylib; sourceTree = "<absolute>"; };
+		694AB43607F48A860071A2AE /* libpng12.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libpng12.dylib; path = /usr/local/lib/libpng12.dylib; sourceTree = "<absolute>"; };
+		6952B61A07DBFDCC00E2565F /* SemaphoreManager.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SemaphoreManager.h; sourceTree = "<group>"; };
+		695967E007FF3DCF004FABFF /* LoadImageThread.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LoadImageThread.cc; sourceTree = "<group>"; };
+		695967E107FF3DCF004FABFF /* LoadImageThread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LoadImageThread.h; sourceTree = "<group>"; };
+		695F1AC80804A81800ACB3D7 /* BufferedImageGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BufferedImageGenerator.cc; sourceTree = "<group>"; };
+		695F1AC90804A81800ACB3D7 /* BufferedImageGenerator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BufferedImageGenerator.h; sourceTree = "<group>"; };
+		696B01FB07D6906E000C1839 /* ms */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ms; sourceTree = "<group>"; };
+		69761DBB0856207A007DB073 /* AiboComm.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = AiboComm.java; sourceTree = "<group>"; };
+		69761DBC0856207A007DB073 /* Base64.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = Base64.java; sourceTree = "<group>"; };
+		69761DBD0856207A007DB073 /* ClassPathModifier.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ClassPathModifier.java; sourceTree = "<group>"; };
+		69761DBE0856207A007DB073 /* ControllerErr.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ControllerErr.java; sourceTree = "<group>"; };
+		69761DBF0856207A007DB073 /* ControllerGUI.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ControllerGUI.java; sourceTree = "<group>"; };
+		69761DC00856207A007DB073 /* ControllerListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ControllerListener.java; sourceTree = "<group>"; };
+		69761DC10856207A007DB073 /* ControllerMsg.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ControllerMsg.java; sourceTree = "<group>"; };
+		69761DC20856207A007DB073 /* DogConfig.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = DogConfig.java; sourceTree = "<group>"; };
+		69761DC30856207A007DB073 /* DogConfigFTP.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = DogConfigFTP.java; sourceTree = "<group>"; };
+		69761DC40856207A007DB073 /* EditScriptGUI.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = EditScriptGUI.java; sourceTree = "<group>"; };
+		69761DC50856207A007DB073 /* EStopButton.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = EStopButton.java; sourceTree = "<group>"; };
+		69761DC60856207A007DB073 /* EStopGUI.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = EStopGUI.java; sourceTree = "<group>"; };
+		69761DC70856207A007DB073 /* EStopListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = EStopListener.java; sourceTree = "<group>"; };
+		69761DC80856207A007DB073 /* EStopPanel.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = EStopPanel.java; sourceTree = "<group>"; };
+		69761DC90856207A007DB073 /* GraphCanvas.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = GraphCanvas.java; sourceTree = "<group>"; };
+		69761DCA0856207A007DB073 /* HeadPointGUI.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = HeadPointGUI.java; sourceTree = "<group>"; };
+		69761DCB0856207A007DB073 /* HeadPointListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = HeadPointListener.java; sourceTree = "<group>"; };
+		69761DCC0856207A007DB073 /* ImageSequenceWriterThread.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ImageSequenceWriterThread.java; sourceTree = "<group>"; };
+		69761DCD0856207A007DB073 /* JointLogger.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = JointLogger.java; sourceTree = "<group>"; };
+		69761DCE0856207A007DB073 /* JointRelay.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = JointRelay.java; sourceTree = "<group>"; };
+		69761DCF0856207A007DB073 /* JointRequestor.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = JointRequestor.java; sourceTree = "<group>"; };
+		69761DD00856207A007DB073 /* Joints.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = Joints.java; sourceTree = "<group>"; };
+		69761DD10856207A007DB073 /* JointWriter.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = JointWriter.java; sourceTree = "<group>"; };
+		69761DD20856207A007DB073 /* Listener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = Listener.java; sourceTree = "<group>"; };
+		69761DD30856207A007DB073 /* MechaController.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = MechaController.java; sourceTree = "<group>"; };
+		69761DD40856207A007DB073 /* MicrophoneClient.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = MicrophoneClient.java; sourceTree = "<group>"; };
+		69761DD50856207A007DB073 /* NetDebug.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = NetDebug.java; sourceTree = "<group>"; };
+		69761DD60856207A007DB073 /* ParamListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ParamListener.java; sourceTree = "<group>"; };
+		69761DD70856207A007DB073 /* PIDs.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = PIDs.java; sourceTree = "<group>"; };
+		69761DD80856207A007DB073 /* PointPick.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = PointPick.java; sourceTree = "<group>"; };
+		69761DD90856207A007DB073 /* PrintDuties.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = PrintDuties.java; sourceTree = "<group>"; };
+		69761DDA0856207A007DB073 /* ScriptEntry.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = ScriptEntry.java; sourceTree = "<group>"; };
+		69761DDB0856207A007DB073 /* SpeakerClient.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = SpeakerClient.java; sourceTree = "<group>"; };
+		69761DDC0856207A007DB073 /* SquareRightLayout.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = SquareRightLayout.java; sourceTree = "<group>"; };
+		69761DDD0856207A007DB073 /* TableMap.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TableMap.java; sourceTree = "<group>"; };
+		69761DDE0856207A007DB073 /* TableSorter.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TableSorter.java; sourceTree = "<group>"; };
+		69761DDF0856207A007DB073 /* TCPListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TCPListener.java; sourceTree = "<group>"; };
+		69761DE00856207A007DB073 /* TCPVisionListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TCPVisionListener.java; sourceTree = "<group>"; };
+		69761DE10856207A007DB073 /* Terminal.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = Terminal.java; sourceTree = "<group>"; };
+		69761DE20856207A007DB073 /* TestGraph.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TestGraph.java; sourceTree = "<group>"; };
+		69761DE30856207A007DB073 /* TextListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TextListener.java; sourceTree = "<group>"; };
+		69761DE40856207A007DB073 /* TextWatchableMemory.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TextWatchableMemory.java; sourceTree = "<group>"; };
+		69761DE50856207A007DB073 /* TwoParamPanel.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = TwoParamPanel.java; sourceTree = "<group>"; };
+		69761DE60856207A007DB073 /* UDPListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = UDPListener.java; sourceTree = "<group>"; };
+		69761DE70856207A007DB073 /* UDPVisionListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = UDPVisionListener.java; sourceTree = "<group>"; };
+		69761DE80856207A007DB073 /* VisionGUI.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = VisionGUI.java; sourceTree = "<group>"; };
+		69761DE90856207A007DB073 /* VisionListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = VisionListener.java; sourceTree = "<group>"; };
+		69761DEA0856207A007DB073 /* VisionPanel.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = VisionPanel.java; sourceTree = "<group>"; };
+		69761DEB0856207A007DB073 /* VisionUpdatedListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = VisionUpdatedListener.java; sourceTree = "<group>"; };
+		69761DEC0856207A007DB073 /* WalkGUI.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WalkGUI.java; sourceTree = "<group>"; };
+		69761DED0856207A007DB073 /* WatchableMemory.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WatchableMemory.java; sourceTree = "<group>"; };
+		69761DEE0856207A007DB073 /* WatchableMemoryListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WatchableMemoryListener.java; sourceTree = "<group>"; };
+		69761DEF0856207A007DB073 /* WM2DMData.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WM2DMData.java; sourceTree = "<group>"; };
+		69761DF00856207A007DB073 /* WM2DMListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WM2DMListener.java; sourceTree = "<group>"; };
+		69761DF10856207A007DB073 /* WM2FSData.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WM2FSData.java; sourceTree = "<group>"; };
+		69761DF20856207A007DB073 /* WM2FSListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WM2FSListener.java; sourceTree = "<group>"; };
+		69761DF30856207A007DB073 /* WM2HMData.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WM2HMData.java; sourceTree = "<group>"; };
+		69761DF40856207A007DB073 /* WM2HMListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WM2HMListener.java; sourceTree = "<group>"; };
+		69761DF50856207A007DB073 /* WMvar.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WMvar.java; sourceTree = "<group>"; };
+		69761DF60856207A007DB073 /* WorldModel2Conf.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WorldModel2Conf.java; sourceTree = "<group>"; };
+		69761DF70856207A007DB073 /* WorldStateJointsListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WorldStateJointsListener.java; sourceTree = "<group>"; };
+		69761DF80856207A007DB073 /* WorldStatePIDsListener.java */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.java; path = WorldStatePIDsListener.java; sourceTree = "<group>"; };
+		6985DA3408527479009FD05A /* tools */ = {isa = PBXFileReference; lastKnownFileType = folder; name = tools; path = ../tools; sourceTree = SOURCE_ROOT; };
+		6994F3CA07D4D35F003A7628 /* ListMemBuf.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ListMemBuf.h; sourceTree = "<group>"; };
+		6994F3CB07D4D35F003A7628 /* LockScope.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LockScope.h; sourceTree = "<group>"; };
+		6994F3CC07D4D35F003A7628 /* MessageQueue.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MessageQueue.h; sourceTree = "<group>"; };
+		6994F3CD07D4D35F003A7628 /* MessageReceiver.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MessageReceiver.h; sourceTree = "<group>"; };
+		6994F3CE07D4D35F003A7628 /* MutexLock.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MutexLock.h; sourceTree = "<group>"; };
+		6994F3CF07D4D35F003A7628 /* SemaphoreManager.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SemaphoreManager.cc; sourceTree = "<group>"; };
+		6994F3D107D4D35F003A7628 /* ProcessID.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ProcessID.cc; sourceTree = "<group>"; };
+		6994F3D207D4D35F003A7628 /* ProcessID.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ProcessID.h; sourceTree = "<group>"; };
+		6994F3D307D4D35F003A7628 /* RCRegion.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RCRegion.cc; sourceTree = "<group>"; };
+		6994F3D407D4D35F003A7628 /* RCRegion.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RCRegion.h; sourceTree = "<group>"; };
+		6994F3D507D4D35F003A7628 /* RegionRegistry.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RegionRegistry.h; sourceTree = "<group>"; };
+		6994F3D607D4D35F003A7628 /* SharedObject.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SharedObject.cc; sourceTree = "<group>"; };
+		6994F3D707D4D35F003A7628 /* SharedObject.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SharedObject.h; sourceTree = "<group>"; };
+		6994F56F07D68C8D003A7628 /* README */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README; sourceTree = "<group>"; };
+		6994F57D07D68D23003A7628 /* INSTALL */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = INSTALL; sourceTree = "<group>"; };
+		6994F59607D68DF6003A7628 /* Makefile.aperios */ = {isa = PBXFileReference; explicitFileType = sourcecode.make; fileEncoding = 30; path = Makefile.aperios; sourceTree = "<group>"; };
+		6994F59807D68DF6003A7628 /* MMCombo.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MMCombo.cc; sourceTree = "<group>"; };
+		6994F59907D68DF6003A7628 /* MMCombo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MMCombo.h; sourceTree = "<group>"; };
+		6994F59A07D68DF6003A7628 /* MMCombo.ocf */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = MMCombo.ocf; sourceTree = "<group>"; };
+		6994F59B07D68DF6003A7628 /* stub.cfg */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = stub.cfg; sourceTree = "<group>"; };
+		6994F59D07D68DF6003A7628 /* SndPlay.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SndPlay.cc; sourceTree = "<group>"; };
+		6994F59E07D68DF6003A7628 /* SndPlay.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = SndPlay.h; sourceTree = "<group>"; };
+		6994F59F07D68DF7003A7628 /* SoundPlay.ocf */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = SoundPlay.ocf; sourceTree = "<group>"; };
+		6994F5A007D68DF7003A7628 /* stub.cfg */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = stub.cfg; sourceTree = "<group>"; };
+		6994F5A207D68DF7003A7628 /* FtpConfig.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = FtpConfig.h; sourceTree = "<group>"; };
+		6994F5A307D68DF7003A7628 /* FtpDTP.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FtpDTP.cc; sourceTree = "<group>"; };
+		6994F5A407D68DF7003A7628 /* FtpDTP.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = FtpDTP.h; sourceTree = "<group>"; };
+		6994F5A507D68DF7003A7628 /* FtpMethod.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FtpMethod.cc; sourceTree = "<group>"; };
+		6994F5A607D68DF7003A7628 /* FtpPI.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FtpPI.cc; sourceTree = "<group>"; };
+		6994F5A707D68DF7003A7628 /* FtpPI.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = FtpPI.h; sourceTree = "<group>"; };
+		6994F5A807D68DF7003A7628 /* FtpRequest.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FtpRequest.cc; sourceTree = "<group>"; };
+		6994F5A907D68DF7003A7628 /* stub.cfg */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = stub.cfg; sourceTree = "<group>"; };
+		6994F5AA07D68DF7003A7628 /* TCPConnection.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TCPConnection.h; sourceTree = "<group>"; };
+		6994F5AB07D68DF7003A7628 /* TinyFTPD.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TinyFTPD.cc; sourceTree = "<group>"; };
+		6994F5AC07D68DF7003A7628 /* TinyFTPD.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TinyFTPD.h; sourceTree = "<group>"; };
+		6994F5AD07D68DF7003A7628 /* TinyFTPD.ocf */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = TinyFTPD.ocf; sourceTree = "<group>"; };
+		6994F5B807D68E41003A7628 /* Makefile.local */ = {isa = PBXFileReference; explicitFileType = sourcecode.make; fileEncoding = 30; name = Makefile.local; path = /Users/ejt/todo/Tekkotsu/local/Makefile.local; sourceTree = "<absolute>"; };
+		6994F5C307D68EE4003A7628 /* Makefile.local */ = {isa = PBXFileReference; explicitFileType = sourcecode.make; fileEncoding = 30; name = Makefile.local; path = local/Makefile.local; sourceTree = "<group>"; };
+		6994F5CC07D68F2A003A7628 /* Makefile.aperios */ = {isa = PBXFileReference; explicitFileType = sourcecode.make; fileEncoding = 30; languageSpecificationIdentifier = make; path = Makefile.aperios; sourceTree = "<group>"; };
+		69970AC0083DB2760069D95C /* StewartPlatformBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StewartPlatformBehavior.cc; sourceTree = "<group>"; };
+		69970AC3083DB2830069D95C /* StewartPlatformBehavior.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = StewartPlatformBehavior.h; sourceTree = "<group>"; };
+		69970AC4083DB2C60069D95C /* LogTestMachine.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = LogTestMachine.h; sourceTree = "<group>"; };
+		69970ACC083DB35B0069D95C /* TextMsgTrans.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TextMsgTrans.h; sourceTree = "<group>"; };
+		69A1995E080ED8A200540970 /* EchoBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EchoBehavior.cc; sourceTree = "<group>"; };
+		69A19963080ED8AE00540970 /* EchoBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EchoBehavior.h; sourceTree = "<group>"; };
+		69A323C007E35646009D94E1 /* write_jpeg.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = write_jpeg.cc; sourceTree = "<group>"; };
+		69A323C107E35646009D94E1 /* write_jpeg.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = write_jpeg.h; sourceTree = "<group>"; };
+		69A6D61007CD2C7700CB4720 /* sim-ERS7 */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "sim-ERS7"; sourceTree = BUILT_PRODUCTS_DIR; };
+		69AA7D690860898300185BA2 /* MessageReceiver.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MessageReceiver.cc; sourceTree = "<group>"; };
+		69B4E445089409D800832D58 /* StareAtPawBehavior2.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StareAtPawBehavior2.cc; sourceTree = "<group>"; };
+		69E0A75707CBD4F9008493CA /* SampleBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SampleBehavior.h; sourceTree = "<group>"; };
+		69E0A75807CBD4F9008493CA /* SampleMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SampleMC.h; sourceTree = "<group>"; };
+		69E0A75907CBD4F9008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior_SetupBackgroundBehaviors.cc; sourceTree = "<group>"; };
+		69E0A75A07CBD4F9008493CA /* StartupBehavior_SetupFileAccess.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior_SetupFileAccess.cc; sourceTree = "<group>"; };
+		69E0A75B07CBD4F9008493CA /* StartupBehavior_SetupModeSwitch.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior_SetupModeSwitch.cc; sourceTree = "<group>"; };
+		69E0A75C07CBD4F9008493CA /* StartupBehavior_SetupStatusReports.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior_SetupStatusReports.cc; sourceTree = "<group>"; };
+		69E0A75D07CBD4F9008493CA /* StartupBehavior_SetupTekkotsuMon.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior_SetupTekkotsuMon.cc; sourceTree = "<group>"; };
+		69E0A75E07CBD4F9008493CA /* StartupBehavior_SetupVision.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior_SetupVision.cc; sourceTree = "<group>"; };
+		69E0A75F07CBD4F9008493CA /* StartupBehavior_SetupWalkEdit.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior_SetupWalkEdit.cc; sourceTree = "<group>"; };
+		69E0A76007CBD4F9008493CA /* StartupBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StartupBehavior.cc; sourceTree = "<group>"; };
+		69E0A76107CBD4F9008493CA /* StartupBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = StartupBehavior.h; sourceTree = "<group>"; };
+		69E0A76F07CBD52D008493CA /* Main.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Main.cc; sourceTree = "<group>"; };
+		69E0A77007CBD52D008493CA /* Main.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Main.h; sourceTree = "<group>"; };
+		69E0A77107CBD52D008493CA /* Motion.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Motion.cc; sourceTree = "<group>"; };
+		69E0A77207CBD52D008493CA /* Motion.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Motion.h; sourceTree = "<group>"; };
+		69E0A77307CBD52D008493CA /* Process.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Process.cc; sourceTree = "<group>"; };
+		69E0A77407CBD52D008493CA /* Process.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Process.h; sourceTree = "<group>"; };
+		69E0A77607CBD52D008493CA /* SharedGlobals.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SharedGlobals.cc; sourceTree = "<group>"; };
+		69E0A77707CBD52D008493CA /* SharedGlobals.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SharedGlobals.h; sourceTree = "<group>"; };
+		69E0A77807CBD52D008493CA /* Simulator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Simulator.cc; sourceTree = "<group>"; };
+		69E0A77907CBD52D008493CA /* Simulator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Simulator.h; sourceTree = "<group>"; };
+		69E0A77A07CBD52D008493CA /* SoundPlay.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SoundPlay.cc; sourceTree = "<group>"; };
+		69E0A77B07CBD52D008493CA /* SoundPlay.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SoundPlay.h; sourceTree = "<group>"; };
+		69E0A78C07CBD6BF008493CA /* BehaviorBase.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BehaviorBase.cc; sourceTree = "<group>"; };
+		69E0A78D07CBD6BF008493CA /* BehaviorBase.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BehaviorBase.h; sourceTree = "<group>"; };
+		69E0A78F07CBD6BF008493CA /* Controller.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Controller.cc; sourceTree = "<group>"; };
+		69E0A79007CBD6BF008493CA /* Controller.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Controller.h; sourceTree = "<group>"; };
+		69E0A79207CBD6BF008493CA /* BatteryCheckControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BatteryCheckControl.h; sourceTree = "<group>"; };
+		69E0A79307CBD6BF008493CA /* BehaviorActivatorControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BehaviorActivatorControl.h; sourceTree = "<group>"; };
+		69E0A79407CBD6BF008493CA /* BehaviorReportControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BehaviorReportControl.h; sourceTree = "<group>"; };
+		69E0A79507CBD6BF008493CA /* BehaviorSwitchActivatorControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BehaviorSwitchActivatorControl.h; sourceTree = "<group>"; };
+		69E0A79607CBD6BF008493CA /* BehaviorSwitchControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BehaviorSwitchControl.h; sourceTree = "<group>"; };
+		69E0A79707CBD6BF008493CA /* ControlBase.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ControlBase.cc; sourceTree = "<group>"; };
+		69E0A79807CBD6BF008493CA /* ControlBase.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ControlBase.h; sourceTree = "<group>"; };
+		69E0A79907CBD6C0008493CA /* DumpFileControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = DumpFileControl.h; sourceTree = "<group>"; };
+		69E0A79A07CBD6C0008493CA /* EventLogger.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EventLogger.cc; sourceTree = "<group>"; };
+		69E0A79B07CBD6C0008493CA /* EventLogger.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventLogger.h; sourceTree = "<group>"; };
+		69E0A79C07CBD6C0008493CA /* FileBrowserControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FileBrowserControl.cc; sourceTree = "<group>"; };
+		69E0A79D07CBD6C0008493CA /* FileBrowserControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FileBrowserControl.h; sourceTree = "<group>"; };
+		69E0A79E07CBD6C0008493CA /* FileInputControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FileInputControl.h; sourceTree = "<group>"; };
+		69E0A79F07CBD6C0008493CA /* FreeMemReportControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FreeMemReportControl.cc; sourceTree = "<group>"; };
+		69E0A7A007CBD6C0008493CA /* FreeMemReportControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FreeMemReportControl.h; sourceTree = "<group>"; };
+		69E0A7A107CBD6C0008493CA /* HelpControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = HelpControl.cc; sourceTree = "<group>"; };
+		69E0A7A207CBD6C0008493CA /* HelpControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = HelpControl.h; sourceTree = "<group>"; };
+		69E0A7A307CBD6C0008493CA /* LoadCalibration.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LoadCalibration.h; sourceTree = "<group>"; };
+		69E0A7A407CBD6C0008493CA /* LoadPostureControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LoadPostureControl.h; sourceTree = "<group>"; };
+		69E0A7A507CBD6C0008493CA /* LoadWalkControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LoadWalkControl.h; sourceTree = "<group>"; };
+		69E0A7A607CBD6C0008493CA /* MCValueEditControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MCValueEditControl.h; sourceTree = "<group>"; };
+		69E0A7A707CBD6C0008493CA /* NetworkStatusControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = NetworkStatusControl.h; sourceTree = "<group>"; };
+		69E0A7A807CBD6C0008493CA /* NullControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = NullControl.h; sourceTree = "<group>"; };
+		69E0A7A907CBD6C0008493CA /* PlaySoundControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = PlaySoundControl.h; sourceTree = "<group>"; };
+		69E0A7AA07CBD6C0008493CA /* PostureEditor.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PostureEditor.cc; sourceTree = "<group>"; };
+		69E0A7AB07CBD6C0008493CA /* PostureEditor.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = PostureEditor.h; sourceTree = "<group>"; };
+		69E0A7AC07CBD6C0008493CA /* ProfilerCheckControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ProfilerCheckControl.h; sourceTree = "<group>"; };
+		69E0A7AD07CBD6C0008493CA /* RebootControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RebootControl.cc; sourceTree = "<group>"; };
+		69E0A7AE07CBD6C0008493CA /* RebootControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RebootControl.h; sourceTree = "<group>"; };
+		69E0A7AF07CBD6C0008493CA /* RunSequenceControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RunSequenceControl.h; sourceTree = "<group>"; };
+		69E0A7B007CBD6C0008493CA /* SavePostureControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SavePostureControl.h; sourceTree = "<group>"; };
+		69E0A7B107CBD6C0008493CA /* SaveWalkControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SaveWalkControl.h; sourceTree = "<group>"; };
+		69E0A7B207CBD6C0008493CA /* SensorObserverControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SensorObserverControl.cc; sourceTree = "<group>"; };
+		69E0A7B307CBD6C0008493CA /* SensorObserverControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SensorObserverControl.h; sourceTree = "<group>"; };
+		69E0A7B407CBD6C0008493CA /* ShutdownControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ShutdownControl.cc; sourceTree = "<group>"; };
+		69E0A7B507CBD6C0008493CA /* ShutdownControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ShutdownControl.h; sourceTree = "<group>"; };
+		69E0A7B607CBD6C0008493CA /* StringInputControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StringInputControl.cc; sourceTree = "<group>"; };
+		69E0A7B707CBD6C0008493CA /* StringInputControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = StringInputControl.h; sourceTree = "<group>"; };
+		69E0A7B807CBD6C0008493CA /* ToggleControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ToggleControl.h; sourceTree = "<group>"; };
+		69E0A7B907CBD6C0008493CA /* ValueEditControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ValueEditControl.h; sourceTree = "<group>"; };
+		69E0A7BA07CBD6C0008493CA /* ValueSetControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ValueSetControl.h; sourceTree = "<group>"; };
+		69E0A7BB07CBD6C0008493CA /* WalkCalibration.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WalkCalibration.cc; sourceTree = "<group>"; };
+		69E0A7BC07CBD6C0008493CA /* WalkCalibration.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WalkCalibration.h; sourceTree = "<group>"; };
+		69E0A7BD07CBD6C0008493CA /* WaypointWalkControl.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WaypointWalkControl.cc; sourceTree = "<group>"; };
+		69E0A7BE07CBD6C0008493CA /* WaypointWalkControl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WaypointWalkControl.h; sourceTree = "<group>"; };
+		69E0A7C007CBD6C0008493CA /* AlanBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = AlanBehavior.h; sourceTree = "<group>"; };
+		69E0A7C107CBD6C0008493CA /* ASCIIVisionBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ASCIIVisionBehavior.cc; sourceTree = "<group>"; };
+		69E0A7C207CBD6C0008493CA /* ASCIIVisionBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ASCIIVisionBehavior.h; sourceTree = "<group>"; };
+		69E0A7C307CBD6C0008493CA /* AutoGetupBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = AutoGetupBehavior.h; sourceTree = "<group>"; };
+		69E0A7C407CBD6C0008493CA /* BanditMachine.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BanditMachine.h; sourceTree = "<group>"; };
+		69E0A7C507CBD6C0008493CA /* BatteryMonitorBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BatteryMonitorBehavior.h; sourceTree = "<group>"; };
+		69E0A7C607CBD6C0008493CA /* CameraBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CameraBehavior.cc; sourceTree = "<group>"; };
+		69E0A7C707CBD6C0008493CA /* CameraBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = CameraBehavior.h; sourceTree = "<group>"; };
+		69E0A7C807CBD6C0008493CA /* ChaseBallBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ChaseBallBehavior.cc; sourceTree = "<group>"; };
+		69E0A7C907CBD6C0008493CA /* ChaseBallBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ChaseBallBehavior.h; sourceTree = "<group>"; };
+		69E0A7CA07CBD6C0008493CA /* CrashTestBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = CrashTestBehavior.h; sourceTree = "<group>"; };
+		69E0A7CB07CBD6C0008493CA /* DriveMeBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = DriveMeBehavior.cc; sourceTree = "<group>"; };
+		69E0A7CC07CBD6C0008493CA /* DriveMeBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = DriveMeBehavior.h; sourceTree = "<group>"; };
+		69E0A7CD07CBD6C0008493CA /* ExploreMachine.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ExploreMachine.cc; sourceTree = "<group>"; };
+		69E0A7CE07CBD6C0008493CA /* ExploreMachine.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ExploreMachine.h; sourceTree = "<group>"; };
+		69E0A7CF07CBD6C0008493CA /* FlashIPAddrBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FlashIPAddrBehavior.cc; sourceTree = "<group>"; };
+		69E0A7D007CBD6C0008493CA /* FlashIPAddrBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FlashIPAddrBehavior.h; sourceTree = "<group>"; };
+		69E0A7D107CBD6C0008493CA /* FollowHeadBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FollowHeadBehavior.cc; sourceTree = "<group>"; };
+		69E0A7D207CBD6C0008493CA /* FollowHeadBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FollowHeadBehavior.h; sourceTree = "<group>"; };
+		69E0A7D307CBD6C0008493CA /* FreezeTestBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FreezeTestBehavior.h; sourceTree = "<group>"; };
+		69E0A7D407CBD6C0008493CA /* GroundPlaneBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = GroundPlaneBehavior.h; sourceTree = "<group>"; };
+		69E0A7D507CBD6C0008493CA /* HeadLevelBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = HeadLevelBehavior.h; sourceTree = "<group>"; };
+		69E0A7D607CBD6C0008493CA /* HelloWorldBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = HelloWorldBehavior.h; sourceTree = "<group>"; };
+		69E0A7D707CBD6C0008493CA /* karmedbandit.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = karmedbandit.h; sourceTree = "<group>"; };
+		69E0A7D807CBD6C0008493CA /* KinematicSampleBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = KinematicSampleBehavior.h; sourceTree = "<group>"; };
+		69E0A7D907CBD6C0008493CA /* KinematicSampleBehavior2.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = KinematicSampleBehavior2.h; sourceTree = "<group>"; };
+		69E0A7DA07CBD6C0008493CA /* LookForSoundBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LookForSoundBehavior.h; sourceTree = "<group>"; };
+		69E0A7DB07CBD6C0008493CA /* MCRepeater.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MCRepeater.h; sourceTree = "<group>"; };
+		69E0A7DC07CBD6C0008493CA /* MotionStressTestBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MotionStressTestBehavior.h; sourceTree = "<group>"; };
+		69E0A7DD07CBD6C0008493CA /* PaceTargetsMachine.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PaceTargetsMachine.cc; sourceTree = "<group>"; };
+		69E0A7DE07CBD6C0008493CA /* PaceTargetsMachine.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = PaceTargetsMachine.h; sourceTree = "<group>"; };
+		69E0A7DF07CBD6C0008493CA /* RelaxBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RelaxBehavior.h; sourceTree = "<group>"; };
+		69E0A7E007CBD6C0008493CA /* SimpleChaseBallBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SimpleChaseBallBehavior.h; sourceTree = "<group>"; };
+		69E0A7E107CBD6C0008493CA /* SoundTestBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SoundTestBehavior.h; sourceTree = "<group>"; };
+		69E0A7E207CBD6C0008493CA /* StareAtBallBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StareAtBallBehavior.cc; sourceTree = "<group>"; };
+		69E0A7E307CBD6C0008493CA /* StareAtBallBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = StareAtBallBehavior.h; sourceTree = "<group>"; };
+		69E0A7E407CBD6C0008493CA /* StareAtPawBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = StareAtPawBehavior.h; sourceTree = "<group>"; };
+		69E0A7E507CBD6C0008493CA /* StareAtPawBehavior2.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = StareAtPawBehavior2.h; sourceTree = "<group>"; };
+		69E0A7E607CBD6C0008493CA /* ToggleHeadLightBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ToggleHeadLightBehavior.h; sourceTree = "<group>"; };
+		69E0A7E707CBD6C0008493CA /* WallTestBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WallTestBehavior.cc; sourceTree = "<group>"; };
+		69E0A7E807CBD6C0008493CA /* WallTestBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WallTestBehavior.h; sourceTree = "<group>"; };
+		69E0A7E907CBD6C0008493CA /* WorldStateVelDaemon.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WorldStateVelDaemon.h; sourceTree = "<group>"; };
+		69E0A7EB07CBD6C0008493CA /* Aibo3DControllerBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Aibo3DControllerBehavior.h; sourceTree = "<group>"; };
+		69E0A7EC07CBD6C0008493CA /* EStopControllerBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EStopControllerBehavior.cc; sourceTree = "<group>"; };
+		69E0A7ED07CBD6C0008493CA /* EStopControllerBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EStopControllerBehavior.h; sourceTree = "<group>"; };
+		69E0A7EE07CBD6C0008493CA /* HeadPointControllerBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = HeadPointControllerBehavior.cc; sourceTree = "<group>"; };
+		69E0A7EF07CBD6C0008493CA /* HeadPointControllerBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = HeadPointControllerBehavior.h; sourceTree = "<group>"; };
+		69E0A7F007CBD6C0008493CA /* MicrophoneServer.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MicrophoneServer.cc; sourceTree = "<group>"; };
+		69E0A7F107CBD6C0008493CA /* MicrophoneServer.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MicrophoneServer.h; sourceTree = "<group>"; };
+		69E0A7F207CBD6C0008493CA /* RawCamBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RawCamBehavior.cc; sourceTree = "<group>"; };
+		69E0A7F307CBD6C0008493CA /* RawCamBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RawCamBehavior.h; sourceTree = "<group>"; };
+		69E0A7F407CBD6C0008493CA /* SegCamBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SegCamBehavior.cc; sourceTree = "<group>"; };
+		69E0A7F507CBD6C0008493CA /* SegCamBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SegCamBehavior.h; sourceTree = "<group>"; };
+		69E0A7F607CBD6C0008493CA /* SpeakerServer.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SpeakerServer.cc; sourceTree = "<group>"; };
+		69E0A7F707CBD6C0008493CA /* SpeakerServer.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SpeakerServer.h; sourceTree = "<group>"; };
+		69E0A7F807CBD6C0008493CA /* SpiderMachineBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SpiderMachineBehavior.cc; sourceTree = "<group>"; };
+		69E0A7F907CBD6C0008493CA /* SpiderMachineBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SpiderMachineBehavior.h; sourceTree = "<group>"; };
+		69E0A7FA07CBD6C0008493CA /* ViewWMVarsBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ViewWMVarsBehavior.h; sourceTree = "<group>"; };
+		69E0A7FB07CBD6C0008493CA /* WalkControllerBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WalkControllerBehavior.cc; sourceTree = "<group>"; };
+		69E0A7FC07CBD6C0008493CA /* WalkControllerBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WalkControllerBehavior.h; sourceTree = "<group>"; };
+		69E0A7FD07CBD6C0008493CA /* WMMonitorBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WMMonitorBehavior.cc; sourceTree = "<group>"; };
+		69E0A7FE07CBD6C0008493CA /* WMMonitorBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WMMonitorBehavior.h; sourceTree = "<group>"; };
+		69E0A7FF07CBD6C0008493CA /* WorldStateSerializerBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WorldStateSerializerBehavior.cc; sourceTree = "<group>"; };
+		69E0A80007CBD6C0008493CA /* WorldStateSerializerBehavior.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WorldStateSerializerBehavior.h; sourceTree = "<group>"; };
+		69E0A80207CBD6C0008493CA /* GroupNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = GroupNode.h; sourceTree = "<group>"; };
+		69E0A80307CBD6C0008493CA /* HeadPointerNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = HeadPointerNode.h; sourceTree = "<group>"; };
+		69E0A80407CBD6C0008493CA /* LedNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LedNode.h; sourceTree = "<group>"; };
+		69E0A80507CBD6C0008493CA /* MotionSequenceNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MotionSequenceNode.h; sourceTree = "<group>"; };
+		69E0A80607CBD6C0008493CA /* OutputNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = OutputNode.h; sourceTree = "<group>"; };
+		69E0A80707CBD6C0008493CA /* PlayMotionSequenceNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = PlayMotionSequenceNode.h; sourceTree = "<group>"; };
+		69E0A80807CBD6C0008493CA /* SoundNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SoundNode.h; sourceTree = "<group>"; };
+		69E0A80907CBD6C0008493CA /* TailWagNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = TailWagNode.h; sourceTree = "<group>"; };
+		69E0A80A07CBD6C0008493CA /* WalkNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WalkNode.h; sourceTree = "<group>"; };
+		69E0A80B07CBD6C0008493CA /* WalkToTargetNode.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WalkToTargetNode.cc; sourceTree = "<group>"; };
+		69E0A80C07CBD6C0008493CA /* WalkToTargetNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WalkToTargetNode.h; sourceTree = "<group>"; };
+		69E0A80D07CBD6C0008493CA /* README */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = README; sourceTree = "<group>"; };
+		69E0A80E07CBD6C0008493CA /* StateNode.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = StateNode.cc; sourceTree = "<group>"; };
+		69E0A80F07CBD6C0008493CA /* StateNode.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = StateNode.h; sourceTree = "<group>"; };
+		69E0A81007CBD6C0008493CA /* Transition.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Transition.cc; sourceTree = "<group>"; };
+		69E0A81107CBD6C0008493CA /* Transition.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Transition.h; sourceTree = "<group>"; };
+		69E0A81307CBD6C0008493CA /* CompareTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = CompareTrans.h; sourceTree = "<group>"; };
+		69E0A81407CBD6C0008493CA /* CompletionTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = CompletionTrans.h; sourceTree = "<group>"; };
+		69E0A81507CBD6C0008493CA /* EventTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventTrans.h; sourceTree = "<group>"; };
+		69E0A81607CBD6C0008493CA /* LostTargetTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LostTargetTrans.h; sourceTree = "<group>"; };
+		69E0A81707CBD6C0008493CA /* NullTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = NullTrans.h; sourceTree = "<group>"; };
+		69E0A81807CBD6C0008493CA /* RandomTrans.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RandomTrans.cc; sourceTree = "<group>"; };
+		69E0A81907CBD6C0008493CA /* RandomTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RandomTrans.h; sourceTree = "<group>"; };
+		69E0A81A07CBD6C0008493CA /* SmoothCompareTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SmoothCompareTrans.h; sourceTree = "<group>"; };
+		69E0A81B07CBD6C0008493CA /* TimeOutTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = TimeOutTrans.h; sourceTree = "<group>"; };
+		69E0A81C07CBD6C0008493CA /* VisualTargetCloseTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = VisualTargetCloseTrans.h; sourceTree = "<group>"; };
+		69E0A81D07CBD6C0008493CA /* VisualTargetTrans.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = VisualTargetTrans.h; sourceTree = "<group>"; };
+		69E0A81F07CBD6C0008493CA /* DataEvent.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = DataEvent.h; sourceTree = "<group>"; };
+		69E0A82007CBD6C0008493CA /* EventBase.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EventBase.cc; sourceTree = "<group>"; };
+		69E0A82107CBD6C0008493CA /* EventBase.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventBase.h; sourceTree = "<group>"; };
+		69E0A82207CBD6C0008493CA /* EventGeneratorBase.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EventGeneratorBase.cc; sourceTree = "<group>"; };
+		69E0A82307CBD6C0008493CA /* EventGeneratorBase.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventGeneratorBase.h; sourceTree = "<group>"; };
+		69E0A82407CBD6C0008493CA /* EventListener.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventListener.h; sourceTree = "<group>"; };
+		69E0A82507CBD6C0008493CA /* EventRouter.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EventRouter.cc; sourceTree = "<group>"; };
+		69E0A82607CBD6C0008493CA /* EventRouter.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventRouter.h; sourceTree = "<group>"; };
+		69E0A82707CBD6C0008493CA /* EventTranslator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EventTranslator.cc; sourceTree = "<group>"; };
+		69E0A82807CBD6C0008493CA /* EventTranslator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventTranslator.h; sourceTree = "<group>"; };
+		69E0A82907CBD6C0008493CA /* EventTrapper.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EventTrapper.h; sourceTree = "<group>"; };
+		69E0A82A07CBD6C0008493CA /* FilterBankEvent.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FilterBankEvent.h; sourceTree = "<group>"; };
+		69E0A82B07CBD6C0008493CA /* LocomotionEvent.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LocomotionEvent.cc; sourceTree = "<group>"; };
+		69E0A82C07CBD6C0008493CA /* LocomotionEvent.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LocomotionEvent.h; sourceTree = "<group>"; };
+		69E0A82D07CBD6C0008493CA /* SegmentedColorFilterBankEvent.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SegmentedColorFilterBankEvent.h; sourceTree = "<group>"; };
+		69E0A82E07CBD6C0008493CA /* TextMsgEvent.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TextMsgEvent.cc; sourceTree = "<group>"; };
+		69E0A82F07CBD6C0008493CA /* TextMsgEvent.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = TextMsgEvent.h; sourceTree = "<group>"; };
+		69E0A83007CBD6C0008493CA /* VisionObjectEvent.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = VisionObjectEvent.cc; sourceTree = "<group>"; };
+		69E0A83107CBD6C0008493CA /* VisionObjectEvent.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = VisionObjectEvent.h; sourceTree = "<group>"; };
+		69E0A83307CBD6C0008493CA /* DynamicMotionSequence.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = DynamicMotionSequence.h; sourceTree = "<group>"; };
+		69E0A83407CBD6C0008493CA /* EmergencyStopMC.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = EmergencyStopMC.cc; sourceTree = "<group>"; };
+		69E0A83507CBD6C0008493CA /* EmergencyStopMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = EmergencyStopMC.h; sourceTree = "<group>"; };
+		69E0A83607CBD6C0008493CA /* Geometry.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Geometry.h; sourceTree = "<group>"; };
+		69E0A83707CBD6C0008493CA /* gvector.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = gvector.h; sourceTree = "<group>"; };
+		69E0A83807CBD6C0008493CA /* HeadPointerMC.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = HeadPointerMC.cc; sourceTree = "<group>"; };
+		69E0A83907CBD6C0008493CA /* HeadPointerMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = HeadPointerMC.h; sourceTree = "<group>"; };
+		69E0A83A07CBD6C0008493CA /* Kinematics.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Kinematics.cc; sourceTree = "<group>"; };
+		69E0A83B07CBD6C0008493CA /* Kinematics.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Kinematics.h; sourceTree = "<group>"; };
+		69E0A83C07CBD6C0008493CA /* LedEngine.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LedEngine.cc; sourceTree = "<group>"; };
+		69E0A83D07CBD6C0008493CA /* LedEngine.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LedEngine.h; sourceTree = "<group>"; };
+		69E0A83E07CBD6C0008493CA /* LedMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LedMC.h; sourceTree = "<group>"; };
+		69E0A83F07CBD6C0008493CA /* MMAccessor.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MMAccessor.h; sourceTree = "<group>"; };
+		69E0A84007CBD6C0008493CA /* MotionCommand.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MotionCommand.cc; sourceTree = "<group>"; };
+		69E0A84107CBD6C0008493CA /* MotionCommand.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MotionCommand.h; sourceTree = "<group>"; };
+		69E0A84207CBD6C0008493CA /* MotionManager.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MotionManager.cc; sourceTree = "<group>"; };
+		69E0A84307CBD6C0008493CA /* MotionManager.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MotionManager.h; sourceTree = "<group>"; };
+		69E0A84407CBD6C0008493CA /* MotionManagerMsg.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MotionManagerMsg.h; sourceTree = "<group>"; };
+		69E0A84507CBD6C0008493CA /* MotionSequenceEngine.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = MotionSequenceEngine.cc; sourceTree = "<group>"; };
+		69E0A84607CBD6C0008493CA /* MotionSequenceEngine.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MotionSequenceEngine.h; sourceTree = "<group>"; };
+		69E0A84707CBD6C0008493CA /* MotionSequenceMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = MotionSequenceMC.h; sourceTree = "<group>"; };
+		69E0A84807CBD6C0008493CA /* OldHeadPointerMC.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OldHeadPointerMC.cc; sourceTree = "<group>"; };
+		69E0A84907CBD6C0008493CA /* OldHeadPointerMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = OldHeadPointerMC.h; sourceTree = "<group>"; };
+		69E0A84A07CBD6C0008493CA /* OldKinematics.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OldKinematics.cc; sourceTree = "<group>"; };
+		69E0A84B07CBD6C0008493CA /* OldKinematics.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = OldKinematics.h; sourceTree = "<group>"; };
+		69E0A84C07CBD6C0008493CA /* OutputCmd.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OutputCmd.cc; sourceTree = "<group>"; };
+		69E0A84D07CBD6C0008493CA /* OutputCmd.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = OutputCmd.h; sourceTree = "<group>"; };
+		69E0A84E07CBD6C0008493CA /* OutputPID.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = OutputPID.h; sourceTree = "<group>"; };
+		69E0A84F07CBD6C0008493CA /* Path.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Path.h; sourceTree = "<group>"; };
+		69E0A85007CBD6C0008493CA /* PIDMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = PIDMC.h; sourceTree = "<group>"; };
+		69E0A85107CBD6C0008493CA /* PostureEngine.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PostureEngine.cc; sourceTree = "<group>"; };
+		69E0A85207CBD6C0008493CA /* PostureEngine.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = PostureEngine.h; sourceTree = "<group>"; };
+		69E0A85307CBD6C0008493CA /* PostureMC.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = PostureMC.cc; sourceTree = "<group>"; };
+		69E0A85407CBD6C0008493CA /* PostureMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = PostureMC.h; sourceTree = "<group>"; };
+		69E0A85507CBD6C0008493CA /* RemoteControllerMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RemoteControllerMC.h; sourceTree = "<group>"; };
+		69E0A85707CBD6C0008493CA /* clik.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = clik.cpp; sourceTree = "<group>"; };
+		69E0A85807CBD6C0008493CA /* clik.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = clik.h; sourceTree = "<group>"; };
+		69E0A85907CBD6C0008493CA /* comp_dq.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = comp_dq.cpp; sourceTree = "<group>"; };
+		69E0A85A07CBD6C0008493CA /* comp_dqp.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = comp_dqp.cpp; sourceTree = "<group>"; };
+		69E0A85B07CBD6C0008493CA /* config.cpp */ = {isa = PBXFileReference; fileEncoding = 30; indentWidth = 3; lastKnownFileType = sourcecode.cpp.cpp; path = config.cpp; sourceTree = "<group>"; tabWidth = 2; usesTabs = 0; };
+		69E0A85C07CBD6C0008493CA /* config.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = config.h; sourceTree = "<group>"; };
+		69E0A85D07CBD6C0008493CA /* control_select.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = control_select.cpp; sourceTree = "<group>"; };
+		69E0A85E07CBD6C0008493CA /* control_select.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = control_select.h; sourceTree = "<group>"; };
+		69E0A85F07CBD6C0008493CA /* controller.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = controller.cpp; sourceTree = "<group>"; };
+		69E0A86007CBD6C0008493CA /* controller.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = controller.h; sourceTree = "<group>"; };
+		69E0A86107CBD6C0008493CA /* delta_t.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = delta_t.cpp; sourceTree = "<group>"; };
+		69E0A86207CBD6C0008493CA /* dynamics.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = dynamics.cpp; sourceTree = "<group>"; };
+		69E0A86307CBD6C0008493CA /* dynamics_sim.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = dynamics_sim.cpp; sourceTree = "<group>"; };
+		69E0A86407CBD6C0008493CA /* dynamics_sim.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = dynamics_sim.h; sourceTree = "<group>"; };
+		69E0A87907CBD6C0008493CA /* gnugraph.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = gnugraph.cpp; sourceTree = "<group>"; };
+		69E0A87A07CBD6C0008493CA /* gnugraph.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = gnugraph.h; sourceTree = "<group>"; };
+		69E0A87B07CBD6C0008493CA /* homogen.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = homogen.cpp; sourceTree = "<group>"; };
+		69E0A87C07CBD6C0008493CA /* invkine.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = invkine.cpp; sourceTree = "<group>"; };
+		69E0A87D07CBD6C0008493CA /* kinemat.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = kinemat.cpp; sourceTree = "<group>"; };
+		69E0A87E07CBD6C0008493CA /* Makefile */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = "<group>"; };
+		69E0A87F07CBD6C0008493CA /* quaternion.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = quaternion.cpp; sourceTree = "<group>"; };
+		69E0A88007CBD6C0008493CA /* quaternion.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = quaternion.h; sourceTree = "<group>"; };
+		69E0A88107CBD6C0008493CA /* readme.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = readme.txt; sourceTree = "<group>"; };
+		69E0A88207CBD6C0008493CA /* revisions.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = revisions.txt; sourceTree = "<group>"; };
+		69E0A88307CBD6C0008493CA /* robdocs.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = robdocs.tar.gz; sourceTree = "<group>"; };
+		69E0A88407CBD6C0008493CA /* robot.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = robot.cpp; sourceTree = "<group>"; };
+		69E0A88507CBD6C0008493CA /* robot.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = robot.h; sourceTree = "<group>"; };
+		69E0A88607CBD6C0008493CA /* sensitiv.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = sensitiv.cpp; sourceTree = "<group>"; };
+		69E0A88707CBD6C0008493CA /* trajectory.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = trajectory.cpp; sourceTree = "<group>"; };
+		69E0A88807CBD6C0008493CA /* trajectory.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = trajectory.h; sourceTree = "<group>"; };
+		69E0A88907CBD6C0008493CA /* utils.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = utils.cpp; sourceTree = "<group>"; };
+		69E0A88A07CBD6C0008493CA /* utils.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = utils.h; sourceTree = "<group>"; };
+		69E0A88B07CBD6C0008493CA /* Spline.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Spline.h; sourceTree = "<group>"; };
+		69E0A88C07CBD6C0008493CA /* TailWagMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = TailWagMC.h; sourceTree = "<group>"; };
+		69E0A88D07CBD6C0008493CA /* WalkMC.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WalkMC.cc; sourceTree = "<group>"; };
+		69E0A88E07CBD6C0008493CA /* WalkMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WalkMC.h; sourceTree = "<group>"; };
+		69E0A88F07CBD6C0008493CA /* WaypointEngine.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WaypointEngine.h; sourceTree = "<group>"; };
+		69E0A89007CBD6C0008493CA /* WaypointWalkMC.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WaypointWalkMC.h; sourceTree = "<group>"; };
+		69E0A89207CBD6C0008493CA /* Buffer.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Buffer.cc; sourceTree = "<group>"; };
+		69E0A89307CBD6C0008493CA /* Buffer.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Buffer.h; sourceTree = "<group>"; };
+		69E0A89407CBD6C0008493CA /* CommonInfo.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = CommonInfo.h; sourceTree = "<group>"; };
+		69E0A89507CBD6C0008493CA /* Config.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Config.cc; sourceTree = "<group>"; };
+		69E0A89607CBD6C0008493CA /* Config.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Config.h; sourceTree = "<group>"; };
+		69E0A89707CBD6C0008493CA /* debuget.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = debuget.h; sourceTree = "<group>"; };
+		69E0A89807CBD6C0008493CA /* ERS210Info.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ERS210Info.h; sourceTree = "<group>"; };
+		69E0A89907CBD6C0008493CA /* ERS220Info.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ERS220Info.h; sourceTree = "<group>"; };
+		69E0A89A07CBD6C0008493CA /* ERS2xxInfo.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ERS2xxInfo.h; sourceTree = "<group>"; };
+		69E0A89B07CBD6C0008493CA /* ERS7Info.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ERS7Info.h; sourceTree = "<group>"; };
+		69E0A89C07CBD6C0008493CA /* Factory.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Factory.h; sourceTree = "<group>"; };
+		69E0A89D07CBD6C0008493CA /* get_time.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = get_time.cc; sourceTree = "<group>"; };
+		69E0A89E07CBD6C0008493CA /* get_time.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = get_time.h; sourceTree = "<group>"; };
+		69E0A8DE07CBD6C1008493CA /* jpeg_mem_dest.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = jpeg_mem_dest.cc; sourceTree = "<group>"; };
+		69E0A8DF07CBD6C1008493CA /* jpeg_mem_dest.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = jpeg_mem_dest.h; sourceTree = "<group>"; };
+		69E0A8F807CBD6C1008493CA /* LoadSave.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = LoadSave.cc; sourceTree = "<group>"; };
+		69E0A8F907CBD6C1008493CA /* LoadSave.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = LoadSave.h; sourceTree = "<group>"; };
+		69E0A8FB07CBD6C1008493CA /* mathutils.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = mathutils.h; sourceTree = "<group>"; };
+		69E0A8FE07CBD6C1008493CA /* bandmat.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = bandmat.cpp; sourceTree = "<group>"; };
+		69E0A8FF07CBD6C1008493CA /* boolean.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = boolean.h; sourceTree = "<group>"; };
+		69E0A90007CBD6C1008493CA /* cholesky.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = cholesky.cpp; sourceTree = "<group>"; };
+		69E0A90107CBD6C1008493CA /* controlw.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = controlw.h; sourceTree = "<group>"; };
+		69E0A90407CBD6C1008493CA /* add_time.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = add_time.png; sourceTree = "<group>"; };
+		69E0A90507CBD6C1008493CA /* nm11.htm */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.html; path = nm11.htm; sourceTree = "<group>"; };
+		69E0A90607CBD6C1008493CA /* rbd.css */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = rbd.css; sourceTree = "<group>"; };
+		69E0A90707CBD6C1008493CA /* evalue.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = evalue.cpp; sourceTree = "<group>"; };
+		69E0A93807CBD6C1008493CA /* fft.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = fft.cpp; sourceTree = "<group>"; };
+		69E0A93907CBD6C1008493CA /* hholder.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = hholder.cpp; sourceTree = "<group>"; };
+		69E0A93A07CBD6C1008493CA /* include.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = include.h; sourceTree = "<group>"; };
+		69E0A93B07CBD6C1008493CA /* jacobi.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = jacobi.cpp; sourceTree = "<group>"; };
+		69E0A93C07CBD6C1008493CA /* Makefile */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = "<group>"; };
+		69E0A93D07CBD6C1008493CA /* myexcept.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = myexcept.cpp; sourceTree = "<group>"; };
+		69E0A93E07CBD6C1008493CA /* myexcept.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = myexcept.h; sourceTree = "<group>"; };
+		69E0A93F07CBD6C1008493CA /* newfft.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newfft.cpp; sourceTree = "<group>"; };
+		69E0A94007CBD6C1008493CA /* newmat.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = newmat.h; sourceTree = "<group>"; };
+		69E0A94107CBD6C1008493CA /* newmat1.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat1.cpp; sourceTree = "<group>"; };
+		69E0A94207CBD6C1008493CA /* newmat2.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat2.cpp; sourceTree = "<group>"; };
+		69E0A94307CBD6C1008493CA /* newmat3.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat3.cpp; sourceTree = "<group>"; };
+		69E0A94407CBD6C1008493CA /* newmat4.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat4.cpp; sourceTree = "<group>"; };
+		69E0A94507CBD6C1008493CA /* newmat5.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat5.cpp; sourceTree = "<group>"; };
+		69E0A94607CBD6C1008493CA /* newmat6.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat6.cpp; sourceTree = "<group>"; };
+		69E0A94707CBD6C1008493CA /* newmat7.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat7.cpp; sourceTree = "<group>"; };
+		69E0A94807CBD6C1008493CA /* newmat8.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat8.cpp; sourceTree = "<group>"; };
+		69E0A94907CBD6C1008493CA /* newmat9.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmat9.cpp; sourceTree = "<group>"; };
+		69E0A94A07CBD6C1008493CA /* newmatap.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = newmatap.h; sourceTree = "<group>"; };
+		69E0A94B07CBD6C1008493CA /* newmatex.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmatex.cpp; sourceTree = "<group>"; };
+		69E0A94C07CBD6C1008493CA /* newmatio.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = newmatio.h; sourceTree = "<group>"; };
+		69E0A94D07CBD6C1008493CA /* newmatnl.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmatnl.cpp; sourceTree = "<group>"; };
+		69E0A94E07CBD6C1008493CA /* newmatnl.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = newmatnl.h; sourceTree = "<group>"; };
+		69E0A94F07CBD6C1008493CA /* newmatrc.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = newmatrc.h; sourceTree = "<group>"; };
+		69E0A95007CBD6C1008493CA /* newmatrm.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = newmatrm.cpp; sourceTree = "<group>"; };
+		69E0A95107CBD6C1008493CA /* newmatrm.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = newmatrm.h; sourceTree = "<group>"; };
+		69E0A95207CBD6C1008493CA /* precisio.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = precisio.h; sourceTree = "<group>"; };
+		69E0A95307CBD6C1008493CA /* readme.txt */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = readme.txt; sourceTree = "<group>"; };
+		69E0A95407CBD6C1008493CA /* sort.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = sort.cpp; sourceTree = "<group>"; };
+		69E0A95507CBD6C1008493CA /* submat.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = submat.cpp; sourceTree = "<group>"; };
+		69E0A95607CBD6C1008493CA /* svd.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = svd.cpp; sourceTree = "<group>"; };
+		69E0A95707CBD6C1008493CA /* ODataFormats.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ODataFormats.h; sourceTree = "<group>"; };
+		69E0A95A07CBD6C1008493CA /* Profiler.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Profiler.cc; sourceTree = "<group>"; };
+		69E0A95B07CBD6C1008493CA /* Profiler.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Profiler.h; sourceTree = "<group>"; };
+		69E0A95C07CBD6C1008493CA /* ProjectInterface.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = ProjectInterface.cc; sourceTree = "<group>"; };
+		69E0A95D07CBD6C1008493CA /* ProjectInterface.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ProjectInterface.h; sourceTree = "<group>"; };
+		69E0A96007CBD6C1008493CA /* ReferenceCounter.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = ReferenceCounter.h; sourceTree = "<group>"; };
+		69E0A96107CBD6C1008493CA /* RobotInfo.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RobotInfo.h; sourceTree = "<group>"; };
+		69E0A96507CBD6C1008493CA /* string_util.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = string_util.cc; sourceTree = "<group>"; };
+		69E0A96607CBD6C1008493CA /* string_util.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = string_util.h; sourceTree = "<group>"; };
+		69E0A96707CBD6C1008493CA /* SystemUtility.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SystemUtility.h; sourceTree = "<group>"; };
+		69E0A96807CBD6C1008493CA /* TimeET.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TimeET.cc; sourceTree = "<group>"; };
+		69E0A96907CBD6C1008493CA /* TimeET.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = TimeET.h; sourceTree = "<group>"; };
+		69E0A96A07CBD6C1008493CA /* Util.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Util.h; sourceTree = "<group>"; };
+		69E0A96B07CBD6C1008493CA /* WMclass.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WMclass.cc; sourceTree = "<group>"; };
+		69E0A96C07CBD6C1008493CA /* WMclass.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WMclass.h; sourceTree = "<group>"; };
+		69E0A96D07CBD6C1008493CA /* WorldState.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WorldState.cc; sourceTree = "<group>"; };
+		69E0A96E07CBD6C1008493CA /* WorldState.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WorldState.h; sourceTree = "<group>"; };
+		69E0A97007CBD6C1008493CA /* SoundManager.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SoundManager.cc; sourceTree = "<group>"; };
+		69E0A97107CBD6C1008493CA /* SoundManager.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SoundManager.h; sourceTree = "<group>"; };
+		69E0A97207CBD6C1008493CA /* SoundManagerMsg.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SoundManagerMsg.h; sourceTree = "<group>"; };
+		69E0A97307CBD6C1008493CA /* WAV.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = WAV.cc; sourceTree = "<group>"; };
+		69E0A97407CBD6C1008493CA /* WAV.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = WAV.h; sourceTree = "<group>"; };
+		69E0A97607CBD6C1008493CA /* BallDetectionGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = BallDetectionGenerator.cc; sourceTree = "<group>"; };
+		69E0A97707CBD6C1008493CA /* BallDetectionGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = BallDetectionGenerator.h; sourceTree = "<group>"; };
+		69E0A97807CBD6C1008493CA /* CDTGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = CDTGenerator.cc; sourceTree = "<group>"; };
+		69E0A97907CBD6C1008493CA /* CDTGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = CDTGenerator.h; sourceTree = "<group>"; };
+		69E0A97A07CBD6C1008493CA /* cmv_region.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = cmv_region.h; sourceTree = "<group>"; };
+		69E0A97B07CBD6C1008493CA /* cmv_threshold.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = cmv_threshold.h; sourceTree = "<group>"; usesTabs = 0; };
+		69E0A97C07CBD6C1008493CA /* cmv_types.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = cmv_types.h; sourceTree = "<group>"; };
+		69E0A97D07CBD6C1008493CA /* cmvision.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = cmvision.h; sourceTree = "<group>"; };
+		69E0A97E07CBD6C1008493CA /* colors.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = colors.h; sourceTree = "<group>"; };
+		69E0A97F07CBD6C1008493CA /* FilterBankGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = FilterBankGenerator.cc; sourceTree = "<group>"; };
+		69E0A98007CBD6C1008493CA /* FilterBankGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = FilterBankGenerator.h; sourceTree = "<group>"; };
+		69E0A98107CBD6C1008493CA /* InterleavedYUVGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = InterleavedYUVGenerator.cc; sourceTree = "<group>"; };
+		69E0A98207CBD6C1008493CA /* InterleavedYUVGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = InterleavedYUVGenerator.h; sourceTree = "<group>"; };
+		69E0A98307CBD6C1008493CA /* JPEGGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = JPEGGenerator.cc; sourceTree = "<group>"; };
+		69E0A98407CBD6C1008493CA /* JPEGGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = JPEGGenerator.h; sourceTree = "<group>"; };
+		69E0A98507CBD6C1008493CA /* OFbkImage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = OFbkImage.h; sourceTree = "<group>"; };
+		69E0A98607CBD6C1008493CA /* RawCameraGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RawCameraGenerator.cc; sourceTree = "<group>"; };
+		69E0A98707CBD6C1008493CA /* RawCameraGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RawCameraGenerator.h; sourceTree = "<group>"; };
+		69E0A98807CBD6C1008493CA /* RegionGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RegionGenerator.cc; sourceTree = "<group>"; };
+		69E0A98907CBD6C1008493CA /* RegionGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RegionGenerator.h; sourceTree = "<group>"; };
+		69E0A98A07CBD6C1008493CA /* RLEGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RLEGenerator.cc; sourceTree = "<group>"; };
+		69E0A98B07CBD6C1008493CA /* RLEGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = RLEGenerator.h; sourceTree = "<group>"; };
+		69E0A98C07CBD6C1008493CA /* SegmentedColorGenerator.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = SegmentedColorGenerator.cc; sourceTree = "<group>"; };
+		69E0A98D07CBD6C1008493CA /* SegmentedColorGenerator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = SegmentedColorGenerator.h; sourceTree = "<group>"; };
+		69E0A98F07CBD6C1008493CA /* DummySocket.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = DummySocket.h; sourceTree = "<group>"; };
+		69E0A99107CBD6C1008493CA /* Socket.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Socket.cc; sourceTree = "<group>"; };
+		69E0A99207CBD6C1008493CA /* Socket.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Socket.h; sourceTree = "<group>"; };
+		69E0A99307CBD6C1008493CA /* Wireless.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Wireless.cc; sourceTree = "<group>"; };
+		69E0A99407CBD6C1008493CA /* Wireless.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 30; path = Wireless.h; sourceTree = "<group>"; };
+		69E0AD5C07CBDE11008493CA /* sim-ERS210 */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "sim-ERS210"; sourceTree = BUILT_PRODUCTS_DIR; };
+		69E0AD8407CBED91008493CA /* Makefile */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = "<group>"; };
+		69E0AD8907CBEDAA008493CA /* Makefile */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = "<group>"; };
+		69E0AD9107CBEDC6008493CA /* Environment.conf */ = {isa = PBXFileReference; explicitFileType = sourcecode.make; fileEncoding = 30; path = Environment.conf; sourceTree = "<group>"; };
+		69E0ADB607CBF0AB008493CA /* libroboop.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libroboop.a; path = PLATFORM_LOCAL/Motion/roboop/libroboop.a; sourceTree = TEKKOTSU_BUILDDIR; };
+		69E0ADBD07CBF0F8008493CA /* libnewmat.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libnewmat.a; path = PLATFORM_LOCAL/Shared/newmat/libnewmat.a; sourceTree = TEKKOTSU_BUILDDIR; };
+		69E0ADC407CBF382008493CA /* libtekkotsu.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libtekkotsu.a; path = PLATFORM_LOCAL/TGT_ERS7/libtekkotsu.a; sourceTree = TEKKOTSU_BUILDDIR; };
+		69E0AFA807CBF79B008493CA /* sim-ERS7 */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "sim-ERS7"; sourceTree = BUILT_PRODUCTS_DIR; };
+		69E0AFDC07CC0113008493CA /* libtekkotsu.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libtekkotsu.a; path = PLATFORM_LOCAL/TGT_ERS210/libtekkotsu.a; sourceTree = TEKKOTSU_BUILDDIR; };
+		69E666B607F0CE3A005F4FA9 /* plist.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = plist.h; sourceTree = "<group>"; };
+		69E666BB07F0CE51005F4FA9 /* plist.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = plist.cc; sourceTree = "<group>"; };
+		69E6674707F1E23A005F4FA9 /* XMLLoadSave.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XMLLoadSave.cc; sourceTree = "<group>"; };
+		69E6674807F1E23A005F4FA9 /* XMLLoadSave.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XMLLoadSave.h; sourceTree = "<group>"; };
+		69E6696307F3398F005F4FA9 /* SimConfig.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SimConfig.cc; sourceTree = "<group>"; };
+		69E6696407F3398F005F4FA9 /* SimConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimConfig.h; sourceTree = "<group>"; };
+		69EA8B9207EB57480047DA8D /* libiconv.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libiconv.dylib; path = /usr/lib/libiconv.dylib; sourceTree = "<absolute>"; };
+		69EA8B9307EB57480047DA8D /* libxml2.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libxml2.dylib; path = /usr/lib/libxml2.dylib; sourceTree = "<absolute>"; };
+		69EA8B9407EB57480047DA8D /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = /usr/lib/libz.dylib; sourceTree = "<absolute>"; };
+		69ED0BB807DEABF700114CD2 /* Thread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Thread.h; sourceTree = "<group>"; };
+		69FA48F5084C389D0003A261 /* UPennWalkMC.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = UPennWalkMC.cc; sourceTree = "<group>"; };
+		69FA48F6084C389D0003A261 /* UPennWalkMC.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = UPennWalkMC.h; sourceTree = "<group>"; };
+		69FA48F9084C38E80003A261 /* Graphics.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = Graphics.cc; sourceTree = "<group>"; };
+		69FA48FA084C38E80003A261 /* Graphics.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = Graphics.h; sourceTree = "<group>"; };
+		69FA48FB084C38E80003A261 /* RLEGraphics.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = RLEGraphics.cc; sourceTree = "<group>"; };
+		69FA48FC084C38E80003A261 /* RLEGraphics.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = RLEGraphics.h; sourceTree = "<group>"; };
+		69FA4901084C39230003A261 /* UPennWalkControllerBehavior.cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = UPennWalkControllerBehavior.cc; sourceTree = "<group>"; };
+		69FA4902084C39230003A261 /* UPennWalkControllerBehavior.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = UPennWalkControllerBehavior.h; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		69E0AC5A07CBDE11008493CA /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				69E0AC5B07CBDE11008493CA /* libstdc++.a in Frameworks */,
+				69EA8B9B07EB57480047DA8D /* libiconv.dylib in Frameworks */,
+				69EA8B9C07EB57480047DA8D /* libxml2.dylib in Frameworks */,
+				69EA8B9D07EB57480047DA8D /* libz.dylib in Frameworks */,
+				694AB43707F48A860071A2AE /* libjpeg.dylib in Frameworks */,
+				694AB43807F48A860071A2AE /* libpng12.dylib in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		69E0AFA607CBF79B008493CA /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				69E0AFB907CBF881008493CA /* libtekkotsu.a in Frameworks */,
+				69E0AFBA07CBF881008493CA /* libroboop.a in Frameworks */,
+				69E0AFBB07CBF881008493CA /* libnewmat.a in Frameworks */,
+				69EA8B9807EB57480047DA8D /* libiconv.dylib in Frameworks */,
+				69EA8B9907EB57480047DA8D /* libxml2.dylib in Frameworks */,
+				69EA8B9A07EB57480047DA8D /* libz.dylib in Frameworks */,
+				694AB43B07F48A860071A2AE /* libjpeg.dylib in Frameworks */,
+				694AB43C07F48A860071A2AE /* libpng12.dylib in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		8DD76F660486A84900D96B5E /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				69A6D6DB07CD7C9500CB4720 /* libstdc++.a in Frameworks */,
+				69EA8B9507EB57480047DA8D /* libiconv.dylib in Frameworks */,
+				69EA8B9607EB57480047DA8D /* libxml2.dylib in Frameworks */,
+				69EA8B9707EB57480047DA8D /* libz.dylib in Frameworks */,
+				694AB43907F48A860071A2AE /* libjpeg.dylib in Frameworks */,
+				694AB43A07F48A860071A2AE /* libpng12.dylib in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		0249A662FF388D9811CA2CEA /* External Frameworks and Libraries */ = {
+			isa = PBXGroup;
+			children = (
+				69E0ADC407CBF382008493CA /* libtekkotsu.a */,
+				69E0AFDC07CC0113008493CA /* libtekkotsu.a */,
+				69E0ADB607CBF0AB008493CA /* libroboop.a */,
+				69E0ADBD07CBF0F8008493CA /* libnewmat.a */,
+				0249A663FF388D9811CA2CEA /* libstdc++.a */,
+				694AB43507F48A860071A2AE /* libjpeg.dylib */,
+				694AB43607F48A860071A2AE /* libpng12.dylib */,
+				69EA8B9307EB57480047DA8D /* libxml2.dylib */,
+				69EA8B9207EB57480047DA8D /* libiconv.dylib */,
+				69EA8B9407EB57480047DA8D /* libz.dylib */,
+			);
+			name = "External Frameworks and Libraries";
+			sourceTree = "<group>";
+		};
+		08FB7794FE84155DC02AAC07 /* sim */ = {
+			isa = PBXGroup;
+			children = (
+				08FB7795FE84155DC02AAC07 /* Project Files */,
+				69E0A74A07CBBECE008493CA /* Tekkotsu Source */,
+				69E0A75107CBBF2D008493CA /* Sim Source */,
+				0249A662FF388D9811CA2CEA /* External Frameworks and Libraries */,
+				6985DA3408527479009FD05A /* tools */,
+				69761DB608562012007DB073 /* mon */,
+				69E0AD5D07CBDE11008493CA /* Products */,
+			);
+			name = sim;
+			sourceTree = "<group>";
+		};
+		08FB7795FE84155DC02AAC07 /* Project Files */ = {
+			isa = PBXGroup;
+			children = (
+				696B01FB07D6906E000C1839 /* ms */,
+				69E0A75707CBD4F9008493CA /* SampleBehavior.h */,
+				69E0A75807CBD4F9008493CA /* SampleMC.h */,
+				69E0A75907CBD4F9008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc */,
+				69E0A75A07CBD4F9008493CA /* StartupBehavior_SetupFileAccess.cc */,
+				69E0A75B07CBD4F9008493CA /* StartupBehavior_SetupModeSwitch.cc */,
+				69E0A75C07CBD4F9008493CA /* StartupBehavior_SetupStatusReports.cc */,
+				69E0A75D07CBD4F9008493CA /* StartupBehavior_SetupTekkotsuMon.cc */,
+				69E0A75E07CBD4F9008493CA /* StartupBehavior_SetupVision.cc */,
+				69E0A75F07CBD4F9008493CA /* StartupBehavior_SetupWalkEdit.cc */,
+				69E0A76007CBD4F9008493CA /* StartupBehavior.cc */,
+				69E0A76107CBD4F9008493CA /* StartupBehavior.h */,
+				69E0AD8907CBEDAA008493CA /* Makefile */,
+				69E0AD9107CBEDC6008493CA /* Environment.conf */,
+				6994F5CB07D68F2A003A7628 /* aperios */,
+				6994F5BF07D68ED9003A7628 /* local */,
+			);
+			includeInIndex = 1;
+			name = "Project Files";
+			sourceTree = "<group>";
+		};
+		69761DB608562012007DB073 /* mon */ = {
+			isa = PBXGroup;
+			children = (
+				69761DBB0856207A007DB073 /* AiboComm.java */,
+				69761DBC0856207A007DB073 /* Base64.java */,
+				69761DBD0856207A007DB073 /* ClassPathModifier.java */,
+				69761DBE0856207A007DB073 /* ControllerErr.java */,
+				69761DBF0856207A007DB073 /* ControllerGUI.java */,
+				69761DC00856207A007DB073 /* ControllerListener.java */,
+				69761DC10856207A007DB073 /* ControllerMsg.java */,
+				69761DC20856207A007DB073 /* DogConfig.java */,
+				69761DC30856207A007DB073 /* DogConfigFTP.java */,
+				69761DC40856207A007DB073 /* EditScriptGUI.java */,
+				69761DC50856207A007DB073 /* EStopButton.java */,
+				69761DC60856207A007DB073 /* EStopGUI.java */,
+				69761DC70856207A007DB073 /* EStopListener.java */,
+				69761DC80856207A007DB073 /* EStopPanel.java */,
+				69761DC90856207A007DB073 /* GraphCanvas.java */,
+				69761DCA0856207A007DB073 /* HeadPointGUI.java */,
+				69761DCB0856207A007DB073 /* HeadPointListener.java */,
+				69761DCC0856207A007DB073 /* ImageSequenceWriterThread.java */,
+				69761DCD0856207A007DB073 /* JointLogger.java */,
+				69761DCE0856207A007DB073 /* JointRelay.java */,
+				69761DCF0856207A007DB073 /* JointRequestor.java */,
+				69761DD00856207A007DB073 /* Joints.java */,
+				69761DD10856207A007DB073 /* JointWriter.java */,
+				69761DD20856207A007DB073 /* Listener.java */,
+				69761DD30856207A007DB073 /* MechaController.java */,
+				69761DD40856207A007DB073 /* MicrophoneClient.java */,
+				69761DD50856207A007DB073 /* NetDebug.java */,
+				69761DD60856207A007DB073 /* ParamListener.java */,
+				69761DD70856207A007DB073 /* PIDs.java */,
+				69761DD80856207A007DB073 /* PointPick.java */,
+				69761DD90856207A007DB073 /* PrintDuties.java */,
+				69761DDA0856207A007DB073 /* ScriptEntry.java */,
+				69761DDB0856207A007DB073 /* SpeakerClient.java */,
+				69761DDC0856207A007DB073 /* SquareRightLayout.java */,
+				69761DDD0856207A007DB073 /* TableMap.java */,
+				69761DDE0856207A007DB073 /* TableSorter.java */,
+				69761DDF0856207A007DB073 /* TCPListener.java */,
+				69761DE00856207A007DB073 /* TCPVisionListener.java */,
+				69761DE10856207A007DB073 /* Terminal.java */,
+				69761DE20856207A007DB073 /* TestGraph.java */,
+				69761DE30856207A007DB073 /* TextListener.java */,
+				69761DE40856207A007DB073 /* TextWatchableMemory.java */,
+				69761DE50856207A007DB073 /* TwoParamPanel.java */,
+				69761DE60856207A007DB073 /* UDPListener.java */,
+				69761DE70856207A007DB073 /* UDPVisionListener.java */,
+				69761DE80856207A007DB073 /* VisionGUI.java */,
+				69761DE90856207A007DB073 /* VisionListener.java */,
+				69761DEA0856207A007DB073 /* VisionPanel.java */,
+				69761DEB0856207A007DB073 /* VisionUpdatedListener.java */,
+				69761DEC0856207A007DB073 /* WalkGUI.java */,
+				69761DED0856207A007DB073 /* WatchableMemory.java */,
+				69761DEE0856207A007DB073 /* WatchableMemoryListener.java */,
+				69761DEF0856207A007DB073 /* WM2DMData.java */,
+				69761DF00856207A007DB073 /* WM2DMListener.java */,
+				69761DF10856207A007DB073 /* WM2FSData.java */,
+				69761DF20856207A007DB073 /* WM2FSListener.java */,
+				69761DF30856207A007DB073 /* WM2HMData.java */,
+				69761DF40856207A007DB073 /* WM2HMListener.java */,
+				69761DF50856207A007DB073 /* WMvar.java */,
+				69761DF60856207A007DB073 /* WorldModel2Conf.java */,
+				69761DF70856207A007DB073 /* WorldStateJointsListener.java */,
+				69761DF80856207A007DB073 /* WorldStatePIDsListener.java */,
+			);
+			name = mon;
+			path = tools/mon/org/tekkotsu/mon;
+			sourceTree = TEKKOTSU_ROOT;
+		};
+		6994F3C907D4D35F003A7628 /* IPC */ = {
+			isa = PBXGroup;
+			children = (
+				6994F3CA07D4D35F003A7628 /* ListMemBuf.h */,
+				6994F3CB07D4D35F003A7628 /* LockScope.h */,
+				6994F3CC07D4D35F003A7628 /* MessageQueue.h */,
+				69AA7D690860898300185BA2 /* MessageReceiver.cc */,
+				6994F3CD07D4D35F003A7628 /* MessageReceiver.h */,
+				6994F3CE07D4D35F003A7628 /* MutexLock.h */,
+				6942757707E0DCDD003DE3D9 /* MutexLock.cc */,
+				6994F3CF07D4D35F003A7628 /* SemaphoreManager.cc */,
+				6952B61A07DBFDCC00E2565F /* SemaphoreManager.h */,
+				6994F3D107D4D35F003A7628 /* ProcessID.cc */,
+				6994F3D207D4D35F003A7628 /* ProcessID.h */,
+				6994F3D307D4D35F003A7628 /* RCRegion.cc */,
+				6994F3D407D4D35F003A7628 /* RCRegion.h */,
+				6994F3D507D4D35F003A7628 /* RegionRegistry.h */,
+				6994F3D607D4D35F003A7628 /* SharedObject.cc */,
+				6994F3D707D4D35F003A7628 /* SharedObject.h */,
+				6942779007E164EA003DE3D9 /* Thread.cc */,
+				69ED0BB807DEABF700114CD2 /* Thread.h */,
+			);
+			path = IPC;
+			sourceTree = "<group>";
+		};
+		6994F59507D68DF6003A7628 /* aperios */ = {
+			isa = PBXGroup;
+			children = (
+				6994F59607D68DF6003A7628 /* Makefile.aperios */,
+				6994F59707D68DF6003A7628 /* MMCombo */,
+				6994F59C07D68DF6003A7628 /* SndPlay */,
+				6994F5A107D68DF7003A7628 /* TinyFTPD */,
+			);
+			path = aperios;
+			sourceTree = "<group>";
+		};
+		6994F59707D68DF6003A7628 /* MMCombo */ = {
+			isa = PBXGroup;
+			children = (
+				6994F59807D68DF6003A7628 /* MMCombo.cc */,
+				6994F59907D68DF6003A7628 /* MMCombo.h */,
+				6994F59A07D68DF6003A7628 /* MMCombo.ocf */,
+				6994F59B07D68DF6003A7628 /* stub.cfg */,
+			);
+			path = MMCombo;
+			sourceTree = "<group>";
+		};
+		6994F59C07D68DF6003A7628 /* SndPlay */ = {
+			isa = PBXGroup;
+			children = (
+				6994F59D07D68DF6003A7628 /* SndPlay.cc */,
+				6994F59E07D68DF6003A7628 /* SndPlay.h */,
+				6994F59F07D68DF7003A7628 /* SoundPlay.ocf */,
+				6994F5A007D68DF7003A7628 /* stub.cfg */,
+			);
+			path = SndPlay;
+			sourceTree = "<group>";
+		};
+		6994F5A107D68DF7003A7628 /* TinyFTPD */ = {
+			isa = PBXGroup;
+			children = (
+				6994F5A207D68DF7003A7628 /* FtpConfig.h */,
+				6994F5A307D68DF7003A7628 /* FtpDTP.cc */,
+				6994F5A407D68DF7003A7628 /* FtpDTP.h */,
+				6994F5A507D68DF7003A7628 /* FtpMethod.cc */,
+				6994F5A607D68DF7003A7628 /* FtpPI.cc */,
+				6994F5A707D68DF7003A7628 /* FtpPI.h */,
+				6994F5A807D68DF7003A7628 /* FtpRequest.cc */,
+				6994F5A907D68DF7003A7628 /* stub.cfg */,
+				6994F5AA07D68DF7003A7628 /* TCPConnection.h */,
+				6994F5AB07D68DF7003A7628 /* TinyFTPD.cc */,
+				6994F5AC07D68DF7003A7628 /* TinyFTPD.h */,
+				6994F5AD07D68DF7003A7628 /* TinyFTPD.ocf */,
+			);
+			path = TinyFTPD;
+			sourceTree = "<group>";
+		};
+		6994F5B407D68E31003A7628 /* local */ = {
+			isa = PBXGroup;
+			children = (
+				690564F20819531A00613A0E /* minisim.h */,
+				6994F5B807D68E41003A7628 /* Makefile.local */,
+			);
+			name = local;
+			path = aperios;
+			sourceTree = "<group>";
+		};
+		6994F5BF07D68ED9003A7628 /* local */ = {
+			isa = PBXGroup;
+			children = (
+				6994F5C307D68EE4003A7628 /* Makefile.local */,
+			);
+			name = local;
+			sourceTree = "<group>";
+		};
+		6994F5CB07D68F2A003A7628 /* aperios */ = {
+			isa = PBXGroup;
+			children = (
+				6994F5CC07D68F2A003A7628 /* Makefile.aperios */,
+			);
+			path = aperios;
+			sourceTree = "<group>";
+		};
+		69E0A74A07CBBECE008493CA /* Tekkotsu Source */ = {
+			isa = PBXGroup;
+			children = (
+				6994F56F07D68C8D003A7628 /* README */,
+				6994F57D07D68D23003A7628 /* INSTALL */,
+				69E0AD8407CBED91008493CA /* Makefile */,
+				69E0A78B07CBD6BF008493CA /* Behaviors */,
+				69E0A81E07CBD6C0008493CA /* Events */,
+				6994F3C907D4D35F003A7628 /* IPC */,
+				69E0A83207CBD6C0008493CA /* Motion */,
+				69E0A89107CBD6C0008493CA /* Shared */,
+				69E0A96F07CBD6C1008493CA /* Sound */,
+				69E0A97507CBD6C1008493CA /* Vision */,
+				69E0A98E07CBD6C1008493CA /* Wireless */,
+				6994F59507D68DF6003A7628 /* aperios */,
+				6994F5B407D68E31003A7628 /* local */,
+			);
+			name = "Tekkotsu Source";
+			sourceTree = TEKKOTSU_ROOT;
+		};
+		69E0A75107CBBF2D008493CA /* Sim Source */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A75607CBD4A2008493CA /* Framework */,
+			);
+			name = "Sim Source";
+			sourceTree = "<group>";
+		};
+		69E0A75607CBD4A2008493CA /* Framework */ = {
+			isa = PBXGroup;
+			children = (
+				695967E007FF3DCF004FABFF /* LoadImageThread.cc */,
+				695967E107FF3DCF004FABFF /* LoadImageThread.h */,
+				692CD99407F9F05500604100 /* LoadFileThread.cc */,
+				692CD99507F9F05500604100 /* LoadFileThread.h */,
+				692CD63407F8C46B00604100 /* sim.cc */,
+				6934224207D408E600BB3331 /* sim.h */,
+				69E0A76F07CBD52D008493CA /* Main.cc */,
+				69E0A77007CBD52D008493CA /* Main.h */,
+				69E0A77107CBD52D008493CA /* Motion.cc */,
+				69E0A77207CBD52D008493CA /* Motion.h */,
+				69E0A77307CBD52D008493CA /* Process.cc */,
+				69E0A77407CBD52D008493CA /* Process.h */,
+				69E0A77607CBD52D008493CA /* SharedGlobals.cc */,
+				69E0A77707CBD52D008493CA /* SharedGlobals.h */,
+				69E6696307F3398F005F4FA9 /* SimConfig.cc */,
+				69E6696407F3398F005F4FA9 /* SimConfig.h */,
+				69E0A77807CBD52D008493CA /* Simulator.cc */,
+				69E0A77907CBD52D008493CA /* Simulator.h */,
+				69E0A77A07CBD52D008493CA /* SoundPlay.cc */,
+				69E0A77B07CBD52D008493CA /* SoundPlay.h */,
+			);
+			name = Framework;
+			path = local/sim;
+			sourceTree = TEKKOTSU_ROOT;
+		};
+		69E0A78B07CBD6BF008493CA /* Behaviors */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A80D07CBD6C0008493CA /* README */,
+				69E0A78C07CBD6BF008493CA /* BehaviorBase.cc */,
+				69E0A78D07CBD6BF008493CA /* BehaviorBase.h */,
+				69E0A78F07CBD6BF008493CA /* Controller.cc */,
+				69E0A79007CBD6BF008493CA /* Controller.h */,
+				69E0A79107CBD6BF008493CA /* Controls */,
+				69E0A7BF07CBD6C0008493CA /* Demos */,
+				69E0A7EA07CBD6C0008493CA /* Mon */,
+				69E0A80107CBD6C0008493CA /* Nodes */,
+				69E0A80E07CBD6C0008493CA /* StateNode.cc */,
+				69E0A80F07CBD6C0008493CA /* StateNode.h */,
+				69E0A81007CBD6C0008493CA /* Transition.cc */,
+				69E0A81107CBD6C0008493CA /* Transition.h */,
+				69E0A81207CBD6C0008493CA /* Transitions */,
+			);
+			path = Behaviors;
+			sourceTree = "<group>";
+		};
+		69E0A79107CBD6BF008493CA /* Controls */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A79207CBD6BF008493CA /* BatteryCheckControl.h */,
+				69E0A79307CBD6BF008493CA /* BehaviorActivatorControl.h */,
+				69E0A79407CBD6BF008493CA /* BehaviorReportControl.h */,
+				69E0A79507CBD6BF008493CA /* BehaviorSwitchActivatorControl.h */,
+				69E0A79607CBD6BF008493CA /* BehaviorSwitchControl.h */,
+				69E0A79707CBD6BF008493CA /* ControlBase.cc */,
+				69E0A79807CBD6BF008493CA /* ControlBase.h */,
+				69E0A79907CBD6C0008493CA /* DumpFileControl.h */,
+				69E0A79A07CBD6C0008493CA /* EventLogger.cc */,
+				69E0A79B07CBD6C0008493CA /* EventLogger.h */,
+				69E0A79C07CBD6C0008493CA /* FileBrowserControl.cc */,
+				69E0A79D07CBD6C0008493CA /* FileBrowserControl.h */,
+				69E0A79E07CBD6C0008493CA /* FileInputControl.h */,
+				69E0A79F07CBD6C0008493CA /* FreeMemReportControl.cc */,
+				69E0A7A007CBD6C0008493CA /* FreeMemReportControl.h */,
+				69E0A7A107CBD6C0008493CA /* HelpControl.cc */,
+				69E0A7A207CBD6C0008493CA /* HelpControl.h */,
+				69E0A7A307CBD6C0008493CA /* LoadCalibration.h */,
+				69E0A7A407CBD6C0008493CA /* LoadPostureControl.h */,
+				69E0A7A507CBD6C0008493CA /* LoadWalkControl.h */,
+				69E0A7A607CBD6C0008493CA /* MCValueEditControl.h */,
+				69E0A7A707CBD6C0008493CA /* NetworkStatusControl.h */,
+				69E0A7A807CBD6C0008493CA /* NullControl.h */,
+				69E0A7A907CBD6C0008493CA /* PlaySoundControl.h */,
+				69E0A7AA07CBD6C0008493CA /* PostureEditor.cc */,
+				69E0A7AB07CBD6C0008493CA /* PostureEditor.h */,
+				69E0A7AC07CBD6C0008493CA /* ProfilerCheckControl.h */,
+				69E0A7AD07CBD6C0008493CA /* RebootControl.cc */,
+				69E0A7AE07CBD6C0008493CA /* RebootControl.h */,
+				69E0A7AF07CBD6C0008493CA /* RunSequenceControl.h */,
+				69E0A7B007CBD6C0008493CA /* SavePostureControl.h */,
+				69E0A7B107CBD6C0008493CA /* SaveWalkControl.h */,
+				69E0A7B207CBD6C0008493CA /* SensorObserverControl.cc */,
+				69E0A7B307CBD6C0008493CA /* SensorObserverControl.h */,
+				69E0A7B407CBD6C0008493CA /* ShutdownControl.cc */,
+				69E0A7B507CBD6C0008493CA /* ShutdownControl.h */,
+				69E0A7B607CBD6C0008493CA /* StringInputControl.cc */,
+				69E0A7B707CBD6C0008493CA /* StringInputControl.h */,
+				69E0A7B807CBD6C0008493CA /* ToggleControl.h */,
+				69E0A7B907CBD6C0008493CA /* ValueEditControl.h */,
+				69E0A7BA07CBD6C0008493CA /* ValueSetControl.h */,
+				69E0A7BB07CBD6C0008493CA /* WalkCalibration.cc */,
+				69E0A7BC07CBD6C0008493CA /* WalkCalibration.h */,
+				69E0A7BD07CBD6C0008493CA /* WaypointWalkControl.cc */,
+				69E0A7BE07CBD6C0008493CA /* WaypointWalkControl.h */,
+			);
+			path = Controls;
+			sourceTree = "<group>";
+		};
+		69E0A7BF07CBD6C0008493CA /* Demos */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A7C007CBD6C0008493CA /* AlanBehavior.h */,
+				69E0A7C107CBD6C0008493CA /* ASCIIVisionBehavior.cc */,
+				69E0A7C207CBD6C0008493CA /* ASCIIVisionBehavior.h */,
+				69E0A7C307CBD6C0008493CA /* AutoGetupBehavior.h */,
+				69E0A7C407CBD6C0008493CA /* BanditMachine.h */,
+				69E0A7C507CBD6C0008493CA /* BatteryMonitorBehavior.h */,
+				69E0A7C607CBD6C0008493CA /* CameraBehavior.cc */,
+				69E0A7C707CBD6C0008493CA /* CameraBehavior.h */,
+				69E0A7C807CBD6C0008493CA /* ChaseBallBehavior.cc */,
+				69E0A7C907CBD6C0008493CA /* ChaseBallBehavior.h */,
+				69E0A7CA07CBD6C0008493CA /* CrashTestBehavior.h */,
+				69E0A7CB07CBD6C0008493CA /* DriveMeBehavior.cc */,
+				69E0A7CC07CBD6C0008493CA /* DriveMeBehavior.h */,
+				69E0A7CD07CBD6C0008493CA /* ExploreMachine.cc */,
+				69E0A7CE07CBD6C0008493CA /* ExploreMachine.h */,
+				69E0A7CF07CBD6C0008493CA /* FlashIPAddrBehavior.cc */,
+				69E0A7D007CBD6C0008493CA /* FlashIPAddrBehavior.h */,
+				69E0A7D107CBD6C0008493CA /* FollowHeadBehavior.cc */,
+				69E0A7D207CBD6C0008493CA /* FollowHeadBehavior.h */,
+				69E0A7D307CBD6C0008493CA /* FreezeTestBehavior.h */,
+				69E0A7D407CBD6C0008493CA /* GroundPlaneBehavior.h */,
+				69E0A7D507CBD6C0008493CA /* HeadLevelBehavior.h */,
+				69E0A7D607CBD6C0008493CA /* HelloWorldBehavior.h */,
+				69E0A7D707CBD6C0008493CA /* karmedbandit.h */,
+				69E0A7D807CBD6C0008493CA /* KinematicSampleBehavior.h */,
+				69E0A7D907CBD6C0008493CA /* KinematicSampleBehavior2.h */,
+				69970AC4083DB2C60069D95C /* LogTestMachine.h */,
+				69E0A7DA07CBD6C0008493CA /* LookForSoundBehavior.h */,
+				69E0A7DB07CBD6C0008493CA /* MCRepeater.h */,
+				69E0A7DC07CBD6C0008493CA /* MotionStressTestBehavior.h */,
+				69E0A7DD07CBD6C0008493CA /* PaceTargetsMachine.cc */,
+				69E0A7DE07CBD6C0008493CA /* PaceTargetsMachine.h */,
+				69E0A7DF07CBD6C0008493CA /* RelaxBehavior.h */,
+				69E0A7E007CBD6C0008493CA /* SimpleChaseBallBehavior.h */,
+				69E0A7E107CBD6C0008493CA /* SoundTestBehavior.h */,
+				69E0A7E207CBD6C0008493CA /* StareAtBallBehavior.cc */,
+				69E0A7E307CBD6C0008493CA /* StareAtBallBehavior.h */,
+				69E0A7E407CBD6C0008493CA /* StareAtPawBehavior.h */,
+				69B4E445089409D800832D58 /* StareAtPawBehavior2.cc */,
+				69E0A7E507CBD6C0008493CA /* StareAtPawBehavior2.h */,
+				69E0A7E607CBD6C0008493CA /* ToggleHeadLightBehavior.h */,
+				69E0A7E707CBD6C0008493CA /* WallTestBehavior.cc */,
+				69E0A7E807CBD6C0008493CA /* WallTestBehavior.h */,
+				69E0A7E907CBD6C0008493CA /* WorldStateVelDaemon.h */,
+			);
+			path = Demos;
+			sourceTree = "<group>";
+		};
+		69E0A7EA07CBD6C0008493CA /* Mon */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A7EB07CBD6C0008493CA /* Aibo3DControllerBehavior.h */,
+				69A1995E080ED8A200540970 /* EchoBehavior.cc */,
+				69A19963080ED8AE00540970 /* EchoBehavior.h */,
+				69E0A7EC07CBD6C0008493CA /* EStopControllerBehavior.cc */,
+				69E0A7ED07CBD6C0008493CA /* EStopControllerBehavior.h */,
+				69E0A7EE07CBD6C0008493CA /* HeadPointControllerBehavior.cc */,
+				69E0A7EF07CBD6C0008493CA /* HeadPointControllerBehavior.h */,
+				69E0A7F007CBD6C0008493CA /* MicrophoneServer.cc */,
+				69E0A7F107CBD6C0008493CA /* MicrophoneServer.h */,
+				69E0A7F207CBD6C0008493CA /* RawCamBehavior.cc */,
+				69E0A7F307CBD6C0008493CA /* RawCamBehavior.h */,
+				69E0A7F407CBD6C0008493CA /* SegCamBehavior.cc */,
+				69E0A7F507CBD6C0008493CA /* SegCamBehavior.h */,
+				69E0A7F607CBD6C0008493CA /* SpeakerServer.cc */,
+				69E0A7F707CBD6C0008493CA /* SpeakerServer.h */,
+				69E0A7F807CBD6C0008493CA /* SpiderMachineBehavior.cc */,
+				69E0A7F907CBD6C0008493CA /* SpiderMachineBehavior.h */,
+				69970AC0083DB2760069D95C /* StewartPlatformBehavior.cc */,
+				69970AC3083DB2830069D95C /* StewartPlatformBehavior.h */,
+				69FA4901084C39230003A261 /* UPennWalkControllerBehavior.cc */,
+				69FA4902084C39230003A261 /* UPennWalkControllerBehavior.h */,
+				69E0A7FA07CBD6C0008493CA /* ViewWMVarsBehavior.h */,
+				69E0A7FB07CBD6C0008493CA /* WalkControllerBehavior.cc */,
+				69E0A7FC07CBD6C0008493CA /* WalkControllerBehavior.h */,
+				69E0A7FD07CBD6C0008493CA /* WMMonitorBehavior.cc */,
+				69E0A7FE07CBD6C0008493CA /* WMMonitorBehavior.h */,
+				69E0A7FF07CBD6C0008493CA /* WorldStateSerializerBehavior.cc */,
+				69E0A80007CBD6C0008493CA /* WorldStateSerializerBehavior.h */,
+			);
+			path = Mon;
+			sourceTree = "<group>";
+		};
+		69E0A80107CBD6C0008493CA /* Nodes */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A80207CBD6C0008493CA /* GroupNode.h */,
+				69E0A80307CBD6C0008493CA /* HeadPointerNode.h */,
+				69E0A80407CBD6C0008493CA /* LedNode.h */,
+				69E0A80507CBD6C0008493CA /* MotionSequenceNode.h */,
+				69E0A80607CBD6C0008493CA /* OutputNode.h */,
+				69E0A80707CBD6C0008493CA /* PlayMotionSequenceNode.h */,
+				69E0A80807CBD6C0008493CA /* SoundNode.h */,
+				69E0A80907CBD6C0008493CA /* TailWagNode.h */,
+				69E0A80A07CBD6C0008493CA /* WalkNode.h */,
+				69E0A80B07CBD6C0008493CA /* WalkToTargetNode.cc */,
+				69E0A80C07CBD6C0008493CA /* WalkToTargetNode.h */,
+			);
+			path = Nodes;
+			sourceTree = "<group>";
+		};
+		69E0A81207CBD6C0008493CA /* Transitions */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A81307CBD6C0008493CA /* CompareTrans.h */,
+				69E0A81407CBD6C0008493CA /* CompletionTrans.h */,
+				69E0A81507CBD6C0008493CA /* EventTrans.h */,
+				69E0A81607CBD6C0008493CA /* LostTargetTrans.h */,
+				69E0A81707CBD6C0008493CA /* NullTrans.h */,
+				69E0A81807CBD6C0008493CA /* RandomTrans.cc */,
+				69E0A81907CBD6C0008493CA /* RandomTrans.h */,
+				69E0A81A07CBD6C0008493CA /* SmoothCompareTrans.h */,
+				69970ACC083DB35B0069D95C /* TextMsgTrans.h */,
+				69E0A81B07CBD6C0008493CA /* TimeOutTrans.h */,
+				69E0A81C07CBD6C0008493CA /* VisualTargetCloseTrans.h */,
+				69E0A81D07CBD6C0008493CA /* VisualTargetTrans.h */,
+			);
+			path = Transitions;
+			sourceTree = "<group>";
+		};
+		69E0A81E07CBD6C0008493CA /* Events */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A81F07CBD6C0008493CA /* DataEvent.h */,
+				69E0A82007CBD6C0008493CA /* EventBase.cc */,
+				69E0A82107CBD6C0008493CA /* EventBase.h */,
+				69E0A82207CBD6C0008493CA /* EventGeneratorBase.cc */,
+				69E0A82307CBD6C0008493CA /* EventGeneratorBase.h */,
+				69E0A82407CBD6C0008493CA /* EventListener.h */,
+				69E0A82507CBD6C0008493CA /* EventRouter.cc */,
+				69E0A82607CBD6C0008493CA /* EventRouter.h */,
+				69E0A82707CBD6C0008493CA /* EventTranslator.cc */,
+				69E0A82807CBD6C0008493CA /* EventTranslator.h */,
+				69E0A82907CBD6C0008493CA /* EventTrapper.h */,
+				69E0A82A07CBD6C0008493CA /* FilterBankEvent.h */,
+				69E0A82B07CBD6C0008493CA /* LocomotionEvent.cc */,
+				69E0A82C07CBD6C0008493CA /* LocomotionEvent.h */,
+				69E0A82D07CBD6C0008493CA /* SegmentedColorFilterBankEvent.h */,
+				69E0A82E07CBD6C0008493CA /* TextMsgEvent.cc */,
+				69E0A82F07CBD6C0008493CA /* TextMsgEvent.h */,
+				69E0A83007CBD6C0008493CA /* VisionObjectEvent.cc */,
+				69E0A83107CBD6C0008493CA /* VisionObjectEvent.h */,
+			);
+			path = Events;
+			sourceTree = "<group>";
+		};
+		69E0A83207CBD6C0008493CA /* Motion */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A83307CBD6C0008493CA /* DynamicMotionSequence.h */,
+				69E0A83407CBD6C0008493CA /* EmergencyStopMC.cc */,
+				69E0A83507CBD6C0008493CA /* EmergencyStopMC.h */,
+				69E0A83607CBD6C0008493CA /* Geometry.h */,
+				69E0A83707CBD6C0008493CA /* gvector.h */,
+				69E0A83807CBD6C0008493CA /* HeadPointerMC.cc */,
+				69E0A83907CBD6C0008493CA /* HeadPointerMC.h */,
+				69E0A83A07CBD6C0008493CA /* Kinematics.cc */,
+				69E0A83B07CBD6C0008493CA /* Kinematics.h */,
+				69E0A83C07CBD6C0008493CA /* LedEngine.cc */,
+				69E0A83D07CBD6C0008493CA /* LedEngine.h */,
+				69E0A83E07CBD6C0008493CA /* LedMC.h */,
+				69E0A83F07CBD6C0008493CA /* MMAccessor.h */,
+				69E0A84007CBD6C0008493CA /* MotionCommand.cc */,
+				69E0A84107CBD6C0008493CA /* MotionCommand.h */,
+				69E0A84207CBD6C0008493CA /* MotionManager.cc */,
+				69E0A84307CBD6C0008493CA /* MotionManager.h */,
+				69E0A84407CBD6C0008493CA /* MotionManagerMsg.h */,
+				69E0A84507CBD6C0008493CA /* MotionSequenceEngine.cc */,
+				69E0A84607CBD6C0008493CA /* MotionSequenceEngine.h */,
+				69E0A84707CBD6C0008493CA /* MotionSequenceMC.h */,
+				69E0A84807CBD6C0008493CA /* OldHeadPointerMC.cc */,
+				69E0A84907CBD6C0008493CA /* OldHeadPointerMC.h */,
+				69E0A84A07CBD6C0008493CA /* OldKinematics.cc */,
+				69E0A84B07CBD6C0008493CA /* OldKinematics.h */,
+				69E0A84C07CBD6C0008493CA /* OutputCmd.cc */,
+				69E0A84D07CBD6C0008493CA /* OutputCmd.h */,
+				69E0A84E07CBD6C0008493CA /* OutputPID.h */,
+				69E0A84F07CBD6C0008493CA /* Path.h */,
+				69E0A85007CBD6C0008493CA /* PIDMC.h */,
+				69E0A85107CBD6C0008493CA /* PostureEngine.cc */,
+				69E0A85207CBD6C0008493CA /* PostureEngine.h */,
+				69E0A85307CBD6C0008493CA /* PostureMC.cc */,
+				69E0A85407CBD6C0008493CA /* PostureMC.h */,
+				69E0A85507CBD6C0008493CA /* RemoteControllerMC.h */,
+				69E0A85607CBD6C0008493CA /* roboop */,
+				69E0A88B07CBD6C0008493CA /* Spline.h */,
+				69E0A88C07CBD6C0008493CA /* TailWagMC.h */,
+				69FA48F5084C389D0003A261 /* UPennWalkMC.cc */,
+				69FA48F6084C389D0003A261 /* UPennWalkMC.h */,
+				69E0A88D07CBD6C0008493CA /* WalkMC.cc */,
+				69E0A88E07CBD6C0008493CA /* WalkMC.h */,
+				69E0A88F07CBD6C0008493CA /* WaypointEngine.h */,
+				69E0A89007CBD6C0008493CA /* WaypointWalkMC.h */,
+			);
+			path = Motion;
+			sourceTree = "<group>";
+		};
+		69E0A85607CBD6C0008493CA /* roboop */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A85707CBD6C0008493CA /* clik.cpp */,
+				69E0A85807CBD6C0008493CA /* clik.h */,
+				69E0A85907CBD6C0008493CA /* comp_dq.cpp */,
+				69E0A85A07CBD6C0008493CA /* comp_dqp.cpp */,
+				69E0A85B07CBD6C0008493CA /* config.cpp */,
+				69E0A85C07CBD6C0008493CA /* config.h */,
+				69E0A85D07CBD6C0008493CA /* control_select.cpp */,
+				69E0A85E07CBD6C0008493CA /* control_select.h */,
+				69E0A85F07CBD6C0008493CA /* controller.cpp */,
+				69E0A86007CBD6C0008493CA /* controller.h */,
+				69E0A86107CBD6C0008493CA /* delta_t.cpp */,
+				69E0A86207CBD6C0008493CA /* dynamics.cpp */,
+				69E0A86307CBD6C0008493CA /* dynamics_sim.cpp */,
+				69E0A86407CBD6C0008493CA /* dynamics_sim.h */,
+				69E0A87907CBD6C0008493CA /* gnugraph.cpp */,
+				69E0A87A07CBD6C0008493CA /* gnugraph.h */,
+				69E0A87B07CBD6C0008493CA /* homogen.cpp */,
+				69E0A87C07CBD6C0008493CA /* invkine.cpp */,
+				69E0A87D07CBD6C0008493CA /* kinemat.cpp */,
+				69E0A87E07CBD6C0008493CA /* Makefile */,
+				69E0A87F07CBD6C0008493CA /* quaternion.cpp */,
+				69E0A88007CBD6C0008493CA /* quaternion.h */,
+				69E0A88107CBD6C0008493CA /* readme.txt */,
+				69E0A88207CBD6C0008493CA /* revisions.txt */,
+				69E0A88307CBD6C0008493CA /* robdocs.tar.gz */,
+				69E0A88407CBD6C0008493CA /* robot.cpp */,
+				69E0A88507CBD6C0008493CA /* robot.h */,
+				69E0A88607CBD6C0008493CA /* sensitiv.cpp */,
+				69E0A88707CBD6C0008493CA /* trajectory.cpp */,
+				69E0A88807CBD6C0008493CA /* trajectory.h */,
+				69E0A88907CBD6C0008493CA /* utils.cpp */,
+				69E0A88A07CBD6C0008493CA /* utils.h */,
+			);
+			path = roboop;
+			sourceTree = "<group>";
+		};
+		69E0A89107CBD6C0008493CA /* Shared */ = {
+			isa = PBXGroup;
+			children = (
+				691C805508255F6300E8E256 /* Base64.cc */,
+				691C805C08255F6D00E8E256 /* Base64.h */,
+				69E0A89207CBD6C0008493CA /* Buffer.cc */,
+				69E0A89307CBD6C0008493CA /* Buffer.h */,
+				69E0A89407CBD6C0008493CA /* CommonInfo.h */,
+				69E0A89507CBD6C0008493CA /* Config.cc */,
+				69E0A89607CBD6C0008493CA /* Config.h */,
+				69E0A89707CBD6C0008493CA /* debuget.h */,
+				69E0A89807CBD6C0008493CA /* ERS210Info.h */,
+				69E0A89907CBD6C0008493CA /* ERS220Info.h */,
+				69E0A89A07CBD6C0008493CA /* ERS2xxInfo.h */,
+				69E0A89B07CBD6C0008493CA /* ERS7Info.h */,
+				69E0A89C07CBD6C0008493CA /* Factory.h */,
+				69E0A89D07CBD6C0008493CA /* get_time.cc */,
+				69E0A89E07CBD6C0008493CA /* get_time.h */,
+				69E0A89F07CBD6C0008493CA /* jpeg-6b */,
+				69E0A8F807CBD6C1008493CA /* LoadSave.cc */,
+				69E0A8F907CBD6C1008493CA /* LoadSave.h */,
+				69E0A8FB07CBD6C1008493CA /* mathutils.h */,
+				69E0A8FD07CBD6C1008493CA /* newmat */,
+				69E0A95707CBD6C1008493CA /* ODataFormats.h */,
+				69E666BB07F0CE51005F4FA9 /* plist.cc */,
+				69E666B607F0CE3A005F4FA9 /* plist.h */,
+				69E0A95A07CBD6C1008493CA /* Profiler.cc */,
+				69E0A95B07CBD6C1008493CA /* Profiler.h */,
+				69E0A95C07CBD6C1008493CA /* ProjectInterface.cc */,
+				69E0A95D07CBD6C1008493CA /* ProjectInterface.h */,
+				69E0A96007CBD6C1008493CA /* ReferenceCounter.h */,
+				69E0A96107CBD6C1008493CA /* RobotInfo.h */,
+				69E0A96507CBD6C1008493CA /* string_util.cc */,
+				69E0A96607CBD6C1008493CA /* string_util.h */,
+				69E0A96707CBD6C1008493CA /* SystemUtility.h */,
+				69E0A96807CBD6C1008493CA /* TimeET.cc */,
+				69E0A96907CBD6C1008493CA /* TimeET.h */,
+				69E0A96A07CBD6C1008493CA /* Util.h */,
+				69E0A96B07CBD6C1008493CA /* WMclass.cc */,
+				69E0A96C07CBD6C1008493CA /* WMclass.h */,
+				69E0A96D07CBD6C1008493CA /* WorldState.cc */,
+				69E0A96E07CBD6C1008493CA /* WorldState.h */,
+				69E6674707F1E23A005F4FA9 /* XMLLoadSave.cc */,
+				69E6674807F1E23A005F4FA9 /* XMLLoadSave.h */,
+			);
+			path = Shared;
+			sourceTree = "<group>";
+		};
+		69E0A89F07CBD6C0008493CA /* jpeg-6b */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A8DE07CBD6C1008493CA /* jpeg_mem_dest.cc */,
+				69E0A8DF07CBD6C1008493CA /* jpeg_mem_dest.h */,
+				69A323C007E35646009D94E1 /* write_jpeg.cc */,
+				69A323C107E35646009D94E1 /* write_jpeg.h */,
+			);
+			path = "jpeg-6b";
+			sourceTree = "<group>";
+		};
+		69E0A8FD07CBD6C1008493CA /* newmat */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A8FE07CBD6C1008493CA /* bandmat.cpp */,
+				69E0A8FF07CBD6C1008493CA /* boolean.h */,
+				69E0A90007CBD6C1008493CA /* cholesky.cpp */,
+				69E0A90107CBD6C1008493CA /* controlw.h */,
+				69E0A90207CBD6C1008493CA /* docs */,
+				69E0A90707CBD6C1008493CA /* evalue.cpp */,
+				69E0A93807CBD6C1008493CA /* fft.cpp */,
+				69E0A93907CBD6C1008493CA /* hholder.cpp */,
+				69E0A93A07CBD6C1008493CA /* include.h */,
+				69E0A93B07CBD6C1008493CA /* jacobi.cpp */,
+				69E0A93C07CBD6C1008493CA /* Makefile */,
+				69E0A93D07CBD6C1008493CA /* myexcept.cpp */,
+				69E0A93E07CBD6C1008493CA /* myexcept.h */,
+				69E0A93F07CBD6C1008493CA /* newfft.cpp */,
+				69E0A94007CBD6C1008493CA /* newmat.h */,
+				69E0A94107CBD6C1008493CA /* newmat1.cpp */,
+				69E0A94207CBD6C1008493CA /* newmat2.cpp */,
+				69E0A94307CBD6C1008493CA /* newmat3.cpp */,
+				69E0A94407CBD6C1008493CA /* newmat4.cpp */,
+				69E0A94507CBD6C1008493CA /* newmat5.cpp */,
+				69E0A94607CBD6C1008493CA /* newmat6.cpp */,
+				69E0A94707CBD6C1008493CA /* newmat7.cpp */,
+				69E0A94807CBD6C1008493CA /* newmat8.cpp */,
+				69E0A94907CBD6C1008493CA /* newmat9.cpp */,
+				69E0A94A07CBD6C1008493CA /* newmatap.h */,
+				69E0A94B07CBD6C1008493CA /* newmatex.cpp */,
+				69E0A94C07CBD6C1008493CA /* newmatio.h */,
+				69E0A94D07CBD6C1008493CA /* newmatnl.cpp */,
+				69E0A94E07CBD6C1008493CA /* newmatnl.h */,
+				69E0A94F07CBD6C1008493CA /* newmatrc.h */,
+				69E0A95007CBD6C1008493CA /* newmatrm.cpp */,
+				69E0A95107CBD6C1008493CA /* newmatrm.h */,
+				69E0A95207CBD6C1008493CA /* precisio.h */,
+				69E0A95307CBD6C1008493CA /* readme.txt */,
+				69E0A95407CBD6C1008493CA /* sort.cpp */,
+				69E0A95507CBD6C1008493CA /* submat.cpp */,
+				69E0A95607CBD6C1008493CA /* svd.cpp */,
+			);
+			path = newmat;
+			sourceTree = "<group>";
+		};
+		69E0A90207CBD6C1008493CA /* docs */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A90307CBD6C1008493CA /* images */,
+				69E0A90507CBD6C1008493CA /* nm11.htm */,
+				69E0A90607CBD6C1008493CA /* rbd.css */,
+			);
+			path = docs;
+			sourceTree = "<group>";
+		};
+		69E0A90307CBD6C1008493CA /* images */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A90407CBD6C1008493CA /* add_time.png */,
+			);
+			path = images;
+			sourceTree = "<group>";
+		};
+		69E0A96F07CBD6C1008493CA /* Sound */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A97007CBD6C1008493CA /* SoundManager.cc */,
+				69E0A97107CBD6C1008493CA /* SoundManager.h */,
+				69E0A97207CBD6C1008493CA /* SoundManagerMsg.h */,
+				69E0A97307CBD6C1008493CA /* WAV.cc */,
+				69E0A97407CBD6C1008493CA /* WAV.h */,
+			);
+			path = Sound;
+			sourceTree = "<group>";
+		};
+		69E0A97507CBD6C1008493CA /* Vision */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A97607CBD6C1008493CA /* BallDetectionGenerator.cc */,
+				69E0A97707CBD6C1008493CA /* BallDetectionGenerator.h */,
+				695F1AC80804A81800ACB3D7 /* BufferedImageGenerator.cc */,
+				695F1AC90804A81800ACB3D7 /* BufferedImageGenerator.h */,
+				69E0A97807CBD6C1008493CA /* CDTGenerator.cc */,
+				69E0A97907CBD6C1008493CA /* CDTGenerator.h */,
+				69E0A97A07CBD6C1008493CA /* cmv_region.h */,
+				69E0A97B07CBD6C1008493CA /* cmv_threshold.h */,
+				69E0A97C07CBD6C1008493CA /* cmv_types.h */,
+				69E0A97D07CBD6C1008493CA /* cmvision.h */,
+				69E0A97E07CBD6C1008493CA /* colors.h */,
+				69E0A97F07CBD6C1008493CA /* FilterBankGenerator.cc */,
+				69E0A98007CBD6C1008493CA /* FilterBankGenerator.h */,
+				69FA48F9084C38E80003A261 /* Graphics.cc */,
+				69FA48FA084C38E80003A261 /* Graphics.h */,
+				69E0A98107CBD6C1008493CA /* InterleavedYUVGenerator.cc */,
+				69E0A98207CBD6C1008493CA /* InterleavedYUVGenerator.h */,
+				69E0A98307CBD6C1008493CA /* JPEGGenerator.cc */,
+				69E0A98407CBD6C1008493CA /* JPEGGenerator.h */,
+				69E0A98507CBD6C1008493CA /* OFbkImage.h */,
+				69E0A98607CBD6C1008493CA /* RawCameraGenerator.cc */,
+				69E0A98707CBD6C1008493CA /* RawCameraGenerator.h */,
+				69E0A98807CBD6C1008493CA /* RegionGenerator.cc */,
+				69E0A98907CBD6C1008493CA /* RegionGenerator.h */,
+				69E0A98A07CBD6C1008493CA /* RLEGenerator.cc */,
+				69E0A98B07CBD6C1008493CA /* RLEGenerator.h */,
+				69FA48FB084C38E80003A261 /* RLEGraphics.cc */,
+				69FA48FC084C38E80003A261 /* RLEGraphics.h */,
+				69E0A98C07CBD6C1008493CA /* SegmentedColorGenerator.cc */,
+				69E0A98D07CBD6C1008493CA /* SegmentedColorGenerator.h */,
+			);
+			path = Vision;
+			sourceTree = "<group>";
+		};
+		69E0A98E07CBD6C1008493CA /* Wireless */ = {
+			isa = PBXGroup;
+			children = (
+				69E0A98F07CBD6C1008493CA /* DummySocket.h */,
+				69E0A99107CBD6C1008493CA /* Socket.cc */,
+				69E0A99207CBD6C1008493CA /* Socket.h */,
+				69E0A99307CBD6C1008493CA /* Wireless.cc */,
+				69E0A99407CBD6C1008493CA /* Wireless.h */,
+			);
+			path = Wireless;
+			sourceTree = "<group>";
+		};
+		69E0AD5D07CBDE11008493CA /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				69E0AD5C07CBDE11008493CA /* sim-ERS210 */,
+				69E0AFA807CBF79B008493CA /* sim-ERS7 */,
+				69A6D61007CD2C7700CB4720 /* sim-ERS7 */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+		69E0AB9A07CBDE11008493CA /* sim (ERS-210) */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 69FD50320881E74900E825BA /* Build configuration list for PBXNativeTarget "sim (ERS-210)" */;
+			buildPhases = (
+				69E0AB9B07CBDE11008493CA /* Sources */,
+				69E0AC5A07CBDE11008493CA /* Frameworks */,
+			);
+			buildRules = (
+			);
+			buildSettings = {
+				INSTALL_PATH = "$(HOME)/bin";
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS210";
+				PRODUCT_NAME = "sim-ERS210";
+			};
+			dependencies = (
+			);
+			name = "sim (ERS-210)";
+			productInstallPath = "$(HOME)/bin";
+			productName = sim;
+			productReference = 69E0AD5C07CBDE11008493CA /* sim-ERS210 */;
+			productType = "com.apple.product-type.tool";
+		};
+		69E0AFA707CBF79B008493CA /* sim (ERS-7) Light */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 69FD502E0881E74900E825BA /* Build configuration list for PBXNativeTarget "sim (ERS-7) Light" */;
+			buildPhases = (
+				69E0AFA507CBF79B008493CA /* Sources */,
+				69E0AFA607CBF79B008493CA /* Frameworks */,
+			);
+			buildRules = (
+			);
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS7";
+				PRODUCT_NAME = "sim-ERS7";
+			};
+			dependencies = (
+			);
+			name = "sim (ERS-7) Light";
+			productName = "sim (ERS-7) Light";
+			productReference = 69E0AFA807CBF79B008493CA /* sim-ERS7 */;
+			productType = "com.apple.product-type.tool";
+		};
+		8DD76F620486A84900D96B5E /* sim (ERS-7) */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 69FD502A0881E74900E825BA /* Build configuration list for PBXNativeTarget "sim (ERS-7)" */;
+			buildPhases = (
+				8DD76F640486A84900D96B5E /* Sources */,
+				8DD76F660486A84900D96B5E /* Frameworks */,
+			);
+			buildRules = (
+			);
+			buildSettings = {
+				INSTALL_PATH = "$(HOME)/bin";
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS7";
+				PRODUCT_NAME = "sim-ERS7";
+			};
+			dependencies = (
+			);
+			name = "sim (ERS-7)";
+			productInstallPath = "$(HOME)/bin";
+			productName = sim;
+			productReference = 69A6D61007CD2C7700CB4720 /* sim-ERS7 */;
+			productType = "com.apple.product-type.tool";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		08FB7793FE84155DC02AAC07 /* Project object */ = {
+			isa = PBXProject;
+			buildConfigurationList = 69FD50360881E74900E825BA /* Build configuration list for PBXProject "Make" */;
+			buildSettings = {
+			};
+			buildStyles = (
+				014CEA460018CE2711CA2923 /* Development */,
+				014CEA470018CE2711CA2923 /* Deployment */,
+			);
+			hasScannedForEncodings = 1;
+			mainGroup = 08FB7794FE84155DC02AAC07 /* sim */;
+			productRefGroup = 69E0AD5D07CBDE11008493CA /* Products */;
+			projectDirPath = "";
+			targets = (
+				8DD76F620486A84900D96B5E /* sim (ERS-7) */,
+				69E0AFA707CBF79B008493CA /* sim (ERS-7) Light */,
+				69E0AB9A07CBDE11008493CA /* sim (ERS-210) */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXSourcesBuildPhase section */
+		69E0AB9B07CBDE11008493CA /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				69E0AB9C07CBDE11008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc in Sources */,
+				69E0AB9D07CBDE11008493CA /* StartupBehavior_SetupFileAccess.cc in Sources */,
+				69E0AB9E07CBDE11008493CA /* StartupBehavior_SetupModeSwitch.cc in Sources */,
+				69E0AB9F07CBDE11008493CA /* StartupBehavior_SetupStatusReports.cc in Sources */,
+				69E0ABA007CBDE11008493CA /* StartupBehavior_SetupTekkotsuMon.cc in Sources */,
+				69E0ABA107CBDE11008493CA /* StartupBehavior_SetupVision.cc in Sources */,
+				69E0ABA207CBDE11008493CA /* StartupBehavior_SetupWalkEdit.cc in Sources */,
+				69E0ABA307CBDE11008493CA /* StartupBehavior.cc in Sources */,
+				69E0ABA507CBDE11008493CA /* Main.cc in Sources */,
+				69E0ABA607CBDE11008493CA /* Motion.cc in Sources */,
+				69E0ABA707CBDE11008493CA /* Process.cc in Sources */,
+				69E0ABA807CBDE11008493CA /* SharedGlobals.cc in Sources */,
+				69E0ABA907CBDE11008493CA /* Simulator.cc in Sources */,
+				69E0ABAA07CBDE11008493CA /* SoundPlay.cc in Sources */,
+				69E0ABAB07CBDE11008493CA /* BehaviorBase.cc in Sources */,
+				69E0ABAC07CBDE11008493CA /* Controller.cc in Sources */,
+				69E0ABAD07CBDE11008493CA /* ControlBase.cc in Sources */,
+				69E0ABAE07CBDE11008493CA /* EventLogger.cc in Sources */,
+				69E0ABAF07CBDE11008493CA /* FileBrowserControl.cc in Sources */,
+				69E0ABB007CBDE11008493CA /* FreeMemReportControl.cc in Sources */,
+				69E0ABB107CBDE11008493CA /* HelpControl.cc in Sources */,
+				69E0ABB207CBDE11008493CA /* PostureEditor.cc in Sources */,
+				69E0ABB307CBDE11008493CA /* RebootControl.cc in Sources */,
+				69E0ABB407CBDE11008493CA /* SensorObserverControl.cc in Sources */,
+				69E0ABB507CBDE11008493CA /* ShutdownControl.cc in Sources */,
+				69E0ABB607CBDE11008493CA /* StringInputControl.cc in Sources */,
+				69E0ABB707CBDE11008493CA /* WalkCalibration.cc in Sources */,
+				69E0ABB807CBDE11008493CA /* WaypointWalkControl.cc in Sources */,
+				69E0ABB907CBDE11008493CA /* ASCIIVisionBehavior.cc in Sources */,
+				69E0ABBA07CBDE11008493CA /* CameraBehavior.cc in Sources */,
+				69E0ABBB07CBDE11008493CA /* ChaseBallBehavior.cc in Sources */,
+				69E0ABBC07CBDE11008493CA /* DriveMeBehavior.cc in Sources */,
+				69E0ABBD07CBDE11008493CA /* ExploreMachine.cc in Sources */,
+				69E0ABBE07CBDE11008493CA /* FlashIPAddrBehavior.cc in Sources */,
+				69E0ABBF07CBDE11008493CA /* FollowHeadBehavior.cc in Sources */,
+				69E0ABC007CBDE11008493CA /* PaceTargetsMachine.cc in Sources */,
+				69E0ABC107CBDE11008493CA /* StareAtBallBehavior.cc in Sources */,
+				69E0ABC207CBDE11008493CA /* WallTestBehavior.cc in Sources */,
+				69E0ABC307CBDE11008493CA /* EStopControllerBehavior.cc in Sources */,
+				69E0ABC407CBDE11008493CA /* HeadPointControllerBehavior.cc in Sources */,
+				69E0ABC507CBDE11008493CA /* MicrophoneServer.cc in Sources */,
+				69E0ABC607CBDE11008493CA /* RawCamBehavior.cc in Sources */,
+				69E0ABC707CBDE11008493CA /* SegCamBehavior.cc in Sources */,
+				69E0ABC807CBDE11008493CA /* SpeakerServer.cc in Sources */,
+				69E0ABC907CBDE11008493CA /* SpiderMachineBehavior.cc in Sources */,
+				69E0ABCA07CBDE11008493CA /* WalkControllerBehavior.cc in Sources */,
+				69E0ABCB07CBDE11008493CA /* WMMonitorBehavior.cc in Sources */,
+				69E0ABCC07CBDE11008493CA /* WorldStateSerializerBehavior.cc in Sources */,
+				69E0ABCD07CBDE11008493CA /* WalkToTargetNode.cc in Sources */,
+				69E0ABCE07CBDE11008493CA /* StateNode.cc in Sources */,
+				69E0ABCF07CBDE11008493CA /* Transition.cc in Sources */,
+				69E0ABD007CBDE11008493CA /* RandomTrans.cc in Sources */,
+				69E0ABD107CBDE11008493CA /* EventBase.cc in Sources */,
+				69E0ABD207CBDE11008493CA /* EventGeneratorBase.cc in Sources */,
+				69E0ABD307CBDE11008493CA /* EventRouter.cc in Sources */,
+				69E0ABD407CBDE11008493CA /* EventTranslator.cc in Sources */,
+				69E0ABD507CBDE11008493CA /* LocomotionEvent.cc in Sources */,
+				69E0ABD607CBDE11008493CA /* TextMsgEvent.cc in Sources */,
+				69E0ABD707CBDE11008493CA /* VisionObjectEvent.cc in Sources */,
+				69E0ABD807CBDE11008493CA /* EmergencyStopMC.cc in Sources */,
+				69E0ABD907CBDE11008493CA /* HeadPointerMC.cc in Sources */,
+				69E0ABDA07CBDE11008493CA /* Kinematics.cc in Sources */,
+				69E0ABDB07CBDE11008493CA /* LedEngine.cc in Sources */,
+				69E0ABDC07CBDE11008493CA /* MotionCommand.cc in Sources */,
+				69E0ABDD07CBDE11008493CA /* MotionManager.cc in Sources */,
+				69E0ABDE07CBDE11008493CA /* MotionSequenceEngine.cc in Sources */,
+				69E0ABDF07CBDE11008493CA /* OldHeadPointerMC.cc in Sources */,
+				69E0ABE007CBDE11008493CA /* OldKinematics.cc in Sources */,
+				69E0ABE107CBDE11008493CA /* OutputCmd.cc in Sources */,
+				69E0ABE207CBDE11008493CA /* PostureEngine.cc in Sources */,
+				69E0ABE307CBDE11008493CA /* PostureMC.cc in Sources */,
+				69E0ABE407CBDE11008493CA /* clik.cpp in Sources */,
+				69E0ABE507CBDE11008493CA /* comp_dq.cpp in Sources */,
+				69E0ABE607CBDE11008493CA /* comp_dqp.cpp in Sources */,
+				69E0ABE707CBDE11008493CA /* config.cpp in Sources */,
+				69E0ABE807CBDE11008493CA /* control_select.cpp in Sources */,
+				69E0ABE907CBDE11008493CA /* controller.cpp in Sources */,
+				69E0ABEA07CBDE11008493CA /* delta_t.cpp in Sources */,
+				69E0ABEB07CBDE11008493CA /* dynamics.cpp in Sources */,
+				69E0ABEC07CBDE11008493CA /* dynamics_sim.cpp in Sources */,
+				69E0ABED07CBDE11008493CA /* gnugraph.cpp in Sources */,
+				69E0ABEE07CBDE11008493CA /* homogen.cpp in Sources */,
+				69E0ABEF07CBDE11008493CA /* invkine.cpp in Sources */,
+				69E0ABF007CBDE11008493CA /* kinemat.cpp in Sources */,
+				69E0ABF207CBDE11008493CA /* quaternion.cpp in Sources */,
+				69E0ABF307CBDE11008493CA /* robot.cpp in Sources */,
+				69E0ABF407CBDE11008493CA /* sensitiv.cpp in Sources */,
+				69E0ABF507CBDE11008493CA /* trajectory.cpp in Sources */,
+				69E0ABF607CBDE11008493CA /* utils.cpp in Sources */,
+				69E0ABF707CBDE11008493CA /* WalkMC.cc in Sources */,
+				69E0ABF807CBDE11008493CA /* Buffer.cc in Sources */,
+				69E0ABF907CBDE11008493CA /* Config.cc in Sources */,
+				69E0ABFA07CBDE11008493CA /* get_time.cc in Sources */,
+				69E0AC2607CBDE11008493CA /* jpeg_mem_dest.cc in Sources */,
+				69E0AC2B07CBDE11008493CA /* LoadSave.cc in Sources */,
+				69E0AC2C07CBDE11008493CA /* bandmat.cpp in Sources */,
+				69E0AC2D07CBDE11008493CA /* cholesky.cpp in Sources */,
+				69E0AC2E07CBDE11008493CA /* evalue.cpp in Sources */,
+				69E0AC2F07CBDE11008493CA /* fft.cpp in Sources */,
+				69E0AC3007CBDE11008493CA /* hholder.cpp in Sources */,
+				69E0AC3107CBDE11008493CA /* jacobi.cpp in Sources */,
+				69E0AC3307CBDE11008493CA /* myexcept.cpp in Sources */,
+				69E0AC3407CBDE11008493CA /* newfft.cpp in Sources */,
+				69E0AC3507CBDE11008493CA /* newmat1.cpp in Sources */,
+				69E0AC3607CBDE11008493CA /* newmat2.cpp in Sources */,
+				69E0AC3707CBDE11008493CA /* newmat3.cpp in Sources */,
+				69E0AC3807CBDE11008493CA /* newmat4.cpp in Sources */,
+				69E0AC3907CBDE11008493CA /* newmat5.cpp in Sources */,
+				69E0AC3A07CBDE11008493CA /* newmat6.cpp in Sources */,
+				69E0AC3B07CBDE11008493CA /* newmat7.cpp in Sources */,
+				69E0AC3C07CBDE11008493CA /* newmat8.cpp in Sources */,
+				69E0AC3D07CBDE11008493CA /* newmat9.cpp in Sources */,
+				69E0AC3E07CBDE11008493CA /* newmatex.cpp in Sources */,
+				69E0AC3F07CBDE11008493CA /* newmatnl.cpp in Sources */,
+				69E0AC4007CBDE11008493CA /* newmatrm.cpp in Sources */,
+				69E0AC4107CBDE11008493CA /* sort.cpp in Sources */,
+				69E0AC4207CBDE11008493CA /* submat.cpp in Sources */,
+				69E0AC4307CBDE11008493CA /* svd.cpp in Sources */,
+				69E0AC4507CBDE11008493CA /* Profiler.cc in Sources */,
+				69E0AC4607CBDE11008493CA /* ProjectInterface.cc in Sources */,
+				69E0AC4907CBDE11008493CA /* string_util.cc in Sources */,
+				69E0AC4A07CBDE11008493CA /* TimeET.cc in Sources */,
+				69E0AC4B07CBDE11008493CA /* WMclass.cc in Sources */,
+				69E0AC4C07CBDE11008493CA /* WorldState.cc in Sources */,
+				69E0AC4D07CBDE11008493CA /* SoundManager.cc in Sources */,
+				69E0AC4E07CBDE11008493CA /* WAV.cc in Sources */,
+				69E0AC4F07CBDE11008493CA /* BallDetectionGenerator.cc in Sources */,
+				69E0AC5007CBDE11008493CA /* CDTGenerator.cc in Sources */,
+				69E0AC5107CBDE11008493CA /* FilterBankGenerator.cc in Sources */,
+				69E0AC5207CBDE11008493CA /* InterleavedYUVGenerator.cc in Sources */,
+				69E0AC5307CBDE11008493CA /* JPEGGenerator.cc in Sources */,
+				69E0AC5407CBDE11008493CA /* RawCameraGenerator.cc in Sources */,
+				69E0AC5507CBDE11008493CA /* RegionGenerator.cc in Sources */,
+				69E0AC5607CBDE11008493CA /* RLEGenerator.cc in Sources */,
+				69E0AC5707CBDE11008493CA /* SegmentedColorGenerator.cc in Sources */,
+				69E0AC5807CBDE11008493CA /* Socket.cc in Sources */,
+				69E0AC5907CBDE11008493CA /* Wireless.cc in Sources */,
+				6994F3DD07D4D35F003A7628 /* SemaphoreManager.cc in Sources */,
+				6994F3DE07D4D35F003A7628 /* ProcessID.cc in Sources */,
+				6994F3DF07D4D35F003A7628 /* RCRegion.cc in Sources */,
+				6994F3E007D4D35F003A7628 /* SharedObject.cc in Sources */,
+				6942757907E0DCDD003DE3D9 /* MutexLock.cc in Sources */,
+				6942779207E164EA003DE3D9 /* Thread.cc in Sources */,
+				69A323C507E35665009D94E1 /* write_jpeg.cc in Sources */,
+				69E666BD07F0CE51005F4FA9 /* plist.cc in Sources */,
+				69E6674907F1E23A005F4FA9 /* XMLLoadSave.cc in Sources */,
+				69E6696507F3398F005F4FA9 /* SimConfig.cc in Sources */,
+				692CD63507F8C46B00604100 /* sim.cc in Sources */,
+				692CD99607F9F05500604100 /* LoadFileThread.cc in Sources */,
+				695967E407FF3DCF004FABFF /* LoadImageThread.cc in Sources */,
+				695F1ACB0804A81800ACB3D7 /* BufferedImageGenerator.cc in Sources */,
+				69A19960080ED8A200540970 /* EchoBehavior.cc in Sources */,
+				691C805708255F6300E8E256 /* Base64.cc in Sources */,
+				69970AC2083DB2760069D95C /* StewartPlatformBehavior.cc in Sources */,
+				69FA48F8084C389E0003A261 /* UPennWalkMC.cc in Sources */,
+				69FA48FF084C38E80003A261 /* Graphics.cc in Sources */,
+				69FA4900084C38E80003A261 /* RLEGraphics.cc in Sources */,
+				69FA4904084C39230003A261 /* UPennWalkControllerBehavior.cc in Sources */,
+				69AA7D6C0860898300185BA2 /* MessageReceiver.cc in Sources */,
+				69B4E447089409D900832D58 /* StareAtPawBehavior2.cc in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		69E0AFA507CBF79B008493CA /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				69E0AFAA07CBF84A008493CA /* StartupBehavior.cc in Sources */,
+				69E0AFAB07CBF84B008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc in Sources */,
+				69E0AFAC07CBF84C008493CA /* StartupBehavior_SetupFileAccess.cc in Sources */,
+				69E0AFAD07CBF84D008493CA /* StartupBehavior_SetupModeSwitch.cc in Sources */,
+				69E0AFAE07CBF84E008493CA /* StartupBehavior_SetupStatusReports.cc in Sources */,
+				69E0AFAF07CBF84E008493CA /* StartupBehavior_SetupTekkotsuMon.cc in Sources */,
+				69E0AFB007CBF84F008493CA /* StartupBehavior_SetupVision.cc in Sources */,
+				69E0AFB107CBF850008493CA /* StartupBehavior_SetupWalkEdit.cc in Sources */,
+				69E0AFB307CBF85E008493CA /* Main.cc in Sources */,
+				69E0AFB407CBF85F008493CA /* Motion.cc in Sources */,
+				69E0AFB507CBF860008493CA /* Process.cc in Sources */,
+				69E0AFB607CBF862008493CA /* SharedGlobals.cc in Sources */,
+				69E0AFB707CBF862008493CA /* Simulator.cc in Sources */,
+				69E0AFB807CBF863008493CA /* SoundPlay.cc in Sources */,
+				692CD63707F8C46B00604100 /* sim.cc in Sources */,
+				692CD99707F9F05500604100 /* LoadFileThread.cc in Sources */,
+				695967E207FF3DCF004FABFF /* LoadImageThread.cc in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		8DD76F640486A84900D96B5E /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				69E0A76407CBD4F9008493CA /* StartupBehavior_SetupBackgroundBehaviors.cc in Sources */,
+				69E0A76507CBD4F9008493CA /* StartupBehavior_SetupFileAccess.cc in Sources */,
+				69E0A76607CBD4F9008493CA /* StartupBehavior_SetupModeSwitch.cc in Sources */,
+				69E0A76707CBD4F9008493CA /* StartupBehavior_SetupStatusReports.cc in Sources */,
+				69E0A76807CBD4F9008493CA /* StartupBehavior_SetupTekkotsuMon.cc in Sources */,
+				69E0A76907CBD4F9008493CA /* StartupBehavior_SetupVision.cc in Sources */,
+				69E0A76A07CBD4F9008493CA /* StartupBehavior_SetupWalkEdit.cc in Sources */,
+				69E0A76B07CBD4F9008493CA /* StartupBehavior.cc in Sources */,
+				69E0A77D07CBD52D008493CA /* Main.cc in Sources */,
+				69E0A77F07CBD52D008493CA /* Motion.cc in Sources */,
+				69E0A78107CBD52D008493CA /* Process.cc in Sources */,
+				69E0A78407CBD52D008493CA /* SharedGlobals.cc in Sources */,
+				69E0A78607CBD52D008493CA /* Simulator.cc in Sources */,
+				69E0A78807CBD52D008493CA /* SoundPlay.cc in Sources */,
+				69E0A99507CBD6C1008493CA /* BehaviorBase.cc in Sources */,
+				69E0A99807CBD6C1008493CA /* Controller.cc in Sources */,
+				69E0A99F07CBD6C1008493CA /* ControlBase.cc in Sources */,
+				69E0A9A207CBD6C1008493CA /* EventLogger.cc in Sources */,
+				69E0A9A407CBD6C1008493CA /* FileBrowserControl.cc in Sources */,
+				69E0A9A707CBD6C1008493CA /* FreeMemReportControl.cc in Sources */,
+				69E0A9A907CBD6C1008493CA /* HelpControl.cc in Sources */,
+				69E0A9B207CBD6C1008493CA /* PostureEditor.cc in Sources */,
+				69E0A9B507CBD6C1008493CA /* RebootControl.cc in Sources */,
+				69E0A9BA07CBD6C1008493CA /* SensorObserverControl.cc in Sources */,
+				69E0A9BC07CBD6C1008493CA /* ShutdownControl.cc in Sources */,
+				69E0A9BE07CBD6C1008493CA /* StringInputControl.cc in Sources */,
+				69E0A9C307CBD6C1008493CA /* WalkCalibration.cc in Sources */,
+				69E0A9C507CBD6C1008493CA /* WaypointWalkControl.cc in Sources */,
+				69E0A9C807CBD6C1008493CA /* ASCIIVisionBehavior.cc in Sources */,
+				69E0A9CD07CBD6C1008493CA /* CameraBehavior.cc in Sources */,
+				69E0A9CF07CBD6C1008493CA /* ChaseBallBehavior.cc in Sources */,
+				69E0A9D207CBD6C1008493CA /* DriveMeBehavior.cc in Sources */,
+				69E0A9D407CBD6C1008493CA /* ExploreMachine.cc in Sources */,
+				69E0A9D607CBD6C1008493CA /* FlashIPAddrBehavior.cc in Sources */,
+				69E0A9D807CBD6C1008493CA /* FollowHeadBehavior.cc in Sources */,
+				69E0A9E407CBD6C1008493CA /* PaceTargetsMachine.cc in Sources */,
+				69E0A9E907CBD6C1008493CA /* StareAtBallBehavior.cc in Sources */,
+				69E0A9EE07CBD6C1008493CA /* WallTestBehavior.cc in Sources */,
+				69E0A9F207CBD6C1008493CA /* EStopControllerBehavior.cc in Sources */,
+				69E0A9F407CBD6C1008493CA /* HeadPointControllerBehavior.cc in Sources */,
+				69E0A9F607CBD6C1008493CA /* MicrophoneServer.cc in Sources */,
+				69E0A9F807CBD6C1008493CA /* RawCamBehavior.cc in Sources */,
+				69E0A9FA07CBD6C1008493CA /* SegCamBehavior.cc in Sources */,
+				69E0A9FC07CBD6C1008493CA /* SpeakerServer.cc in Sources */,
+				69E0A9FE07CBD6C1008493CA /* SpiderMachineBehavior.cc in Sources */,
+				69E0AA0107CBD6C2008493CA /* WalkControllerBehavior.cc in Sources */,
+				69E0AA0307CBD6C2008493CA /* WMMonitorBehavior.cc in Sources */,
+				69E0AA0507CBD6C2008493CA /* WorldStateSerializerBehavior.cc in Sources */,
+				69E0AA1007CBD6C2008493CA /* WalkToTargetNode.cc in Sources */,
+				69E0AA1307CBD6C2008493CA /* StateNode.cc in Sources */,
+				69E0AA1507CBD6C2008493CA /* Transition.cc in Sources */,
+				69E0AA1C07CBD6C2008493CA /* RandomTrans.cc in Sources */,
+				69E0AA2307CBD6C2008493CA /* EventBase.cc in Sources */,
+				69E0AA2507CBD6C2008493CA /* EventGeneratorBase.cc in Sources */,
+				69E0AA2807CBD6C2008493CA /* EventRouter.cc in Sources */,
+				69E0AA2A07CBD6C2008493CA /* EventTranslator.cc in Sources */,
+				69E0AA2E07CBD6C2008493CA /* LocomotionEvent.cc in Sources */,
+				69E0AA3107CBD6C2008493CA /* TextMsgEvent.cc in Sources */,
+				69E0AA3307CBD6C2008493CA /* VisionObjectEvent.cc in Sources */,
+				69E0AA3607CBD6C2008493CA /* EmergencyStopMC.cc in Sources */,
+				69E0AA3A07CBD6C2008493CA /* HeadPointerMC.cc in Sources */,
+				69E0AA3C07CBD6C2008493CA /* Kinematics.cc in Sources */,
+				69E0AA3E07CBD6C2008493CA /* LedEngine.cc in Sources */,
+				69E0AA4207CBD6C2008493CA /* MotionCommand.cc in Sources */,
+				69E0AA4407CBD6C2008493CA /* MotionManager.cc in Sources */,
+				69E0AA4707CBD6C2008493CA /* MotionSequenceEngine.cc in Sources */,
+				69E0AA4A07CBD6C2008493CA /* OldHeadPointerMC.cc in Sources */,
+				69E0AA4C07CBD6C2008493CA /* OldKinematics.cc in Sources */,
+				69E0AA4E07CBD6C2008493CA /* OutputCmd.cc in Sources */,
+				69E0AA5307CBD6C2008493CA /* PostureEngine.cc in Sources */,
+				69E0AA5507CBD6C2008493CA /* PostureMC.cc in Sources */,
+				69E0AA5807CBD6C2008493CA /* clik.cpp in Sources */,
+				69E0AA5A07CBD6C2008493CA /* comp_dq.cpp in Sources */,
+				69E0AA5B07CBD6C2008493CA /* comp_dqp.cpp in Sources */,
+				69E0AA5C07CBD6C2008493CA /* config.cpp in Sources */,
+				69E0AA5E07CBD6C2008493CA /* control_select.cpp in Sources */,
+				69E0AA6007CBD6C2008493CA /* controller.cpp in Sources */,
+				69E0AA6207CBD6C2008493CA /* delta_t.cpp in Sources */,
+				69E0AA6307CBD6C2008493CA /* dynamics.cpp in Sources */,
+				69E0AA6407CBD6C2008493CA /* dynamics_sim.cpp in Sources */,
+				69E0AA7807CBD6C2008493CA /* gnugraph.cpp in Sources */,
+				69E0AA7A07CBD6C2008493CA /* homogen.cpp in Sources */,
+				69E0AA7B07CBD6C2008493CA /* invkine.cpp in Sources */,
+				69E0AA7C07CBD6C2008493CA /* kinemat.cpp in Sources */,
+				69E0AA7E07CBD6C2008493CA /* quaternion.cpp in Sources */,
+				69E0AA8507CBD6C2008493CA /* sensitiv.cpp in Sources */,
+				69E0AA8607CBD6C2008493CA /* trajectory.cpp in Sources */,
+				69E0AA8807CBD6C2008493CA /* utils.cpp in Sources */,
+				69E0AA8C07CBD6C2008493CA /* WalkMC.cc in Sources */,
+				69E0AA9007CBD6C2008493CA /* Buffer.cc in Sources */,
+				69E0AA9307CBD6C2008493CA /* Config.cc in Sources */,
+				69E0AA9B07CBD6C2008493CA /* get_time.cc in Sources */,
+				69E0AADB07CBD6C2008493CA /* jpeg_mem_dest.cc in Sources */,
+				69E0AAF507CBD6C2008493CA /* LoadSave.cc in Sources */,
+				69E0AAFA07CBD6C2008493CA /* bandmat.cpp in Sources */,
+				69E0AAFC07CBD6C2008493CA /* cholesky.cpp in Sources */,
+				69E0AB0107CBD6C2008493CA /* evalue.cpp in Sources */,
+				69E0AB3107CBD6C2008493CA /* fft.cpp in Sources */,
+				69E0AB3207CBD6C2008493CA /* hholder.cpp in Sources */,
+				69E0AB3407CBD6C2008493CA /* jacobi.cpp in Sources */,
+				69E0AB3607CBD6C2008493CA /* myexcept.cpp in Sources */,
+				69E0AB3807CBD6C2008493CA /* newfft.cpp in Sources */,
+				69E0AB3A07CBD6C2008493CA /* newmat1.cpp in Sources */,
+				69E0AB3B07CBD6C2008493CA /* newmat2.cpp in Sources */,
+				69E0AB3C07CBD6C2008493CA /* newmat3.cpp in Sources */,
+				69E0AB3D07CBD6C2008493CA /* newmat4.cpp in Sources */,
+				69E0AB3E07CBD6C2008493CA /* newmat5.cpp in Sources */,
+				69E0AB3F07CBD6C2008493CA /* newmat6.cpp in Sources */,
+				69E0AB4007CBD6C2008493CA /* newmat7.cpp in Sources */,
+				69E0AB4107CBD6C2008493CA /* newmat8.cpp in Sources */,
+				69E0AB4207CBD6C2008493CA /* newmat9.cpp in Sources */,
+				69E0AB4407CBD6C2008493CA /* newmatex.cpp in Sources */,
+				69E0AB4607CBD6C2008493CA /* newmatnl.cpp in Sources */,
+				69E0AB4907CBD6C2008493CA /* newmatrm.cpp in Sources */,
+				69E0AB4D07CBD6C2008493CA /* sort.cpp in Sources */,
+				69E0AB4E07CBD6C2008493CA /* submat.cpp in Sources */,
+				69E0AB4F07CBD6C2008493CA /* svd.cpp in Sources */,
+				69E0AB5307CBD6C2008493CA /* Profiler.cc in Sources */,
+				69E0AB5507CBD6C2008493CA /* ProjectInterface.cc in Sources */,
+				69E0AB5E07CBD6C2008493CA /* string_util.cc in Sources */,
+				69E0AB6107CBD6C2008493CA /* TimeET.cc in Sources */,
+				69E0AB6407CBD6C2008493CA /* WMclass.cc in Sources */,
+				69E0AB6607CBD6C2008493CA /* WorldState.cc in Sources */,
+				69E0AB6807CBD6C2008493CA /* SoundManager.cc in Sources */,
+				69E0AB6B07CBD6C2008493CA /* WAV.cc in Sources */,
+				69E0AB6D07CBD6C2008493CA /* BallDetectionGenerator.cc in Sources */,
+				69E0AB6F07CBD6C2008493CA /* CDTGenerator.cc in Sources */,
+				69E0AB7607CBD6C2008493CA /* FilterBankGenerator.cc in Sources */,
+				69E0AB7807CBD6C2008493CA /* InterleavedYUVGenerator.cc in Sources */,
+				69E0AB7A07CBD6C2008493CA /* JPEGGenerator.cc in Sources */,
+				69E0AB7D07CBD6C2008493CA /* RawCameraGenerator.cc in Sources */,
+				69E0AB7F07CBD6C2008493CA /* RegionGenerator.cc in Sources */,
+				69E0AB8107CBD6C2008493CA /* RLEGenerator.cc in Sources */,
+				69E0AB8307CBD6C2008493CA /* SegmentedColorGenerator.cc in Sources */,
+				69E0AB8707CBD6C2008493CA /* Socket.cc in Sources */,
+				69E0AB8907CBD6C2008493CA /* Wireless.cc in Sources */,
+				6994F3D907D4D35F003A7628 /* SemaphoreManager.cc in Sources */,
+				6994F3DA07D4D35F003A7628 /* ProcessID.cc in Sources */,
+				6994F3DB07D4D35F003A7628 /* RCRegion.cc in Sources */,
+				6994F3DC07D4D35F003A7628 /* SharedObject.cc in Sources */,
+				6942757807E0DCDD003DE3D9 /* MutexLock.cc in Sources */,
+				6942779107E164EA003DE3D9 /* Thread.cc in Sources */,
+				69A323C207E3564F009D94E1 /* write_jpeg.cc in Sources */,
+				69E666BC07F0CE51005F4FA9 /* plist.cc in Sources */,
+				69E6674A07F1E23A005F4FA9 /* XMLLoadSave.cc in Sources */,
+				69E6696607F3398F005F4FA9 /* SimConfig.cc in Sources */,
+				692CD63607F8C46B00604100 /* sim.cc in Sources */,
+				692CD99807F9F05500604100 /* LoadFileThread.cc in Sources */,
+				695967E307FF3DCF004FABFF /* LoadImageThread.cc in Sources */,
+				695F1ACA0804A81800ACB3D7 /* BufferedImageGenerator.cc in Sources */,
+				69A1995F080ED8A200540970 /* EchoBehavior.cc in Sources */,
+				691C805608255F6300E8E256 /* Base64.cc in Sources */,
+				69970AC1083DB2760069D95C /* StewartPlatformBehavior.cc in Sources */,
+				69FA48F7084C389E0003A261 /* UPennWalkMC.cc in Sources */,
+				69FA48FD084C38E80003A261 /* Graphics.cc in Sources */,
+				69FA48FE084C38E80003A261 /* RLEGraphics.cc in Sources */,
+				69FA4903084C39230003A261 /* UPennWalkControllerBehavior.cc in Sources */,
+				69AA7D6B0860898300185BA2 /* MessageReceiver.cc in Sources */,
+				69B4E446089409D900832D58 /* StareAtPawBehavior2.cc in Sources */,
+				69B4E6D50895E34F00832D58 /* robot.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin XCBuildConfiguration section */
+		69FD502B0881E74900E825BA /* Development */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				COPY_PHASE_STRIP = NO;
+				DEPLOYMENT_LOCATION = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					PLATFORM_LOCAL,
+					DEBUG,
+					HAVE_READDIR_R,
+				);
+				GCC_USE_GCC3_PFE_SUPPORT = YES;
+				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
+				GCC_WARN_ABOUT_RETURN_TYPE = NO;
+				GCC_WARN_CHECK_SWITCH_STATEMENTS = YES;
+				GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES;
+				GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
+				GCC_WARN_MISSING_PARENTHESES = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_SIGN_COMPARE = YES;
+				GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_LABEL = YES;
+				GCC_WARN_UNUSED_PARAMETER = YES;
+				GCC_WARN_UNUSED_VALUE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				GENERATE_PROFILING_CODE = YES;
+				HEADER_SEARCH_PATHS = (
+					"$(TEKKOTSU_ROOT)",
+					/usr/include/libxml2,
+				);
+				INSTALL_PATH = "$(HOME)/bin";
+				OBJROOT = build;
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS7";
+				PREBINDING = NO;
+				PRECOMPS_INCLUDE_HEADERS_FROM_BUILT_PRODUCTS_DIR = NO;
+				PRODUCT_NAME = "sim-ERS7";
+				SYMROOT = .;
+				UNSTRIPPED_PRODUCT = YES;
+				WARNING_CFLAGS = (
+					"-Wall",
+					"-W",
+					"-Wpointer-arith",
+					"-Wcast-qual",
+					"-Woverloaded-virtual",
+					"-Wdeprecated",
+				);
+			};
+			name = Development;
+		};
+		69FD502C0881E74900E825BA /* Deployment */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				COPY_PHASE_STRIP = YES;
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = PLATFORM_LOCAL;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES;
+				HEADER_SEARCH_PATHS = "$(TEKKOTSU_ROOT)";
+				INSTALL_PATH = "$(HOME)/bin";
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS7";
+				PRODUCT_NAME = "sim-ERS7";
+				ZERO_LINK = NO;
+			};
+			name = Deployment;
+		};
+		69FD502F0881E74900E825BA /* Development */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					PLATFORM_LOCAL,
+					DEBUG,
+					HAVE_READDIR_R,
+				);
+				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
+				GCC_WARN_CHECK_SWITCH_STATEMENTS = YES;
+				GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES;
+				GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
+				GCC_WARN_MISSING_PARENTHESES = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_SHADOW = NO;
+				GCC_WARN_SIGN_COMPARE = YES;
+				GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_LABEL = YES;
+				GCC_WARN_UNUSED_PARAMETER = YES;
+				GCC_WARN_UNUSED_VALUE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				GENERATE_PROFILING_CODE = YES;
+				HEADER_SEARCH_PATHS = (
+					"$(TEKKOTSU_ROOT)",
+					/usr/include/libxml2,
+				);
+				INSTALL_PATH = /usr/local/bin;
+				OBJROOT = build;
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS7";
+				PREBINDING = NO;
+				PRODUCT_NAME = "sim-ERS7";
+				SYMROOT = "";
+				WARNING_CFLAGS = (
+					"-Wall",
+					"-W",
+					"-Wpointer-arith",
+					"-Wcast-qual",
+					"-Woverloaded-virtual",
+					"-Wdeprecated",
+				);
+			};
+			name = Development;
+		};
+		69FD50300881E74900E825BA /* Deployment */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				COPY_PHASE_STRIP = YES;
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = PLATFORM_LOCAL;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES;
+				HEADER_SEARCH_PATHS = "$(TEKKOTSU_ROOT)";
+				INSTALL_PATH = /usr/local/bin;
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS7";
+				PRODUCT_NAME = "sim-ERS7";
+				ZERO_LINK = NO;
+			};
+			name = Deployment;
+		};
+		69FD50330881E74900E825BA /* Development */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_ENABLE_FIX_AND_CONTINUE = YES;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_GENERATE_DEBUGGING_SYMBOLS = YES;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					PLATFORM_LOCAL,
+					DEBUG,
+					HAVE_READDIR_R,
+				);
+				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
+				GCC_WARN_CHECK_SWITCH_STATEMENTS = YES;
+				GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES;
+				GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
+				GCC_WARN_MISSING_PARENTHESES = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_SHADOW = NO;
+				GCC_WARN_SIGN_COMPARE = YES;
+				GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_LABEL = YES;
+				GCC_WARN_UNUSED_PARAMETER = YES;
+				GCC_WARN_UNUSED_VALUE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				GENERATE_PROFILING_CODE = YES;
+				HEADER_SEARCH_PATHS = (
+					"$(TEKKOTSU_ROOT)",
+					/usr/include/libxml2,
+				);
+				INSTALL_PATH = "$(HOME)/bin";
+				OBJROOT = build;
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS210";
+				PREBINDING = NO;
+				PRODUCT_NAME = "sim-ERS210";
+				SYMROOT = "";
+				WARNING_CFLAGS = (
+					"-Wall",
+					"-W",
+					"-Wpointer-arith",
+					"-Wcast-qual",
+					"-Woverloaded-virtual",
+					"-Wdeprecated",
+				);
+			};
+			name = Development;
+		};
+		69FD50340881E74900E825BA /* Deployment */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				COPY_PHASE_STRIP = YES;
+				GCC_ENABLE_FIX_AND_CONTINUE = NO;
+				GCC_ENABLE_PASCAL_STRINGS = NO;
+				GCC_PRECOMPILE_PREFIX_HEADER = YES;
+				GCC_PREFIX_HEADER = "$(TEKKOTSU_ROOT)/common.h";
+				GCC_PREPROCESSOR_DEFINITIONS = PLATFORM_LOCAL;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES;
+				HEADER_SEARCH_PATHS = "$(TEKKOTSU_ROOT)";
+				INSTALL_PATH = "$(HOME)/bin";
+				OTHER_CPLUSPLUSFLAGS = "-DTGT_ERS210";
+				PRODUCT_NAME = "sim-ERS210";
+				ZERO_LINK = NO;
+			};
+			name = Deployment;
+		};
+		69FD50370881E74900E825BA /* Development */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				DEPLOYMENT_LOCATION = YES;
+				DSTROOT = build;
+			};
+			name = Development;
+		};
+		69FD50380881E74900E825BA /* Deployment */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+			};
+			name = Deployment;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		69FD502A0881E74900E825BA /* Build configuration list for PBXNativeTarget "sim (ERS-7)" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				69FD502B0881E74900E825BA /* Development */,
+				69FD502C0881E74900E825BA /* Deployment */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Development;
+		};
+		69FD502E0881E74900E825BA /* Build configuration list for PBXNativeTarget "sim (ERS-7) Light" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				69FD502F0881E74900E825BA /* Development */,
+				69FD50300881E74900E825BA /* Deployment */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Development;
+		};
+		69FD50320881E74900E825BA /* Build configuration list for PBXNativeTarget "sim (ERS-210)" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				69FD50330881E74900E825BA /* Development */,
+				69FD50340881E74900E825BA /* Deployment */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Development;
+		};
+		69FD50360881E74900E825BA /* Build configuration list for PBXProject "Make" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				69FD50370881E74900E825BA /* Development */,
+				69FD50380881E74900E825BA /* Deployment */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Development;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
+}
diff -urdN ../Tekkotsu_2.3/project/Makefile ./project/Makefile
--- ../Tekkotsu_2.3/project/Makefile	Tue Jan 18 18:25:14 2005
+++ ./project/Makefile	Wed Jul  6 18:53:29 2005
@@ -1,7 +1,9 @@
 ################ PROJECT MAKEFILE #################
-############# $Name: tekkotsu-2_3 $ ###############
-############### $Revision: 1.98 $ #################
-########## $Date: 2005/01/18 23:25:14 $ ###########
+############# $Name: tekkotsu-2_4 $ ###############
+############### $Revision: 1.105 $ #################
+########## $Date: 2005/07/06 22:53:29 $ ###########
+############### $Revision: 1.105 $ #################
+########## $Date: 2005/07/06 22:53:29 $ ###########
 
 # Make sure the default target is 'all' by listing it first
 all:
@@ -10,6 +12,12 @@
 ##             ENVIRONMENT SETUP                 ##
 ###################################################
 TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(shell pwd | sed 's/ /\\ /g')/Environment.conf
+ifneq ($(filter sim%,$(MAKECMDGOALS)),)
+	TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+	ifneq ($(filter sim-%,$(MAKECMDGOALS)),)
+		TEKKOTSU_TARGET_MODEL:=$(patsubst sim-%,TGT_%,$(filter sim-%,$(MAKECMDGOALS)))
+	endif
+endif
 include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
 $(shell mkdir -p $(PROJ_BD))
 
@@ -28,262 +36,152 @@
 	  -isystem $(OPENRSDK_ROOT)/OPEN_R/include/MCOOP \
 	  -isystem $(OPENRSDK_ROOT)/OPEN_R/include/R4000 \
 	  -isystem $(OPENRSDK_ROOT)/OPEN_R/include \
-	  -DOPENR_DEBUG
+	  -isystem $(TEKKOTSU_ROOT)/aperios/include \
+	  $(if $(TEKKOTSU_DEBUG),-DOPENR_DEBUG,) \
+	  `$(TEKKOTSU_ROOT)/aperios/bin/xml2-config --cflags`
+  LDFLAGS=-lObjectComm -lOPENR  -lInternet -lantMCOOP -lERA201D1 \
+	  `$(TEKKOTSU_ROOT)/aperios/bin/xml2-config --libs` -ljpeg
 else
-  PLATFORM_FLAGS=
+  PLATFORM_FLAGS=`xml2-config --cflags`
+  LDFLAGS=`xml2-config --libs` $(if $(shell locate librt.a),-lrt) -ljpeg
 endif
 
 CXXFLAGS= \
-	-g -pipe -fno-inline \
-	-O2 -frename-registers -fomit-frame-pointer -ffast-math -fno-common \
+	$(if $(TEKKOTSU_DEBUG),-g -fno-inline -DDEBUG,) \
+	$(if $(TEKKOTSU_DEBUG),,-O2 -frename-registers -fomit-frame-pointer) \
+	-pipe -ffast-math -fno-common \
 	-Wall -W -Wshadow -Wlarger-than-8192 -Wpointer-arith -Wcast-qual \
 	-Woverloaded-virtual -Weffc++ -Wdeprecated -Wnon-virtual-dtor \
-	-I$(TEKKOTSU_ROOT) -I$(TEKKOTSU_ROOT)/Motion/roboop \
+	-I. -I$(TEKKOTSU_ROOT) -I$(TEKKOTSU_ROOT)/Motion/roboop \
 	-I$(TEKKOTSU_ROOT)/Shared/newmat \
 	-isystem $(TEKKOTSU_ROOT)/Shared/jpeg-6b \
 	-D$(TEKKOTSU_TARGET_PLATFORM)  -D$(TEKKOTSU_TARGET_MODEL) \
-	-DDEBUG $(PLATFORM_FLAGS)
+	$(PLATFORM_FLAGS)
+
+INCLUDE_PCH=$(if $(TEKKOTSU_PCH),-include $(TK_BD)/$(TEKKOTSU_PCH))
 
 
 ###################################################
 ##              SOURCE CODE LIST                 ##
 ###################################################
 
-# Find all of the source files: (except temp files in build directory)
+# Find all of the source files: (except temp files in build directory,
+# or platform-specific files in either aperios or sim)
 # You shouldn't need to change anything here unless you want to add
 # external libraries
 SRCSUFFIX=.cc
-PROJ_SRCS:=$(patsubst ./%,%,$(shell find . -name "*$(SRCSUFFIX)" -or -name "$(PROJECT_BUILDDIR)" \! -prune -or -name "templates" \! -prune))
-
-# We're assuming all of the source files we found are to be linked
-# into MMCombo.
-MAIN_SRCS:=$(PROJ_SRCS)
-
-# We can also link in third-party libraries (path relative to Tekkotsu root)
-# You'll need to specify which processes need which libraries in the next section
-USERLIBS:= $(TK_BD)/Shared/jpeg-6b \
-           $(TK_BD)/Motion/roboop \
-           $(TK_BD)/Shared/newmat \
+SRCS:=$(patsubst ./%,%,$(shell find . -name "*$(SRCSUFFIX)" -or -name "$(PROJECT_BUILDDIR)" \! -prune -or -name "templates" \! -prune -or -name "aperios" \! -prune -or -name "local" \! -prune))
 
-# These system libs are expected to already be compiled, will be linked
-# into all processes... if you only want to link into a single process,
-# see the *_LIBS variables of the next section
-LIBS=-lObjectComm -lOPENR
+# We can also link in third-party libraries
+USERLIBS:= $(TK_BD)/libtekkotsu.a \
+           $(TK_LIB_BD)/Motion/roboop/libroboop.a \
+           $(TK_LIB_BD)/Shared/newmat/libnewmat.a \
 
 
 ###################################################
-##               PROCESS SETUP                   ##
+##             MAKEFILE MACHINERY                ##
 ###################################################
-# This part will set up the four processes:
-# MMCombo is forked into Main and Motion
-# TinyFTPD is the FTP server
-# SoundPlay handles sound output
-
-# It should be pretty easy to add a new process here if
-# you're inclined to do so.
-
-# These all are relative to TEKKOTSU_ROOT
-PROCESS_OBJS=MMCombo TinyFTPD SoundPlay
-
-# These specify the components of each process - list either individual
-# object files or entire directories
-MMCombo_COMP=MMCombo MMCombo/MMComboStub.o Behaviors Events Motion Shared SoundPlay/SoundManager.o SoundPlay/WAV.o Vision Wireless
-TinyFTPD_COMP=TinyFTPD TinyFTPD/TinyFTPDStub.o
-SoundPlay_COMP=SoundPlay SoundPlay/SoundPlayStub.o Shared/Config.o Shared/ProcessID.o Events/EventRouter.o Events/EventTranslator.o Events/EventBase.o Events/LocomotionEvent.o Events/TextMsgEvent.o Events/VisionObjectEvent.o Shared/LoadSave.o Shared/get_time.o
-
-# These just set up the automatically generated stub files
-STUB_FILES:=$(addprefix $(TEKKOTSU_ROOT)/,$(addsuffix /stub.cfg,$(PROCESS_OBJS)))
-STUB_CHECK_FILES:=$(addprefix $(TK_BD)/,$(subst /,-,$(STUB_FILES)))
+# Hopefully, you shouldn't have to change anything down here,
+# except one or two little things ;)
 
-# It's important that the process names and variables are the same
-# case as your memory stick reader - memsticks don't store case, and
-# some drivers may convert all file names to uppercase, others to
-# lower case.  Ours is lower case.  I think this only really matters
-# if you want to update a stick instead of recopying it (make update
-# vs. make install)
+.PHONY: all compile clean cleanDeps cleanProj reportTarget checkLibs testLibs buildLibs sim
 
-ifeq ($(FILENAME_CASE),lower)
-  PROCESSES=mmcombo tinyftpd sndplay
-  mmcombo_OBJS:=$(addprefix $(PROJ_BD)/,$(MAIN_SRCS:$(SRCSUFFIX)=.o)) $(TK_BD)/MMCombo/MMComboStub.o
-  mmcombo_LIBS:=$(addprefix $(TK_BD)/,MMCombo.a Motion/roboop/libroboop.a Shared/newmat/libnewmat.a Shared/jpeg-6b/libjpeg.a) -lInternet -lantMCOOP -lERA201D1 
-  mmcombo_OCF:=$(TEKKOTSU_ROOT)/MMCombo/MMCombo.ocf
-  tinyftpd_OBJS:=$(TK_BD)/TinyFTPD/TinyFTPDStub.o
-  tinyftpd_LIBS:=$(addprefix $(TK_BD)/, TinyFTPD.a ) -lInternet -lantMCOOP
-  tinyftpd_OCF:=$(TEKKOTSU_ROOT)/TinyFTPD/TinyFTPD.ocf
-  sndplay_OBJS:=$(TK_BD)/SoundPlay/SoundPlayStub.o
-  sndplay_LIBS:=$(addprefix $(TK_BD)/, SoundPlay.a )
-  sndplay_OCF:=$(TEKKOTSU_ROOT)/SoundPlay/SoundPlay.ocf
-  CONVERTCASE=$(TEKKOTSU_ROOT)/tools/makelowercase
-  BINSUFFIX=.bin
-  MSIMGDIR=ms
-  INSTALLDIR=$(MSIMGDIR)/open-r/mw/objs
-  MMCOMBOBIN=mmcombo.bin
-  MAINFORK=mainobj.bin
-  MOTOFORK=motoobj.bin
-else
-  PROCESSES=MMCOMBO TINYFTPD SNDPLAY
-  MMCOMBO_OBJS:=$(addprefix $(PROJ_BD)/,$(MAIN_SRCS:$(SRCSUFFIX)=.o)) $(TK_BD)/MMCombo/MMComboStub.o
-  MMCOMBO_LIBS:=$(addprefix $(TK_BD)/,MMCombo.a Motion/roboop/libroboop.a Shared/newmat/libnewmat.a Shared/jpeg-6b/libjpeg.a) -lInternet -lantMCOOP -lERA201D1 
-  MMCOMBO_OCF:=$(TEKKOTSU_ROOT)/MMCombo/MMCombo.ocf
-  TINYFTPD_OBJS:=$(TK_BD)/TinyFTPD/TinyFTPDStub.o
-  TINYFTPD_LIBS:=$(addprefix $(TK_BD)/, TinyFTPD.a ) -lInternet -lantMCOOP 
-  TINYFTPD_OCF:=$(TEKKOTSU_ROOT)/TinyFTPD/TinyFTPD.ocf
-  SNDPLAY_OBJS:=$(TK_BD)/SoundPlay/SoundPlayStub.o
-  SNDPLAY_LIBS:=$(addprefix $(TK_BD)/, SoundPlay.a )
-  SNDPLAY_OCF:=$(TEKKOTSU_ROOT)/SoundPlay/SoundPlay.ocf
-  CONVERTCASE=$(TEKKOTSU_ROOT)/tools/makeuppercase
-  BINSUFFIX=.BIN
-  MSIMGDIR=MS
-  INSTALLDIR=$(MSIMGDIR)/OPEN-R/MW/OBJS
-  MMCOMBOBIN=MMCOMBO.BIN
-  MAINFORK=MAINOBJ.BIN
-  MOTOFORK=MOTOOBJ.BIN
+sim all: reportTarget checkLibs compile
+ifeq ($(TEKKOTSU_TARGET_PLATFORM),PLATFORM_APERIOS)
+	@echo "Type: '$(MAKE) install' to copy all files to the memory stick";
+	@echo "  or: '$(MAKE) update' to copy only changed files";
+	@echo "  or: '$(TEKKOTSU_ROOT)/tools/{ftpinstall,ftpupdate} <ipaddr> ms' might also be useful";
 endif
+	@echo "Build successful."
 
-# creates process build target names: MMCombo -> build/MMCombo.a
-BUILDS:=$(foreach proc,$(PROCESS_OBJS),$(TK_BD)/$(proc).a)
-
-# Each process build target depends on the component object files that
-# should be linked together.  These live in the $TK_BD directory and
-# should be fairly static unless you're editing the framework itself.
-# The automatic way of creating these dependancies automatically is
-# too messy, just add a rule for each process by hand: (skip lines!)
-$(word 1,$(BUILDS)): $(foreach comp,$($(word 1,$(PROCESS_OBJS))_COMP), $(if $(suffix $(comp)),$(TK_BD)/$(comp),$(patsubst $(TEKKOTSU_ROOT)%.cc,$(TK_BD)%.o,$(shell find "$(TEKKOTSU_ROOT)/$(comp)" -name "*.cc") )))
-
-$(word 2,$(BUILDS)): $(foreach comp,$($(word 2,$(PROCESS_OBJS))_COMP), $(if $(suffix $(comp)),$(TK_BD)/$(comp),$(patsubst $(TEKKOTSU_ROOT)%.cc,$(TK_BD)%.o,$(shell find "$(TEKKOTSU_ROOT)/$(comp)" -name "*.cc") )))
-
-$(word 3,$(BUILDS)): $(foreach comp,$($(word 3,$(PROCESS_OBJS))_COMP), $(if $(suffix $(comp)),$(TK_BD)/$(comp),$(patsubst $(TEKKOTSU_ROOT)%.cc,$(TK_BD)%.o,$(shell find "$(TEKKOTSU_ROOT)/$(comp)" -name "*.cc") )))
-
-# Each of the executable binaries depends on the corresponding
-# framework build target(s) plus any project files which were
-# specified above. (by default, all project files are linked into
-# MMCombo) These live in the project directory's build dir and will
-# need to be recompiled any time you change source that's part of that
-# process (but not otherwise ;)
-# Again, the automatic way of creating these dependancies
-# automatically is too messy, just add a rule for each process by
-# hand: (skip lines!)
-PROC_BINS:=$(addprefix $(PROJ_BD)/,$(addsuffix $(BINSUFFIX),$(PROCESSES)))
+# Don't want to try to remake this - give an error if not found
+$(TEKKOTSU_ROOT)/project/Environment.conf:
+	@echo "Could not find Environment file - check the default project directory still exists"
+	@exit 1
 
-$(word 1,$(PROC_BINS)): $($(word 1,$(PROCESSES))_OBJS) $(filter-out -l%,$($(word 1,$(PROCESSES))_LIBS)) $($(word 1,$(PROCESSES))_OCF)
+checkLibs: $(if $(TEKKOTSU_ALWAYS_BUILD),buildLibs,testLibs)
 
-$(word 2,$(PROC_BINS)): $($(word 2,$(PROCESSES))_OBJS) $(filter-out -l%,$($(word 2,$(PROCESSES))_LIBS)) $($(word 2,$(PROCESSES))_OCF)
+ifeq ($(TEKKOTSU_ALWAYS_BUILD),)
+%/libtekkotsu.a:
+	echo "It appears that the framework itself has not been compiled."; \
+	echo "TEKKOTSU_ROOT = $(TEKKOTSU_ROOT)"; \
+	echo "TK_BD = $(TK_BD)"; \
+	echo "Press enter to compile it now, ctl-C to cancel."; \
+	read; \
+	export TEKKOTSU_ENVIRONMENT_CONFIGURATION=$(TEKKOTSU_ENVIRONMENT_CONFIGURATION); \
+	$(MAKE) TEKKOTSU_TARGET_MODEL=$(TEKKOTSU_TARGET_MODEL) TEKKOTSU_TARGET_PLATFORM=$(TEKKOTSU_TARGET_PLATFORM) -C "$(TEKKOTSU_ROOT)" compile ;
 
-$(word 3,$(PROC_BINS)): $($(word 3,$(PROCESSES))_OBJS) $(filter-out -l%,$($(word 3,$(PROCESSES))_LIBS)) $($(word 3,$(PROCESSES))_OCF)
+else
+%/libtekkotsu.a:
+	@echo "Updating framework build...";
+	@export TEKKOTSU_ENVIRONMENT_CONFIGURATION=$(TEKKOTSU_ENVIRONMENT_CONFIGURATION); \
+	$(MAKE) TEKKOTSU_TARGET_MODEL=$(TEKKOTSU_TARGET_MODEL) TEKKOTSU_TARGET_PLATFORM=$(TEKKOTSU_TARGET_PLATFORM) -C "$(TEKKOTSU_ROOT)" compile ; 
 
+endif
 
-###################################################
-##             MAKEFILE MACHINERY                ##
-###################################################
-# Hopefully, you shouldn't have to change anything down here,
-# except one or two little things ;)
+testLibs:
+	@broken=false; \
+	for x in $(USERLIBS) ; do \
+		if [ \! -r "$$x" ] ; then \
+			echo "Could not read framework library '$$x'"; \
+			broken=true; \
+		fi; \
+	done; \
+	if $$broken ; then \
+		echo "It appears that the framework itself has not been compiled."; \
+		echo "TEKKOTSU_ROOT = $(TEKKOTSU_ROOT)"; \
+		echo "TK_BD = $(TK_BD)"; \
+		echo "Press enter to compile it now, ctl-C to cancel."; \
+		read; \
+		export TEKKOTSU_ENVIRONMENT_CONFIGURATION=$(TEKKOTSU_ENVIRONMENT_CONFIGURATION); \
+		$(MAKE) TEKKOTSU_TARGET_MODEL=$(TEKKOTSU_TARGET_MODEL) TEKKOTSU_TARGET_PLATFORM=$(TEKKOTSU_TARGET_PLATFORM) -C "$(TEKKOTSU_ROOT)" compile ; \
+	fi;
 
-# Location of Aperios (the Aibo's OS) binary executables
-SYSTEM_BINARIES:=$(OPENRSDK_ROOT)/OPEN_R/MS_$(if $(findstring $(TEKKOTSU_TARGET_MODEL),TGT_ERS7),ERS7,ERS200)/WCONSOLE/nomemprot
+buildLibs:
+	@echo "Updating framework build...";
+	@export TEKKOTSU_ENVIRONMENT_CONFIGURATION=$(TEKKOTSU_ENVIRONMENT_CONFIGURATION); \
+	$(MAKE) TEKKOTSU_TARGET_MODEL=$(TEKKOTSU_TARGET_MODEL) TEKKOTSU_TARGET_PLATFORM=$(TEKKOTSU_TARGET_PLATFORM) -C "$(TEKKOTSU_ROOT)" compile ; 
 
-# List of all components for all processes, sorted to
-# remove duplicates.
-COMPONENTS:=$(sort $(foreach proc,$(PROCESS_OBJS),$($(proc)_COMP)))
+# The object file for each of the source files
+OBJS:=$(addprefix $(PROJ_BD)/,$(SRCS:$(SRCSUFFIX)=.o))
 
 # list of all source files of all components, sorted to remove
 # duplicates.  This gives us all the source files which we care about,
 # all in one place.
-TK_SRCS:=$(sort $(foreach comp,$(COMPONENTS), $(if $(suffix $(filter-out %.a,$(comp))),$(TEKKOTSU_ROOT)/$(basename $(comp)).cc,$(shell find $(TEKKOTSU_ROOT)/$(comp) -name "*.cc") )))
-TK_DEPENDS:=$(subst $(TEKKOTSU_ROOT),$(TK_BD),$(TK_SRCS:$(SRCSUFFIX)=.d))
-PROJ_DEPENDS:=$(addprefix $(PROJ_BD)/,$(PROJ_SRCS:$(SRCSUFFIX)=.d))
-DEPENDS:=$(sort $(PROJ_DEPENDS) $(TK_DEPENDS))
-
-# These are the file names of the final executable binaries, in the
-# memstick image directory
-INSTALL_BINS:=$(addprefix $(INSTALLDIR)/,$(MAINFORK) $(MOTOFORK) $(addsuffix $(BINSUFFIX),$(filter-out mmcombo MMCOMBO,$(PROCESSES))))
-
-.PHONY: all compile install clean cleanDeps cleanProj cleanTemps Tekkotsu reportTarget newstick update docs dox doc cleandoc updateTools updateLibs $(USERLIBS) checkInstallBinTimestamp test
-
-all: compile
-	@echo "Build successful."
-	@echo "Type: '$(MAKE) install' to copy all files to the memory stick"
-	@echo "  or: '$(MAKE) update' to copy only changed files"
-	@echo "  or: '$(TEKKOTSU_ROOT)/tools/{ftpinstall,ftpupdate} <ipaddr> ms' might also be useful"
-
-reportTarget:
-	@echo " ** Targeting $(TEKKOTSU_TARGET_MODEL) for build on $(TEKKOTSU_TARGET_PLATFORM) ** ";
-
-updateTools:
-	cd $(TEKKOTSU_ROOT)/tools && $(MAKE);
+DEPENDS:=$(addprefix $(PROJ_BD)/,$(SRCS:$(SRCSUFFIX)=.d))
 
-updateLibs: $(USERLIBS)
+ifeq ($(TEKKOTSU_TARGET_PLATFORM),PLATFORM_APERIOS)
 
-$(USERLIBS):
-	@printf "$(notdir $@): "; \
-	export TEKKOTSU_ENVIRONMENT_CONFIGURATION="$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)"; \
-	$(MAKE) -C $(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$@)
+include aperios/Makefile.aperios
 
-$(TK_BD)/%.a:
-	@export TEKKOTSU_ENVIRONMENT_CONFIGURATION="$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)"; \
-	$(MAKE) -C $(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$(dir $@))
+else
 
-#the touch at the end is because memsticks seem to round time to even seconds, which screws up updates.  Grr.
-compile: cleanTemps updateTools updateLibs checkInstallBinTimestamp $(PROJ_BD)/installbin.timestamp
-	@image="$(PROJ_BD)/$(notdir $(MEMSTICK_ROOT))" ; \
-	if [ \! -d "$$image" ] ; then \
-		if [ \! -d "$(SYSTEM_BINARIES)" ] ; then \
-			echo "Could not find OPEN-R system binaries" ; \
-			exit 1 ; \
-		fi ; \
-		echo "Copying system files..." ; \
-		cp -r "$(SYSTEM_BINARIES)" "$$image" ; \
-		chmod -R u+w "$$image" ; \
-		$(CONVERTCASE) -r $$image/*; \
-		rm -f "$$image/open-r/mw/conf/connect.cfg" "$$image/open-r/mw/conf/object.cfg" "$$image/open-r/system/conf/wlandflt.txt" ; \
-		curt=`date +%Y%m%d%H%M`; \
-		find "$$image" -exec touch -ft $$curt \{\} \; ; \
-	fi;
+include local/Makefile.local
 
-checkInstallBinTimestamp:
-	@for x in $(INSTALL_BINS) ; do \
-		if [ "$$x" -nt "$(PROJ_BD)/installbin.timestamp" ] ; then \
-			printf "Target switch detected, cleaning binaries..." ; \
-			rm -f $(INSTALL_BINS) ; \
-			printf "done.\n" ; \
-			exit 0; \
-		fi; \
-	done;
+endif
 
-ifeq ($(findstring clean,$(MAKECMDGOALS)),)
-ifeq ($(findstring docs,$(MAKECMDGOALS)),)
+ifeq ($(filter clean% docs,$(MAKECMDGOALS)),)
 -include $(DEPENDS)
+ifeq ($(TEKKOTSU_TARGET_PLATFORM),PLATFORM_APERIOS)
+-include $(PROJ_BD)/aperios/aperios.d
+else
+-include $(PROJ_BD)/local/local.d
 endif
 endif
 
-$(STUB_CHECK_FILES):
-	@thedir=`echo $@ | sed 's/.*-\(.*\)-.*/\1/g'`; \
-	cd $(TEKKOTSU_ROOT)/$$thedir ; \
-	$(STUBGEN) stub.cfg ; \
-	mkdir -p $(dir $@) ; \
-	touch $@ ;
-
-%.d : $(STUB_CHECK_FILES)
+%.d :
 	@mkdir -p $(dir $@)
-	@src=$(patsubst %.d,%.cc,$(if $(findstring $(TK_BD),$@),$(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$@),$(patsubst $(PROJ_BD)/%,%,$@))); \
-	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
+	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
+	if [ ! -f "$$src" ] ; then \
+		echo "Generating source file '$$src'"; \
+		$(MAKE) "$$src" ; \
+	fi; \
+	echo "$@..." | sed 's@$(PROJ_BD)/@Generating @'; \
 	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
 
-%/def.h %/entry.h: %/stub.cfg
-	@echo "Doing $@"
-	cd $* && $(STUBGEN) stub.cfg
-	@echo "Done with $@"
-
-#%/entry.h: %/stub.cfg
-#	cd $(TEKKOTSU_ROOT)/$* && $(STUBGEN) stub.cfg
-
-%Stub.h %Stub.cc: 
-	@echo "Doing $@"
-	cd $(dir $@) && $(STUBGEN) stub.cfg
-	@echo "Done with $@"
-
-#%Stub.cc:
-#	cd $(dir $@) && $(STUBGEN) stub.cfg
-#	@echo "Done with $@"
+reportTarget:
+	@echo " ** Targeting $(TEKKOTSU_TARGET_MODEL) for build on $(TEKKOTSU_TARGET_PLATFORM) ** ";
+	@echo " ** TEKKOTSU_DEBUG is $(if $(TEKKOTSU_DEBUG),ON ,OFF) ** ";
 
 %.h :
 	@if [ "$(notdir $@)" = "def.h" -o "$(notdir $@)" = "entry.h" ] ; then \
@@ -301,56 +199,12 @@
 	@echo "You might need to rebuild the dependancy files ('make cleanDeps') to get rid of this error.";
 	@exit 1
 
-#The "fork" we do of MMCombo into MainObj and MotoObj crashes with optimization... not a big loss, just turn it off for these files
-$(TK_BD)/MMCombo/MMCombo.o $(TK_BD)/MMCombo/MMComboStub.o: %.o:
-	@mkdir -p $(dir $@)
-	@src=$(patsubst %.o,%$(SRCSUFFIX),$(if $(findstring $(TK_BD),$@),$(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$@),$(patsubst $(PROJ_BD)/%,%,$@))); \
-	if [ -r dist_hosts.txt ] ; then \
-		echo "Adding $@ to job list"; \
-		echo "$(CXX) $(filter-out -O2,$(CXXFLAGS)) -o $@ -c $$src > $*.log 2>&1; retval=\$$?; cat $*.log | $(FILTERSYSWARN) | $(COLORFILT); test \$$retval -eq 0;" >> $(PROJ_BD)/joblist.txt ; \
-		touch $@; \
-		echo "$@" >> $(PROJ_BD)/touched.txt ; \
-	else \
-		echo "Compiling $$src... (no -O2)"; \
-		$(CXX) $(filter-out -O2,$(CXXFLAGS)) -o $@ -c $$src > $*.log 2>&1; \
-		retval=$$?; \
-		cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
-		test $$retval -eq 0; \
-	fi;
-
-$(TK_BD)/TinyFTPD/TinyFTPD.o $(TK_BD)/TinyFTPD/FtpMethod.o $(TK_BD)/TinyFTPD/FtpRequest.o $(TK_BD)/TinyFTPD/FtpDTP.o $(TK_BD)/TinyFTPD/FtpPI.o: %.o:
-	@mkdir -p $(dir $@)
-	@src=$(patsubst %.o,%$(SRCSUFFIX),$(if $(findstring $(TK_BD),$@),$(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$@),$(patsubst $(PROJ_BD)/%,%,$@))); \
-	if [ -r dist_hosts.txt ] ; then \
-		echo "Adding $@ to job list"; \
-		echo "$(CXX) $(filter-out -DOPENR_DEBUG,$(filter-out -Weffc++,$(CXXFLAGS))) -o $@ -c $$src > $*.log 2>&1; retval=\$$?; cat $*.log | $(FILTERSYSWARN) | $(COLORFILT); test \$$retval -eq 0;" >> $(PROJ_BD)/joblist.txt ; \
-		touch $@; \
-		echo "$@" >> $(PROJ_BD)/touched.txt ; \
-	else \
-		echo "Compiling $$src... (reduced warnings, no OPENR_DEBUG)"; \
-		$(CXX) $(filter-out -DOPENR_DEBUG,$(filter-out -Weffc++,$(CXXFLAGS))) -o $@ -c $$src > $*.log 2>&1; \
-		retval=$$?; \
-		cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
-		test $$retval -eq 0; \
-	fi;
-
-$(TK_BD)/SoundPlay/WAV.o: %.o: $(FILTERSYSWARN)
-	@mkdir -p $(dir $@)
-	@src=$(patsubst %.o,%$(SRCSUFFIX),$(if $(findstring $(TK_BD),$@),$(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$@),$(patsubst $(PROJ_BD)/%,%,$@))); \
-	if [ -r dist_hosts.txt ] ; then \
-		echo "Adding $@ to job list"; \
-		echo "$(CXX) $(filter-out -Weffc++,$(CXXFLAGS)) -o $@ -c $$src > $*.log 2>&1; retval=\$$?; cat $*.log | $(FILTERSYSWARN) | $(COLORFILT); test \$$retval -eq 0;" >> $(PROJ_BD)/joblist.txt ; \
-		touch $@; \
-		echo "$@" >> $(PROJ_BD)/touched.txt ; \
-	else \
-		echo "Compiling $$src... (reduced warnings)"; \
-		$(CXX) $(filter-out -Weffc++,$(CXXFLAGS)) -o $@ -c $$src > $*.log 2>&1; \
-		retval=$$?; \
-		cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
-		test $$retval -eq 0; \
-	fi;
+#don't try to make random files via this implicit chain
+%:: %.o
+	echo "I don't know anything about `$*'";
+	exit 1;
 
-%.o:
+%.o: $(if $(TEKKOTSU_PCH),$(TK_BD)/$(TEKKOTSU_PCH).gch)
 	@mkdir -p $(dir $@)
 	@src=$(patsubst %.o,%$(SRCSUFFIX),$(if $(findstring $(TK_BD),$@),$(patsubst $(TK_BD)%,$(TEKKOTSU_ROOT)%,$@),$(patsubst $(PROJ_BD)/%,%,$@))); \
 	if [ -r dist_hosts.txt ] ; then \
@@ -360,147 +214,21 @@
 		echo "$@" >> $(PROJ_BD)/touched.txt ; \
 	else \
 		echo "Compiling $$src..."; \
-		$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+		$(CXX) $(CXXFLAGS) $(INCLUDE_PCH) -o $@ -c $$src > $*.log 2>&1; \
 		retval=$$?; \
 		cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
 		test $$retval -eq 0; \
 	fi;
 
-#BUILDS:   (framework object files, one per process - resides in framework)
-$(BUILDS):
-	@if [ -r dist_hosts.txt -a -r $(PROJ_BD)/joblist.txt ] ; then \
-		echo "Distributing compiles..."; \
-		../tools/pm.pl dist_hosts.txt $(PROJ_BD)/joblist.txt ; \
-	fi
-	@rm -f $(PROJ_BD)/joblist.txt; #this is so we don't rebuild multiple times
-	@echo "Linking component object files..."
-	@if [ $(words $(foreach comp,$(addprefix $(TK_BD)/,$($(basename $(notdir $@))_COMP)),$(if $(suffix $(comp)),$(comp),$(patsubst %.cc,%.o,$(shell find $(comp) -name "*.o"))))) -gt 20 ] ; then \
-		echo "$@ <- [...]"; \
-	else \
-		echo "$@ <- $(sort $(foreach comp,$(addprefix $(TK_BD)/,$(filter-out %.a,$($(basename $(notdir $@))_COMP))), $(if $(suffix $(comp)),$(comp),$(shell find $(comp) -name "*.o") )))" | sed 's@$(TK_BD)/@@g'; \
-	fi;
+$(PROJ_BD)/project.a: $(OBJS)
+	@echo "Linking project files..."
+	@printf "$@ <- "; echo "$(OBJS)" | sed 's@$(PROJ_BD)/@@g';
 	@rm -f $@;
-	@$(AR) $@ $(sort $(foreach comp,$(addprefix $(TK_BD)/,$(filter-out %.a,$($(basename $(notdir $@))_COMP))), $(if $(suffix $(comp)),$(comp),$(shell find $(comp) -name "*.o") )));
+	@$(AR) $@ $(OBJS);
 	@$(AR2) $@
 
-#PROC_BINS:    (executable binaries, uncompressed)
-# we have to do a couple extra steps to cd into the builddir because
-# mkbin doesn't support -o target in a different directory... drops an
-# intermediate file in . and then complains (as of 1.1.3 anyway)
-$(PROJ_BD)/%$(BINSUFFIX):
-	@if [ -r dist_hosts.txt -a -r $(PROJ_BD)/joblist.txt ] ; then \
-		echo "Distributing compiles..."; \
-		../tools/pm.pl dist_hosts.txt $(PROJ_BD)/joblist.txt ; \
-	fi
-	@rm -f $(PROJ_BD)/joblist.txt; #this is so we don't rebuild multiple times
-	@echo "Creating executable binary..."
-	@echo "$@ <- $($(basename $(notdir $@))_OBJS), $($(basename $(notdir $@))_OCF), $($(basename $(notdir $@))_LIBS) $(LIBS)" | sed 's@ $(PROJ_BD)/@ @g';
-	@$(MKBIN) $(MKBINFLAGS) -o $@ $($(basename $(notdir $@))_OBJS) -m $($(basename $(notdir $@))_OCF) $($(basename $(notdir $@))_LIBS) $(LIBS) ; \
-	if [ $$? -gt 0 ] ; then \
-		echo "Build failed."; \
-		exit 1; \
-	fi; \
-	$(STRIP) $@ ;
-
-#INSTALL_BINS:     (compressed executables, in proper location in image directory)
-$(INSTALLDIR)/%$(BINSUFFIX): $(PROJ_BD)/%$(BINSUFFIX)
-	@if [ \! -d "$(INSTALLDIR)" ] ; then \
-		echo "I can't find $(INSTALLDIR).  Hmmm."; \
-		exit 1; \
-	fi;
-	@echo "Compressing $< -> $@"
-	@gzip -c $< > $@;
-
-$(INSTALLDIR)/$(MAINFORK): $(PROJ_BD)/$(MMCOMBOBIN) $(TEKKOTSU_ROOT)/tools/binstrswap/binstrswap
-	@if [ \! -d "$(INSTALLDIR)" ] ; then \
-		echo "I can't find $(INSTALLDIR).  Hmmm."; \
-		exit 1; \
-	fi;
-	@echo "Compressing $< ~> $@"
-	@$(TEKKOTSU_ROOT)/tools/binstrswap/binstrswap $< MMCombo MainObj | gzip -c > $@
-#	@sed 's/MMCombo/MainObj/g;s/mmcombo/mainobj/g' $< | gzip -c > $@
-
-$(INSTALLDIR)/$(MOTOFORK): $(PROJ_BD)/$(MMCOMBOBIN) $(TEKKOTSU_ROOT)/tools/binstrswap/binstrswap
-	@if [ \! -d "$(INSTALLDIR)" ] ; then \
-		echo "I can't find $(INSTALLDIR).  Hmmm."; \
-		exit 1; \
-	fi;
-	@echo "Compressing $< ~> $@"
-	@$(TEKKOTSU_ROOT)/tools/binstrswap/binstrswap $< MMCombo MotoObj | gzip -c > $@
-#	@sed 's/MMCombo/MotoObj/g;s/mmcombo/motoobj/g' $< | gzip -c > $@
-
-$(PROJ_BD)/installbin.timestamp: $(INSTALL_BINS)
-	@touch $@
-
-install: compile
-	@echo "Installing files to memory stick at $(MEMSTICK_ROOT)"
-	$(TEKKOTSU_ROOT)/tools/mntmem "$(MEMSTICK_ROOT)"
-	@if [ \! -r "$(MEMSTICK_ROOT)/open-r/version.txt" -o \! -r "$(MEMSTICK_ROOT)/open-r/system/objs/ipstack.bin" -o \! -r "$(MEMSTICK_ROOT)/open-r/system/objs/vr.bin" -o \! -r "$(MEMSTICK_ROOT)/open-r/system/objs/wlanenbl.bin" ] ; then \
-		echo "** ERROR: It looks like your memory stick is missing critical system files."; \
-		echo "**        You may want to 'make newstick' first to clear the memory stick"; \
-		echo "**        and copy the OPEN-R system files onto it."; \
-		echo $(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
-		$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
-		exit 1; \
-	fi;
-	@if [ -z "`grep \"$(if $(findstring TGT_ERS7,$(TEKKOTSU_TARGET_MODEL)),ERS-7,ERS-210/220)\" \"$(MEMSTICK_ROOT)/open-r/version.txt\"`" ] ; then \
-		echo "** ERROR: It looks like your memory stick has the system files for the wrong"; \
-		echo "**        model of AIBO.  You may want to 'make newstick' first to clear the"; \
-		echo "**        memory stick and reinstall the OPEN-R system files onto it."; \
-		echo $(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
-		$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
-		exit 1; \
-	fi;
-	@$(TEKKOTSU_ROOT)/tools/cpymem --all --img $(MSIMGDIR) --tgt "$(MEMSTICK_ROOT)" --tools $(TEKKOTSU_ROOT)/tools
-	@touch .copiedtomemstick.timestamp
-
-update: compile $(TEKKOTSU_ROOT)/tools/evenmodtime/evenmodtime
-	@echo "Syncing $(MSIMGDIR) and $(MEMSTICK_ROOT)"
-	@$(TEKKOTSU_ROOT)/tools/evenmodtime/evenmodtime `find $(MSIMGDIR)` $(PROJ_BD)/installbin.timestamp
-	@$(TEKKOTSU_ROOT)/tools/mntmem "$(MEMSTICK_ROOT)"
-	@if [ $(STRICT_MEMSTICK_IMAGE) ] ; then \
-		echo "Strict image copy is on." ; \
-		rsync -rLtWCv --delete $(MSIMGDIR)/* "$(PROJ_BD)/$(notdir $(MEMSTICK_ROOT))/"* "$(MEMSTICK_ROOT)" ; \
-	else \
-		rsync -rLtWCv $(MSIMGDIR)/* "$(PROJ_BD)/$(notdir $(MEMSTICK_ROOT))/"* "$(MEMSTICK_ROOT)" ; \
-	fi;
-	@$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"
-	@touch .copiedtomemstick.timestamp
-
-newstick:
-	@echo "  We are about to delete all the files contained within '$(MEMSTICK_ROOT)':"
-	@echo "    rm -rf \"$(MEMSTICK_ROOT)/\"*"
-	@echo
-	@echo "  These files will be replaced with a fresh copy of the system binaries"
-	@echo "  from '$(SYSTEM_BINARIES)'"
-	@printf "  Are you sure you want to continue? (Type 'yes' to continue) > "
-	@read resp ; if [ "$$resp" != "yes" ] ; then \
-		echo "newstick canceled"; \
-		exit 1; \
-	fi;
-	$(TEKKOTSU_ROOT)/tools/mntmem "$(MEMSTICK_ROOT)";
-	rm -rf "$(MEMSTICK_ROOT)/"*;
-	cp -r "$(SYSTEM_BINARIES)/"* "$(MEMSTICK_ROOT)";
-	$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)";
-
-$(FILTERSYSWARN):
-	(cd $(TEKKOTSU_ROOT)/tools && $(MAKE));
-
-cleanTemps:
-	rm -f $(PROJ_BD)/joblist.txt $(PROJ_BD)/touched.txt
-
 clean: cleanProj
-	@printf "Cleaning all ~ files corresponding to .cc files..."
-	@rm -f $(addsuffix ~,$(TK_SRCS)) $(TK_SRCS:$(SRCSUFFIX)=.h~)
-	@printf "done.\n"
-	rm -f $(foreach proc,$(PROCESS_OBJS),$(TEKKOTSU_ROOT)/$(proc)/$(proc)Stub.cc $(TEKKOTSU_ROOT)/$(proc)/$(proc)Stub.h $(TEKKOTSU_ROOT)/$(proc)/def.h $(TEKKOTSU_ROOT)/$(proc)/entry.h)
-	rm -rf $(TEKKOTSU_BUILDDIR)
-	cd $(TEKKOTSU_ROOT)/tools ; $(MAKE) clean
-
-cleanDeps:
-	@printf "Cleaning all .d files corresponding to .cc files..."
-	@rm -f $(DEPENDS)
-	@printf "done.\n"
+	$(if $(TEKKOTSU_ALWAYS_BUILD),$(MAKE) -C $(TEKKOTSU_ROOT) $@)
 
 cleanProj:
 	@printf "Cleaning all ~ files corresponding to project .cc files..."
@@ -508,12 +236,14 @@
 	@printf "done.\n"
 	rm -rf $(PROJECT_BUILDDIR)
 	rm -f $(INSTALL_BINS)
+	for dir in `ls aperios` ; do \
+		if [ "$$dir" = "CVS" ] ; then continue; fi; \
+		if [ -f "aperios/$$dir" ] ; then continue; fi; \
+		rm -f "aperios/$$dir/$${dir}Stub."{h,cc} "aperios/$$dir/def.h" "aperios/$$dir/entry.h" ; \
+	done
 
-dox doc docs:
-	cd $(TEKKOTSU_ROOT) && $(MAKE) $@
-
-cleandoc:
-	docs/builddocs --clean
-
-
-
+cleanDeps:
+	@echo "Cleaning all .d files from build directory..."
+	find $(PROJ_BD) -name "*.d" -exec rm \{\} \;
+	@echo "done."
+	$(if $(TEKKOTSU_ALWAYS_BUILD),$(MAKE) -C $(TEKKOTSU_ROOT) $@)
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior.cc ./project/StartupBehavior.cc
--- ../Tekkotsu_2.3/project/StartupBehavior.cc	Tue Dec 21 16:49:50 2004
+++ ./project/StartupBehavior.cc	Fri Jun 10 13:26:04 2005
@@ -13,25 +13,34 @@
 #include "Motion/MotionSequenceMC.h"
 #include "Motion/MMAccessor.h"
 
-#include "SoundPlay/SoundManager.h"
+#include "Sound/SoundManager.h"
 
 #include "Shared/ERS210Info.h"
 #include "Shared/ERS7Info.h"
 
 #include "Shared/ProjectInterface.h"
 
-StartupBehavior theStartup; //!< used to initialize the global ::startupBehavior, used by MMCombo
-BehaviorBase& ProjectInterface::startupBehavior=theStartup; //!< used by MMCombo as the init behavior
+using namespace std;
+
+BehaviorBase& ProjectInterface::startupBehavior() {
+	// used by Main process, called after environmental setup is complete
+	static StartupBehavior * theStartup=NULL;
+	if(!theStartup)
+		theStartup=new StartupBehavior;
+	return *theStartup;
+}
 
 StartupBehavior::StartupBehavior()
-	: BehaviorBase("StartupBehavior"), spawned(),setup(),
+	: BehaviorBase("StartupBehavior"), spawned(),spawnedMC(),setup(),
 		stop_id(MotionManager::invalid_MC_ID),
 		pid_id(MotionManager::invalid_MC_ID)
-{
-	AddReference(); // this is a global, so there's a global reference
+{	
+			cout << "StartupBehavior()" << endl;
+			SetAutoDelete(false); // this is a global, so there's a global reference, don't delete yourself
+	//could instead AddReference(), but then the teardown code has to know that it should dereference on exit
 }
 
-StartupBehavior::~StartupBehavior() {cout << "Goodbye" << endl;}
+StartupBehavior::~StartupBehavior() {}
 
 void StartupBehavior::DoStart() {
 	BehaviorBase::DoStart();
@@ -45,15 +54,17 @@
 	//also, pause before we start fading in, PIDs take effect right
 	//away, before the emergencystop is picked up
 	erouter->addTimer(this,0,4*FrameTime*NumFrames,true);
+	spawnedMC.push_back(pid_id);
 
 	//This sets up the default emergency stop
-	const SharedObject<EmergencyStopMC> stop;
+	SharedObject<EmergencyStopMC> stop;
 	//if you want to start off unpaused, either change 'true' to
-	//'false', or just comment out the next line (estop's efault is off)
+	//'false', or just comment out the next line (estop's default is off)
 	//Note that if you don't want to start in estop, you should then
 	//also uncomment the line at the end of this function
 	stop->setStopped(true,false); 
 	stop_id=motman->addPersistentMotion(stop,MotionManager::kEmergencyPriority);
+	spawnedMC.push_back(stop_id);
 	
 	//This displays the current battery conditions on the console
 	BatteryCheckControl batchk;
@@ -85,10 +96,15 @@
 		closeMouth->setOutputCmd(mouthOffset,outputRanges[mouthOffset][MaxRange]);
 		closeMouth->advanceTime(500); //and hold it for another .5 seconds
 		closeMouth->setOutputCmd(mouthOffset,outputRanges[mouthOffset][MaxRange]);
-		motman->addPrunableMotion(closeMouth,MotionManager::kEmergencyPriority+1);
+		MotionManager::MC_ID id=motman->addPrunableMotion(closeMouth,MotionManager::kEmergencyPriority+1);
 		erouter->addTimer(this,1,3250,false);
+		spawnedMC.push_back(id);
 	}
-
+	
+	//! we want to know if one of our MCs autoprunes (or is otherwise removed)
+	for(unsigned int i=0; i<spawnedMC.size(); i++)
+		erouter->addListener(this,EventBase::motmanEGID,spawnedMC[i],EventBase::deactivateETID);
+	
 	//if you didn't want to start off paused, you should throw an
 	//un-estop event.  This will make it clear to any background
 	//behaviors (namely WorldStateVelDaemon) that we're not in estop
@@ -96,56 +112,75 @@
 }
 
 void StartupBehavior::DoStop() {
-	for(std::vector<BehaviorBase*>::iterator it=spawned.begin(); it!=spawned.end(); it++) {
+	erouter->removeListener(this);
+	for(vector<BehaviorBase*>::iterator it=spawned.begin(); it!=spawned.end(); it++) {
 		cout << "StartupBehavior stopping spawned: " << (*it)->getName() << endl;
 		(*it)->DoStop();
 	}
-	motman->removeMotion(stop_id);
+	spawned.clear();
+	for(vector<MotionManager::MC_ID>::iterator it=spawnedMC.begin(); it!=spawnedMC.end(); it++) {
+		cout << "StartupBehavior stopping spawned MC: " << (*it) << endl;
+		motman->removeMotion(*it);
+	}
+	spawnedMC.clear();
 	BehaviorBase::DoStop();
 }
 
 /*!Uses a few timer events at the beginning to fade in the PID values, and closes the mouth too*/
 void StartupBehavior::processEvent(const EventBase& event) {
-	if(event.getGeneratorID()==EventBase::timerEGID && event.getSourceID()==0) {
-		//this will do the work of fading in the PID values.  It helps the joints
-		//to power up without twitching
-		static unsigned int start_time=-1U;
-		const unsigned int tot_time=2000; 
-		if(start_time==-1U) { //first time
-			start_time=get_time();
-		} else {
-			float power=(get_time()-start_time)/(float)tot_time;
-			if(power>1)
-				power=1;
-			MMAccessor<PIDMC>(pid_id)->setAllPowerLevel(power*power);
-		}
-		if((get_time()-start_time)>=tot_time) {
-			erouter->removeTimer(this,0);
-			motman->removeMotion(pid_id);
-			pid_id=MotionManager::invalid_MC_ID;
+	if(event.getGeneratorID()==EventBase::timerEGID) {
+		if(event.getSourceID()==0) {
+			//this will do the work of fading in the PID values.  It helps the joints
+			//to power up without twitching
+			static unsigned int start_time=-1U;
+			const unsigned int tot_time=2000; 
+			if(start_time==-1U) { //first time
+				start_time=get_time();
+			} else {
+				float power=(get_time()-start_time)/(float)tot_time;
+				if(power>1)
+					power=1;
+				MMAccessor<PIDMC>(pid_id)->setAllPowerLevel(power*power);
+			}
+			if((get_time()-start_time)>=tot_time) {
+				erouter->removeTimer(this,0);
+				//when this goes through, it will trigger the event handler below to follow through cleanup of the id
+				motman->removeMotion(pid_id);
+			}
+		} else if(event.getSourceID()==1) {
+			//we're done closing the mouth... set the mouth to closed in the estop too
+			//otherwise it might twitch a little when the MotionSequence expires and the estop takes over
+			// (little == +/-.1 radians, aka estop's threshold for resetting an "out of place" joint) (details, details)
+			unsigned int mouthOffset=-1U;
+			if(state->robotDesign & WorldState::ERS210Mask)
+				mouthOffset=ERS210Info::MouthOffset;
+			if(state->robotDesign & WorldState::ERS7Mask)
+				mouthOffset=ERS7Info::MouthOffset;
+			if(mouthOffset!=-1U) {
+				MMAccessor<EmergencyStopMC> estop(stop_id);
+				float weight=estop->getOutputCmd(mouthOffset).weight;
+				estop->setOutputCmd(mouthOffset,OutputCmd(outputRanges[mouthOffset][MaxRange],weight));
+			}
 		}
-	}
-
-	if(event.getGeneratorID()==EventBase::timerEGID && event.getSourceID()==1) {
-		//we're done closing the mouth... set the mouth to closed in the estop too
-		//otherwise it might twitch a little when the MotionSequence expires and the estop takes over
-		// (little == +/-.1 radians, aka estop's threshold for resetting an "out of place" joint) (details, details)
-		unsigned int mouthOffset=-1U;
-		if(state->robotDesign & WorldState::ERS210Mask)
-			mouthOffset=ERS210Info::MouthOffset;
-		if(state->robotDesign & WorldState::ERS7Mask)
-			mouthOffset=ERS7Info::MouthOffset;
-		if(mouthOffset!=-1U) {
-			MMAccessor<EmergencyStopMC> estop(stop_id);
-			float weight=estop->getOutputCmd(mouthOffset).weight;
-			estop->setOutputCmd(mouthOffset,OutputCmd(outputRanges[mouthOffset][MaxRange],weight));
+		
+	} else if(event.getGeneratorID()==EventBase::motmanEGID) {
+		vector<MotionManager::MC_ID>::iterator it=find(spawnedMC.begin(),spawnedMC.end(),event.getSourceID());
+		ASSERTRET(it!=spawnedMC.end(),"Warning: StartupBehavior received deactive motion event for MC it didn't spawn");
+		erouter->removeListener(this,EventBase::motmanEGID,event.getSourceID(),EventBase::deactivateETID);
+		if(event.getSourceID()==stop_id) {
+			//probably a bad idea to remove this -- spit out a warning to let user know it happened
+			cerr << "Warning: Emergency stop MC has been removed" << endl;
+			stop_id=MotionManager::invalid_MC_ID;
 		}
+		if(event.getSourceID()==pid_id) //is supposed to be removed when done, not something to get excited about
+			pid_id=MotionManager::invalid_MC_ID;
+		spawnedMC.erase(it);
 	}
 }
 
 ControlBase*
 StartupBehavior::SetupMenus() {
-	std::cout << "CONTROLLER-INIT..." << std::flush;
+	cout << "CONTROLLER-INIT..." << flush;
 	ControlBase* root=new ControlBase("Root Control");
 	setup.push(root);
 
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior.h ./project/StartupBehavior.h
--- ../Tekkotsu_2.3/project/StartupBehavior.h	Wed Nov 10 20:45:37 2004
+++ ./project/StartupBehavior.h	Wed Jun  1 01:48:07 2005
@@ -72,11 +72,10 @@
 	virtual ControlBase* endSubMenu();  //!< closes out a submenu so that future calls to addItem() will be added to the enclosing menu, returns the menu being closed out
 
 	std::vector<BehaviorBase*> spawned; //!< Holds pointers to all the behaviors spawned from DoStart, so they can automatically be stopped on DoStop (should only happen on shutdown, but ensures cleanliness)
-	std::stack<ControlBase*> setup;     //!< only used during setup - easier than passing it around all the functions
+	std::vector<MotionManager::MC_ID> spawnedMC; //!< Holds ids for all the motion commands spawned from DoStart, so they can automatically be removed on DoStop, if they weren't already autopruned (should only happen on shutdown, but ensures cleanliness)
+	std::stack<ControlBase*> setup;     //!< only used during setup - easier than passing it around all the Setup*() functions
 	MotionManager::MC_ID stop_id; //!< the main EmergencyStopMC
 	MotionManager::MC_ID pid_id; //!< used to fade in the PIDs up to full strength (from initial zero) This is so the joints don't jerk on startup.
 };
-
-extern BehaviorBase& startupBehavior;
 
 #endif
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior_SetupBackgroundBehaviors.cc ./project/StartupBehavior_SetupBackgroundBehaviors.cc
--- ../Tekkotsu_2.3/project/StartupBehavior_SetupBackgroundBehaviors.cc	Thu Jan 27 00:42:31 2005
+++ ./project/StartupBehavior_SetupBackgroundBehaviors.cc	Wed Jun  1 01:48:07 2005
@@ -36,7 +36,7 @@
 		addItem(new BehaviorSwitchControl<TailWagNode>("Wag Tail",false));
 		addItem(new BehaviorSwitchControl<RelaxBehavior>("Relax",false));
 		addItem(new BehaviorSwitchControl<CameraBehavior>("Camera",false));
-		addItem(new BehaviorSwitchControl<ASCIIVisionBehavior>("ASCIIVision",false));
+		addItem((new BehaviorSwitchControl<ASCIIVisionBehavior>("ASCIIVision",false)));
 		addItem(new ControlBase("Debugging Tests","Stress tests"));
 		startSubMenu();
 		{
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior_SetupFileAccess.cc ./project/StartupBehavior_SetupFileAccess.cc
--- ../Tekkotsu_2.3/project/StartupBehavior_SetupFileAccess.cc	Fri Jan  7 14:37:43 2005
+++ ./project/StartupBehavior_SetupFileAccess.cc	Mon Jun  6 19:05:59 2005
@@ -22,7 +22,7 @@
 		addItem(new PlaySoundControl("Play Sound"));
 		addItem(new WaypointWalkControl());
 		SetupWalkEdit();
-		addItem(new DumpFileControl("Files","/ms"));
+		addItem(new DumpFileControl("Files",config->portPath("")));
 	}
 	return endSubMenu();
 }
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior_SetupModeSwitch.cc ./project/StartupBehavior_SetupModeSwitch.cc
--- ../Tekkotsu_2.3/project/StartupBehavior_SetupModeSwitch.cc	Fri Jan 28 19:58:25 2005
+++ ./project/StartupBehavior_SetupModeSwitch.cc	Tue Aug  9 19:15:47 2005
@@ -12,7 +12,6 @@
 #include "Behaviors/Demos/SoundTestBehavior.h"
 #include "Behaviors/Demos/ExploreMachine.h"
 #include "Behaviors/Demos/PaceTargetsMachine.h"
-#include "Behaviors/Demos/StareAtPawBehavior.h"
 #include "Behaviors/Demos/StareAtPawBehavior2.h"
 #include "Behaviors/Demos/KinematicSampleBehavior.h"
 #include "Behaviors/Demos/KinematicSampleBehavior2.h"
@@ -38,8 +37,8 @@
 		if(state->robotDesign&(WorldState::ERS210Mask|WorldState::ERS7Mask)) //this one only really works on the 210 or 7
 			addItem(new BehaviorSwitchControl<AlanBehavior>("Alan's Behavior",bg,false));
 		addItem(new BehaviorSwitchControl<FollowHeadBehavior>("Follow Head",bg,false));
-		addItem(new BehaviorSwitchControl<StareAtBallBehavior>("Stare at Pink Ball",false));
-		addItem(new BehaviorSwitchControl<SimpleChaseBallBehavior>("Simple Chase Ball",false));
+		addItem(new BehaviorSwitchControl<StareAtBallBehavior>("Stare at Pink Ball",bg,false));
+		addItem(new BehaviorSwitchControl<SimpleChaseBallBehavior>("Simple Chase Ball",bg,false));
 		addItem(new BehaviorSwitchControl<ChaseBallBehavior>("Chase Ball",bg,false));
 		addItem(new BehaviorSwitchControl<SoundTestBehavior>("Sound Test",bg,false));
 		addItem(new BehaviorSwitchControl<LookForSoundBehavior>("Look at Sound",bg,false));
@@ -57,8 +56,7 @@
 		{
 			addItem(new BehaviorSwitchControl<KinematicSampleBehavior>("Kinematic Sample 1",bg,false));
 			addItem(new BehaviorSwitchControl<KinematicSampleBehavior2>("Kinematic Sample 2",bg,false));
-			addItem(new BehaviorSwitchControl<StareAtPawBehavior>("Stare at Paw (pre-2.2)",bg,false));
-			addItem(new BehaviorSwitchControl<StareAtPawBehavior2>("New Stare at Paw",bg,false));
+			addItem(new BehaviorSwitchControl<StareAtPawBehavior2>("Stare at Paw",bg,false));
 			addItem(new BehaviorSwitchControl<GroundPlaneBehavior>("Ground Plane Test",bg,false));
 			addItem(new BehaviorSwitchControl<WallTestBehavior>("Wall Test",bg,false));
 		}
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior_SetupTekkotsuMon.cc ./project/StartupBehavior_SetupTekkotsuMon.cc
--- ../Tekkotsu_2.3/project/StartupBehavior_SetupTekkotsuMon.cc	Mon Dec 13 21:54:01 2004
+++ ./project/StartupBehavior_SetupTekkotsuMon.cc	Fri Aug  5 15:44:23 2005
@@ -5,15 +5,19 @@
 
 #include "Behaviors/Mon/ViewWMVarsBehavior.h"
 #include "Behaviors/Mon/WalkControllerBehavior.h"
+#include "Behaviors/Mon/UPennWalkControllerBehavior.h"
 #include "Behaviors/Mon/HeadPointControllerBehavior.h"
+#include "Behaviors/Mon/StewartPlatformBehavior.h"
 #include "Behaviors/Mon/Aibo3DControllerBehavior.h"
 #include "Behaviors/Mon/EStopControllerBehavior.h"
 #include "Behaviors/Mon/WMMonitorBehavior.h"
 #include "Behaviors/Mon/RawCamBehavior.h"
 #include "Behaviors/Mon/SegCamBehavior.h"
+#include "Behaviors/Mon/RegionCamBehavior.h"
 #include "Behaviors/Mon/WorldStateSerializerBehavior.h"
 #include "Behaviors/Mon/MicrophoneServer.h"
 #include "Behaviors/Mon/SpeakerServer.h"
+#include "Behaviors/Mon/EchoBehavior.h"
 #include "Behaviors/Mon/SpiderMachineBehavior.h"
 
 ControlBase*
@@ -23,15 +27,19 @@
 	{ 
 		addItem((new BehaviorSwitchControl<HeadPointControllerBehavior>("Head Remote Control",false)));
 		addItem((new BehaviorSwitchControl<WalkControllerBehavior>("Walk Remote Control",false)));
+		addItem((new BehaviorSwitchControl<UPennWalkControllerBehavior>("UPenn Walk Remote Control",false)));
 		addItem((new BehaviorSwitchControl<ViewWMVarsBehavior>("View WMVars",false)));
 		addItem((new BehaviorSwitchControl<WMMonitorBehavior>("Watchable Memory Monitor",false))->start());
+		addItem((new BehaviorSwitchControl<StewartPlatformBehavior>("Stewart Platform",false)));
 		addItem((new BehaviorSwitchControl<Aibo3DControllerBehavior>("Aibo 3D",false)));
 		addItem((new BehaviorSwitchControl<WorldStateSerializerBehavior>("World State Serializer",false)));
 		addItem((new BehaviorSwitchControl<RawCamBehavior>("Raw Cam Server",false)));
 		addItem((new BehaviorSwitchControl<SegCamBehavior>("Seg Cam Server",false)));
+		addItem((new BehaviorSwitchControl<RegionCamBehavior>("Region Cam Server",false)));
 		addItem((new BehaviorSwitchControlBase(new EStopControllerBehavior(stop_id)))->start());
 		addItem(new BehaviorSwitchControlBase(MicrophoneServer::GetInstance()));
 		addItem(new BehaviorSwitchControlBase(SpeakerServer::GetInstance()));
+		addItem((new BehaviorSwitchControl<EchoBehavior>("Echo Client/Server",false)));
 		addItem((new BehaviorSwitchControl<SpiderMachineBehavior>("Spider State Machines Server",false)));
 	}
 	return endSubMenu();
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior_SetupVision.cc ./project/StartupBehavior_SetupVision.cc
--- ../Tekkotsu_2.3/project/StartupBehavior_SetupVision.cc	Wed Mar 17 17:49:15 2004
+++ ./project/StartupBehavior_SetupVision.cc	Sun Jul 10 16:03:11 2005
@@ -5,8 +5,14 @@
 
 #include "Behaviors/Controls/BehaviorSwitchControl.h"
 #include "Behaviors/Controls/NullControl.h"
+#ifndef PLATFORM_APERIOS
+#  include "Behaviors/Controls/SimulatorAdvanceFrameControl.h"
+#endif
 
 #include "Vision/RawCameraGenerator.h"
+#ifndef PLATFORM_APERIOS
+#  include "Vision/BufferedImageGenerator.h"
+#endif
 #include "Vision/InterleavedYUVGenerator.h"
 #include "Vision/JPEGGenerator.h"
 #include "Vision/SegmentedColorGenerator.h"
@@ -15,6 +21,9 @@
 #include "Vision/BallDetectionGenerator.h"
 #include "Vision/CDTGenerator.h"
 
+#include "Behaviors/Demos/DrawVisObjBoundBehavior.h"
+#include "Behaviors/Demos/DrawSkeletonBehavior.h"
+
 using namespace ProjectInterface;
 
 BallDetectionGenerator * pball=NULL;
@@ -35,34 +44,49 @@
 	//If you change this value, you should modify the *Layer variables in ProjectInterface (if you want to use them)
 	unsigned int numLayers=6;
 
+#ifdef PLATFORM_APERIOS
 	//The top level layer will be double resolution
 	//This will set how many real layers are provided by the system (3 in Aperios)
 	//Any other layers will be subsamples of the lowest resolution system resolution
 	unsigned int numSystemLayers=3;
+	defRawCameraGenerator = new RawCameraGenerator(numSystemLayers,numLayers,visRawCameraSID,EventBase::visOFbkEGID,0);
+#else //PLATFORM_LOCAL
+	defRawCameraGenerator = new BufferedImageGenerator("RawBufferedImageGenerator",EventBase::visRawCameraEGID,visRawCameraSID,numLayers,EventBase::visOFbkEGID,0);
+#endif
+	
 
-	defRawCameraGenerator = new RawCameraGenerator(numSystemLayers,numLayers,EventBase::visOFbkEGID,0,visRawCameraSID);
-
-	defInterleavedYUVGenerator = new InterleavedYUVGenerator(EventBase::visRawCameraEGID,visRawCameraSID,visInterleaveSID,RawCameraGenerator::CHAN_Y,RawCameraGenerator::CHAN_U,RawCameraGenerator::CHAN_V);
+	// These JPEG generators select the "deactivate" stage, so they will work on
+	// the potentially marked up versions of the raw camera.  The camera GUIs use
+	// these to provide vision feedback without requiring an extra pipeline stage
+	// or image copy.
+	// Of course, if you want to analyze the JPEG compression as a part of a
+	// computer vision algorithm, you'll want the un-marked up versions, and so
+	// you may need to add another JPEG compressor instance that uses the
+	// "activate" stage to ensure you get the original data.
 
-	defColorJPEGGenerator = new JPEGGenerator(EventBase::visInterleaveEGID,visInterleaveSID,visColorJPEGSID,JPEGGenerator::SRC_AUTO);
+	//need to do pixel interleaving for JPEG compression
+	//if the results of visRawCameraEGID are already in the proper format (e.g. source layer of BufferedImageGenerator) then InterleavedYUVGenerator is a pass-through
+	defInterleavedYUVGenerator = new InterleavedYUVGenerator(visInterleaveSID,RawCameraGenerator::CHAN_Y,RawCameraGenerator::CHAN_U,RawCameraGenerator::CHAN_V,defRawCameraGenerator,EventBase::deactivateETID);
+	defColorJPEGGenerator = new JPEGGenerator(visColorJPEGSID,defInterleavedYUVGenerator,EventBase::deactivateETID);
 	defColorJPEGGenerator->setName("ColorJPEGGenerator");
-
-	defGrayscaleJPEGGenerator = new JPEGGenerator(EventBase::visRawCameraEGID,visRawCameraSID,visGrayscaleJPEGSID,JPEGGenerator::SRC_AUTO);
+	defGrayscaleJPEGGenerator = new JPEGGenerator(visGrayscaleJPEGSID,defRawCameraGenerator,EventBase::deactivateETID);
 	defGrayscaleJPEGGenerator->setName("GrayscaleJPEGGenerator");
 
+
 	// the hardware level CDT generator allows faster, but less flexible
 	// segmenting it still needs a little work though before it can be
 	// hooked up to the CMVision RLE generator.  See CDTGenerator class notes.
 	// defSegmentedColorGenerator = new CDTGenerator(numSystemLayers,numLayers,EventBase::visOFbkEGID,0,visSegmentSID);
-	SegmentedColorGenerator * segcol = new SegmentedColorGenerator(EventBase::visRawCameraEGID,visRawCameraSID,visSegmentSID);
-	defSegmentedColorGenerator = segcol;
+	defSegmentedColorGenerator = new SegmentedColorGenerator(visSegmentSID,defRawCameraGenerator,EventBase::activateETID);
+	SegmentedColorGenerator * segcol = defSegmentedColorGenerator; //just using segcol as a shorthand for the following setup
 	segcol->loadColorInfo(config->vision.colors);
 	for(unsigned int i=0; i<config->vision.thresh.size(); i++)
 		segcol->loadThresholdMap(config->vision.thresh[i]);
 
-	defRLEGenerator = new RLEGenerator(EventBase::visSegmentEGID,visSegmentSID,visRLESID);
+	// Note this uses the "activate" stage, so you can mark up segmented images as well
+	defRLEGenerator = new RLEGenerator(visRLESID,segcol,EventBase::activateETID);
 	
-	defRegionGenerator = new RegionGenerator(EventBase::visRLEEGID,visRLESID,visRegionSID);
+	defRegionGenerator = new RegionGenerator(visRegionSID, defRLEGenerator, EventBase::activateETID);
 	
 	// for lack of a better idea, the object recognizers below will all
 	// use the config->vision.rlecam_channel for picking the threshold
@@ -83,17 +107,17 @@
 
 	unsigned int pinkIdx=segcol->getColorIndex("red");
 	if(pinkIdx!=-1U) {
-		pball = new BallDetectionGenerator(EventBase::visRegionEGID,visRegionSID,visPinkBallSID,pinkIdx,threshChan,noiseFiltering,confidenceThreshold);
+		pball = new BallDetectionGenerator(visPinkBallSID,defRegionGenerator,pinkIdx,threshChan,noiseFiltering,confidenceThreshold);
 		pball->setName("PinkBallDetectionGenerator");
 	}
 	unsigned int blueIdx=segcol->getColorIndex("blue");
 	if(blueIdx!=-1U) {
-		bball = new BallDetectionGenerator(EventBase::visRegionEGID,visRegionSID,visBlueBallSID,blueIdx,threshChan,noiseFiltering,confidenceThreshold);
+		bball = new BallDetectionGenerator(visBlueBallSID,defRegionGenerator,blueIdx,threshChan,noiseFiltering,confidenceThreshold);
 		bball->setName("BlueBallDetectionGenerator");
 	}
 	unsigned int skinIdx=segcol->getColorIndex("brown");
 	if(skinIdx!=-1U) {
-		handball = new BallDetectionGenerator(EventBase::visRegionEGID,visRegionSID,visHandSID,skinIdx,threshChan,noiseFiltering,confidenceThreshold);
+		handball = new BallDetectionGenerator(visHandSID,defRegionGenerator,skinIdx,threshChan,noiseFiltering,confidenceThreshold);
 		handball->setName("HandBallDetectionGenerator");
 	}
 }
@@ -103,24 +127,49 @@
 	addItem(new ControlBase("Vision Pipeline","Start/Stop stages of the vision pipeline"));
 	startSubMenu();
 	{ 
-		addItem((new BehaviorSwitchControlBase(defRawCameraGenerator))->start());
-		addItem((new BehaviorSwitchControlBase(defInterleavedYUVGenerator))->start());
-		addItem((new BehaviorSwitchControlBase(defColorJPEGGenerator))->start());
-		addItem((new BehaviorSwitchControlBase(defGrayscaleJPEGGenerator))->start());
+		addItem((new BehaviorSwitchControl<DrawVisObjBoundBehavior>("Draw Object Boundaries",false)));
+		addItem((new BehaviorSwitchControl<DrawSkeletonBehavior>("Draw Skeleton",false)));
+#ifndef PLATFORM_APERIOS		
+		addItem(new SimulatorAdvanceFrameControl("Advance Frame"));
+#endif
+		addItem(NULL);
+
+		//check that each generator is actually defined before trying to start it
+		//just as a failsafe in case some of the default generators are disabled
+		
+		if(defRawCameraGenerator)
+			addItem((new BehaviorSwitchControlBase(defRawCameraGenerator))->start());
+
+		if(defInterleavedYUVGenerator)
+			addItem((new BehaviorSwitchControlBase(defInterleavedYUVGenerator))->start());
+
+		if(defColorJPEGGenerator)
+			addItem((new BehaviorSwitchControlBase(defColorJPEGGenerator))->start());
+
+		if(defGrayscaleJPEGGenerator)
+			addItem((new BehaviorSwitchControlBase(defGrayscaleJPEGGenerator))->start());
+		
 		if(config->vision.colors!="" && config->vision.thresh.size()>0)
 			addItem((new BehaviorSwitchControlBase(defSegmentedColorGenerator))->start());
 		else
 			addItem(new BehaviorSwitchControlBase(defSegmentedColorGenerator));
-		addItem((new BehaviorSwitchControlBase(defRLEGenerator))->start());
-		addItem((new BehaviorSwitchControlBase(defRegionGenerator))->start());
+		
+		if(defRLEGenerator)
+			addItem((new BehaviorSwitchControlBase(defRLEGenerator))->start());
+
+		if(defRegionGenerator)
+			addItem((new BehaviorSwitchControlBase(defRegionGenerator))->start());
+
 		if(pball)
 			addItem((new BehaviorSwitchControlBase(pball))->start());
 		else
 			addItem(new NullControl("Error: PinkBallDetectionGenerator","Color \"red\" is undefined"));
+
 		if(bball)
 			addItem((new BehaviorSwitchControlBase(bball))->start());
 		else
 			addItem(new NullControl("Error: BlueBallDetectionGenerator","Color \"blue\" is undefined"));
+
 		if(handball)
 			addItem((new BehaviorSwitchControlBase(handball))->start());
 		else
diff -urdN ../Tekkotsu_2.3/project/StartupBehavior_SetupWalkEdit.cc ./project/StartupBehavior_SetupWalkEdit.cc
--- ../Tekkotsu_2.3/project/StartupBehavior_SetupWalkEdit.cc	Fri May 14 03:18:19 2004
+++ ./project/StartupBehavior_SetupWalkEdit.cc	Fri May 14 03:18:19 2004
@@ -9,7 +9,7 @@
  * @author PA Gov. School for the Sciences 2003 Team Project - Motion group: Haoqian Chen, Yantian Martin, Jon Stahlman (creators)
  * 
  * $Author: ejt $
- * $Name: tekkotsu-2_3 $
+ * $Name: tekkotsu-2_4 $
  * $Revision: 1.8 $
  * $State: Exp $
  * $Date: 2004/05/14 07:18:19 $
diff -urdN ../Tekkotsu_2.3/project/aperios/CVS/Entries ./project/aperios/CVS/Entries
--- ../Tekkotsu_2.3/project/aperios/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/aperios/CVS/Entries	Wed Aug 10 11:03:26 2005
@@ -0,0 +1,2 @@
+/Makefile.aperios/1.3/Fri Jun  3 22:55:49 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/aperios/CVS/Repository ./project/aperios/CVS/Repository
--- ../Tekkotsu_2.3/project/aperios/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/aperios/CVS/Repository	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Tekkotsu/project/aperios
diff -urdN ../Tekkotsu_2.3/project/aperios/CVS/Root ./project/aperios/CVS/Root
--- ../Tekkotsu_2.3/project/aperios/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/aperios/CVS/Root	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/aperios/CVS/Tag ./project/aperios/CVS/Tag
--- ../Tekkotsu_2.3/project/aperios/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/aperios/CVS/Tag	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/aperios/Makefile.aperios ./project/aperios/Makefile.aperios
--- ../Tekkotsu_2.3/project/aperios/Makefile.aperios	Wed Dec 31 19:00:00 1969
+++ ./project/aperios/Makefile.aperios	Fri Jun  3 18:55:49 2005
@@ -0,0 +1,229 @@
+ifeq ($(TEKKOTSU_ENVIRONMENT_CONFIGURATION),)
+$(error This makefile is not meant to be run directly.  It is intended to contain Aperios-specific build instructions.  Please run 'make' from the main project directory.);
+endif
+
+.PHONY: newstick install update cleanTemps checkInstallBinTimestamp
+
+#Each directory represents a separate OObject aka process/thread
+#PROJ_OOBJECTS holds those defined in the project, OOBJECTS
+#holds those defined in either/both $(TEKKOTSU_ROOT) and project
+PROJ_OOBJECTS:=$(filter-out CVS bin include lib share man,$(subst aperios/,,$(shell find aperios -mindepth 1 -maxdepth 1 -type d -prune)))
+OOBJECTS:=$(sort $(PROJ_OOBJECTS) $(filter-out CVS bin include lib share man,$(subst $(TEKKOTSU_ROOT)/aperios/,,$(shell find $(TEKKOTSU_ROOT)/aperios -mindepth 1 -maxdepth 1 -type d -prune))))
+
+# Location of Aperios (the Aibo's OS) binary executables
+SYSTEM_BINARIES:=$(OPENRSDK_ROOT)/OPEN_R/MS_$(if $(findstring $(TEKKOTSU_TARGET_MODEL),TGT_ERS7),ERS7,ERS200)/WCONSOLE/nomemprot
+
+ifeq ($(FILENAME_CASE),lower)
+  TRCMD=tr "[:upper:]" "[:lower:]"
+  CONVERTCASE=$(TEKKOTSU_ROOT)/tools/makelowercase
+  BINSUFFIX=.bin
+  MSIMGDIR=ms
+  INSTALLDIR=$(MSIMGDIR)/open-r/mw/objs
+  MMCOMBO_FORKS=mainobj.bin motoobj.bin
+else
+  TRCMD=tr "[:lower:]" "[:upper:]"
+  CONVERTCASE=$(TEKKOTSU_ROOT)/tools/makeuppercase
+  BINSUFFIX=.BIN
+  MSIMGDIR=MS
+  INSTALLDIR=$(MSIMGDIR)/OPEN-R/MW/OBJS
+  MMCOMBO_FORKS=MAINOBJ.BIN MOTOOBJ.BIN
+endif
+
+# These are the file names of the final executable binaries, in the
+# memstick image directory
+INSTALL_BINS:=$(shell echo $(addprefix $(INSTALLDIR)/, $(addsuffix $(BINSUFFIX), MainObj MotoObj $(filter-out MMCombo,$(OOBJECTS)))) | $(TRCMD))
+
+$(PROJ_BD)/aperios/aperios.d: $(shell find aperios -name "*$(SRCSUFFIX)") $(wildcard $(TK_BD)/aperios/*)
+	@echo Generating $@...
+	@mkdir -p $(dir $@)
+	@rm -f $@;
+	@for dir in $(OOBJECTS) ; do \
+		unset curobj curdir tkdir tkobj; \
+		if [ -d "aperios/$$dir" ] ; then \
+			curdir="aperios/$$dir"; \
+			curobj=`find aperios/$$dir -name "*$(SRCSUFFIX)" | sed 's@\(.*\)$(SRCSUFFIX)$$@$(PROJ_BD)/\1.o@' | xargs` ; \
+			if [ -f "aperios/$$dir/stub.cfg" -a ! -f "aperios/$$dir/$${dir}Stub.cc" ] ; then \
+				curobj="$$curobj $(PROJ_BD)/aperios/$$dir/$${dir}Stub.o"; \
+			fi; \
+		fi; \
+		if [ -d "$(TEKKOTSU_ROOT)/aperios/$$dir" ] ; then \
+			tkdir="$(TEKKOTSU_ROOT)/aperios/$$dir"; \
+			tkobj=`find "$(TEKKOTSU_ROOT)/aperios/$$dir" -name "*$(SRCSUFFIX)" | sed 's@^$(TEKKOTSU_ROOT)\(.*\)$(SRCSUFFIX)$$@$(TK_BD)\1.o@' | xargs` ; \
+			if [ -f "$(TEKKOTSU_ROOT)/aperios/$$dir/stub.cfg" -a ! -f "$(TEKKOTSU_ROOT)/aperios/$$dir/$${dir}Stub.cc" ] ; then \
+				tkobj="$$tkobj $(TK_BD)/aperios/$$dir/$${dir}Stub.o"; \
+			fi; \
+		fi; \
+		echo "$${dir}_OBJS:=$$curobj $$tkobj" >> $@; \
+		echo "$${dir}_OCF:=`find $$curdir $$tkdir -name \"*.ocf\" | head -n 1`" >> $@; \
+		echo >> $@ ; \
+		echo "$(PROJ_BD)/aperios/$$dir$(BINSUFFIX): \$$($${dir}_OBJS) \$$($${dir}_OCF) $(USERLIBS) $$tklib" >> $@ ; \
+		echo >> $@ ; \
+		if [ -d "aperios/$$dir" ] ; then \
+			echo "aperios/$$dir/$${dir}Stub.h aperios/$$dir/$${dir}Stub.cc aperios/$$dir/def.h aperios/$$dir/entry.h: aperios/$$dir/stub.cfg" >> $@ ; \
+			echo '	cd $$(dir $$@) && $$(STUBGEN) stub.cfg' >> $@ ;\
+			echo >> $@ ; \
+			echo "$(PROJ_BD)/aperios/$$dir/$${dir}Stub.o $(PROJ_BD)/aperios/$$dir/$${dir}Stub.d : aperios/$$dir/$${dir}Stub.h aperios/$$dir/$${dir}Stub.cc" >> $@ ; \
+			echo >> $@ ; \
+		fi; \
+		if [ "$$dir" != "MMCombo" ] ; then \
+			inst=`echo $${dir} | $(TRCMD)`; \
+			printf "$(INSTALLDIR)/$${inst}$(BINSUFFIX): $(PROJ_BD)/aperios/$${dir}$(BINSUFFIX)\\n\\n" >> $@; \
+		fi; \
+	done;
+
+OSRCS:=$(shell find aperios -name "*$(SRCSUFFIX)")
+DEPENDS:=$(DEPENDS) $(addprefix $(PROJ_BD)/,$(OSRCS:$(SRCSUFFIX)=.d))
+
+#the touch at the end is because memsticks seem to round time to even seconds, which screws up updates.  Grr.
+compile: checkLibs cleanTemps checkInstallBinTimestamp $(PROJ_BD)/installbin.timestamp
+	@image="$(PROJ_BD)/$(notdir $(MEMSTICK_ROOT))" ; \
+	if [ \! -d "$$image" ] ; then \
+		if [ \! -d "$(SYSTEM_BINARIES)" ] ; then \
+			echo "Could not find OPEN-R system binaries" ; \
+			exit 1 ; \
+		fi ; \
+		echo "Copying system files..." ; \
+		cp -r "$(SYSTEM_BINARIES)" "$$image" ; \
+		chmod -R u+w "$$image" ; \
+		$(CONVERTCASE) -r $$image/*; \
+		rm -f "$$image/open-r/mw/conf/connect.cfg" "$$image/open-r/mw/conf/object.cfg" "$$image/open-r/system/conf/wlandflt.txt" ; \
+		curt=`date +%Y%m%d%H%M`; \
+		find "$$image" -exec touch -ft $$curt \{\} \; ; \
+	fi;
+
+checkInstallBinTimestamp:
+	@for x in $(INSTALL_BINS) ; do \
+		if [ "$$x" -nt "$(PROJ_BD)/installbin.timestamp" ] ; then \
+			printf "Target switch detected, cleaning binaries..." ; \
+			rm -f $(INSTALL_BINS) ; \
+			printf "done.\n" ; \
+			exit 0; \
+		fi; \
+	done;
+
+#only MMCombo depends on the project files -- the other processes don't have hooks for user code
+$(PROJ_BD)/aperios/MMCombo$(BINSUFFIX): $(PROJ_BD)/project.a
+
+#PROC_BINS:    (executable binaries, uncompressed)
+# we have to do a couple extra steps to cd into the builddir because
+# mkbin doesn't support -o target in a different directory... drops an
+# intermediate file in . and then complains (as of 1.1.3 anyway)
+$(PROJ_BD)/aperios/%$(BINSUFFIX):
+	@if [ -r dist_hosts.txt -a -r $(PROJ_BD)/joblist.txt ] ; then \
+		echo "Distributing compiles..."; \
+		../tools/pm.pl dist_hosts.txt $(PROJ_BD)/joblist.txt ; \
+	fi
+	@rm -f $(PROJ_BD)/joblist.txt; #this is so we don't rebuild multiple times
+	@echo "Creating executable binary..."
+	@objs="$($*_OBJS)" ; \
+	ocf="$($*_OCF)" ; \
+	libs="$(if $(findstring MMCombo,$*),$(PROJ_BD)/project.a) $(USERLIBS) $(LDFLAGS)" ; \
+	echo "$@ <- $${objs}, $${ocf}, $${libs}" | sed 's@$(PROJ_BD)/@@g'; \
+	$(MKBIN) $(MKBINFLAGS) -o $@ $$objs -m $$ocf $$libs  ; \
+	if [ $$? -gt 0 ] ; then \
+		echo "Build failed."; \
+		exit 1; \
+	fi; \
+	$(STRIP) $@ ;
+
+#INSTALL_BINS:     (compressed executables, in proper location in image directory)
+$(INSTALLDIR)/%$(BINSUFFIX):
+	@if [ \! -d "$(INSTALLDIR)" ] ; then \
+		echo "I can't find $(INSTALLDIR).  Hmmm."; \
+		exit 1; \
+	fi;
+	@echo "Compressing $< -> $@"
+	@gzip -c $< > $@;
+
+$(INSTALLDIR)/$(shell echo MainObj.bin | $(TRCMD)): $(PROJ_BD)/aperios/MMCombo.bin
+	@if [ \! -d "$(INSTALLDIR)" ] ; then \
+		echo "I can't find $(INSTALLDIR).  Hmmm."; \
+		exit 1; \
+	fi;
+	@echo "Compressing $< ~> $@"
+	@$(TEKKOTSU_ROOT)/tools/binstrswap/binstrswap $< MMCombo MainObj | gzip -c > $@
+
+$(INSTALLDIR)/$(shell echo MotoObj.bin | $(TRCMD)): $(PROJ_BD)/aperios/MMCombo.bin
+	@if [ \! -d "$(INSTALLDIR)" ] ; then \
+		echo "I can't find $(INSTALLDIR).  Hmmm."; \
+		exit 1; \
+	fi;
+	@echo "Compressing $< ~> $@"
+	@$(TEKKOTSU_ROOT)/tools/binstrswap/binstrswap $< MMCombo MotoObj | gzip -c > $@
+
+$(PROJ_BD)/installbin.timestamp: $(INSTALL_BINS)
+	@touch $@
+
+install: compile
+	@echo "Installing files to memory stick at $(MEMSTICK_ROOT)"
+	$(TEKKOTSU_ROOT)/tools/mntmem "$(MEMSTICK_ROOT)"
+	@if [ \! -r "$(MEMSTICK_ROOT)/open-r/version.txt" -o \! -r "$(MEMSTICK_ROOT)/open-r/system/objs/ipstack.bin" -o \! -r "$(MEMSTICK_ROOT)/open-r/system/objs/vr.bin" -o \! -r "$(MEMSTICK_ROOT)/open-r/system/objs/wlanenbl.bin" ] ; then \
+		echo "** ERROR: It looks like your memory stick is missing critical system files."; \
+		echo "**        You may want to 'make newstick' first to clear the memory stick"; \
+		echo "**        and copy the OPEN-R system files onto it."; \
+		echo $(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
+		$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
+		exit 1; \
+	fi;
+	@if [ -z "`grep \"$(if $(findstring TGT_ERS7,$(TEKKOTSU_TARGET_MODEL)),ERS-7,ERS-210/220)\" \"$(MEMSTICK_ROOT)/open-r/version.txt\"`" ] ; then \
+		echo "** ERROR: It looks like your memory stick has the system files for the wrong"; \
+		echo "**        model of AIBO.  You may want to 'make newstick' first to clear the"; \
+		echo "**        memory stick and reinstall the OPEN-R system files onto it."; \
+		echo $(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
+		$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"; \
+		exit 1; \
+	fi;
+	@$(TEKKOTSU_ROOT)/tools/cpymem --all --img $(MSIMGDIR) --tgt "$(MEMSTICK_ROOT)" --tools $(TEKKOTSU_ROOT)/tools
+	@touch .copiedtomemstick.timestamp
+
+update: compile
+	@echo "Syncing $(MSIMGDIR) and $(MEMSTICK_ROOT)"
+	@$(TEKKOTSU_ROOT)/tools/evenmodtime/evenmodtime `find $(MSIMGDIR)` $(PROJ_BD)/installbin.timestamp
+	@$(TEKKOTSU_ROOT)/tools/mntmem "$(MEMSTICK_ROOT)"
+	@if [ $(STRICT_MEMSTICK_IMAGE) ] ; then \
+		echo "Strict image copy is on." ; \
+		rsync -rLtWCv --delete $(MSIMGDIR)/* "$(PROJ_BD)/$(notdir $(MEMSTICK_ROOT))/"* "$(MEMSTICK_ROOT)" ; \
+	else \
+		rsync -rLtWCv $(MSIMGDIR)/* "$(PROJ_BD)/$(notdir $(MEMSTICK_ROOT))/"* "$(MEMSTICK_ROOT)" ; \
+	fi;
+	@$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)"
+	@touch .copiedtomemstick.timestamp
+
+newstick:
+	@echo "  We are about to delete all the files contained within '$(MEMSTICK_ROOT)':"
+	@echo "    rm -rf \"$(MEMSTICK_ROOT)/\"*"
+	@echo
+	@echo "  These files will be replaced with a fresh copy of the system binaries"
+	@echo "  from '$(SYSTEM_BINARIES)'"
+	@printf "  Are you sure you want to continue? (Type 'yes' to continue) > "
+	@read resp ; if [ "$$resp" != "yes" ] ; then \
+		echo "newstick canceled"; \
+		exit 1; \
+	fi;
+	$(TEKKOTSU_ROOT)/tools/mntmem "$(MEMSTICK_ROOT)";
+	rm -rf "$(MEMSTICK_ROOT)/"*;
+	cp -r "$(SYSTEM_BINARIES)/"* "$(MEMSTICK_ROOT)";
+	$(TEKKOTSU_ROOT)/tools/umntmem "$(MEMSTICK_ROOT)";
+
+# MMCombo is actually done in the root library, but just in case it gets moved back here...
+#The "fork" we do of MMCombo into MainObj and MotoObj
+#crashes with optimization turned on... not sure why, but it's
+#not a big loss, just turn it off for these files
+$(PROJ_BD)/aperios/MMCombo/MMCombo.o $(PROJ_BD)/aperios/MMCombo/MMComboStub.o: %.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
+	if [ -r dist_hosts.txt ] ; then \
+		echo "Adding $@ to job list"; \
+		echo "$(CXX) $(filter-out -O2,$(CXXFLAGS)) -o $@ -c $$src > $*.log 2>&1; retval=\$$?; cat $*.log | $(FILTERSYSWARN) | $(COLORFILT); test \$$retval -eq 0;" >> $(PROJ_BD)/joblist.txt ; \
+		touch $@; \
+		echo "$@" >> $(PROJ_BD)/touched.txt ; \
+	else \
+		echo "Compiling $$src... (no -O2)"; \
+		$(CXX) $(filter-out -O2,$(CXXFLAGS)) -o $@ -c $$src > $*.log 2>&1; \
+		retval=$$?; \
+		cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+		test $$retval -eq 0; \
+	fi;
+
+cleanTemps:
+	@rm -f $(PROJ_BD)/joblist.txt $(PROJ_BD)/touched.txt
diff -urdN ../Tekkotsu_2.3/project/local/CVS/Entries ./project/local/CVS/Entries
--- ../Tekkotsu_2.3/project/local/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/local/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,2 @@
+/Makefile.local/1.3/Wed Jun 29 23:13:05 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/local/CVS/Repository ./project/local/CVS/Repository
--- ../Tekkotsu_2.3/project/local/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/local/CVS/Repository	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Tekkotsu/project/local
diff -urdN ../Tekkotsu_2.3/project/local/CVS/Root ./project/local/CVS/Root
--- ../Tekkotsu_2.3/project/local/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/local/CVS/Root	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/local/CVS/Tag ./project/local/CVS/Tag
--- ../Tekkotsu_2.3/project/local/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/local/CVS/Tag	Wed Aug 10 11:03:26 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/local/Makefile.local ./project/local/Makefile.local
--- ../Tekkotsu_2.3/project/local/Makefile.local	Wed Dec 31 19:00:00 1969
+++ ./project/local/Makefile.local	Wed Jun 29 19:13:05 2005
@@ -0,0 +1,57 @@
+ifeq ($(TEKKOTSU_ENVIRONMENT_CONFIGURATION),)
+$(error This makefile is not meant to be run directly.  It is intended to contain local-specific build instructions.  Please run 'make' from the main project directory.);
+endif
+
+.PHONY: 
+
+#Each directory should represent a separate executable
+PROJ_EXECS:=$(filter-out CVS,$(subst local/,,$(shell find local -mindepth 1 -maxdepth 1 -type d -prune)))
+EXECS:=$(sort $(PROJ_EXECS) $(filter-out CVS,$(subst $(TEKKOTSU_ROOT)/local/,,$(shell find $(TEKKOTSU_ROOT)/local -mindepth 1 -maxdepth 1 -type d -prune))))
+TGTEXECS:=$(addsuffix $(subst TGT_,-,$(TEKKOTSU_TARGET_MODEL)),$(EXECS))
+
+ESRCS:=$(shell find local -name "*$(SRCSUFFIX)")
+DEPENDS:=$(DEPENDS) $(addprefix $(PROJ_BD)/,$(ESRCS:$(SRCSUFFIX)=.d))
+
+ifeq ($(shell uname | grep -ci cygwin),0)
+  PLATFORM_FLAGS:=$(PLATFORM_FLAGS) -DHAVE_READDIR_R
+endif
+
+$(PROJ_BD)/local/local.d: $(shell find local -name "*$(SRCSUFFIX)") $(wildcard $(TK_BD)/local/*)
+	@echo Generating $@...
+	@mkdir -p $(dir $@)
+	@rm -f $@;
+	@for dir in $(EXECS) ; do \
+		unset curobj curdir tkdir tkobj; \
+		if [ -d "local/$$dir" ] ; then \
+			curdir="local/$$dir"; \
+			curobj=`find local/$$dir -name "*$(SRCSUFFIX)" | sed 's@\(.*\)$(SRCSUFFIX)$$@$(PROJ_BD)/\1.o@' | xargs` ; \
+		fi; \
+		if [ -d "$(TEKKOTSU_ROOT)/local/$$dir" ] ; then \
+			tkdir="$(TEKKOTSU_ROOT)/local/$$dir"; \
+			tkobj=`find "$(TEKKOTSU_ROOT)/local/$$dir" -name "*$(SRCSUFFIX)" | sed 's@^$(TEKKOTSU_ROOT)\(.*\)$(SRCSUFFIX)$$@$(TK_BD)\1.o@' | xargs` ; \
+		fi; \
+		echo "$${dir}$(subst TGT_,-,$(TEKKOTSU_TARGET_MODEL))_OBJS:=$$curobj $$tkobj" >> $@; \
+		echo >> $@ ; \
+		echo "$${dir}$(subst TGT_,-,$(TEKKOTSU_TARGET_MODEL)): \$$($${dir}$(subst TGT_,-,$(TEKKOTSU_TARGET_MODEL))_OBJS) $(USERLIBS) $$tklib" >> $@ ; \
+		echo >> $@ ; \
+	done;
+
+compile: $(TGTEXECS)
+	@echo "You probably now want to run './sim$(subst TGT_,-,$(TEKKOTSU_TARGET_MODEL))'";
+
+ifneq ($(filter sim-%,$(MAKECMDGOALS)),)
+$(TGTEXECS): checkLibs $(PROJ_BD)/project.a
+else
+$(TGTEXECS): $(PROJ_BD)/project.a
+endif
+	@if [ -r dist_hosts.txt -a -r $(PROJ_BD)/joblist.txt ] ; then \
+		echo "Distributing compiles..."; \
+		../tools/pm.pl dist_hosts.txt $(PROJ_BD)/joblist.txt ; \
+	fi
+	@rm -f $(PROJ_BD)/joblist.txt; #this is so we don't rebuild multiple times
+	@echo "Creating executable binary..."
+	@objs="$($@_OBJS)" ; \
+	libs="$(PROJ_BD)/project.a $(USERLIBS) $(LDFLAGS)" ; \
+	echo "$@ <- $${objs} $${libs}" | sed 's@$(PROJ_BD)/@@g'; \
+	$(CXX) -o $@ $$objs $$libs  ; \
+
diff -urdN ../Tekkotsu_2.3/project/ms/CVS/Entries ./project/ms/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,3 @@
+D/config////
+D/data////
+D/open-r////
diff -urdN ../Tekkotsu_2.3/project/ms/CVS/Repository ./project/ms/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms
diff -urdN ../Tekkotsu_2.3/project/ms/CVS/Root ./project/ms/CVS/Root
--- ../Tekkotsu_2.3/project/ms/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/CVS/Tag ./project/ms/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/config/CVS/Entries ./project/ms/config/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/config/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/config/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,15 @@
+/7red.tm/1.1/Thu Feb  5 23:40:33 2004/-kb/Ttekkotsu-2_4
+/ball.tm/1.4/Wed Feb 18 21:13:59 2004/-kb/Ttekkotsu-2_4
+/default.col/1.2/Mon Jul 28 06:58:16 2003//Ttekkotsu-2_4
+/ers210.kin/1.13/Fri Dec 10 23:49:54 2004//Ttekkotsu-2_4
+/ers220.kin/1.13/Fri Dec 10 23:49:54 2004//Ttekkotsu-2_4
+/ers7.kin/1.15/Fri Dec 10 23:49:54 2004//Ttekkotsu-2_4
+/ers7pnts.kin/1.2/Fri Dec 10 23:49:54 2004//Ttekkotsu-2_4
+/general.tm/1.1/Thu Oct  9 06:25:30 2003/-kb/Ttekkotsu-2_4
+/pb.tm/1.1/Thu Oct  9 06:25:30 2003/-kb/Ttekkotsu-2_4
+/phb.tm/1.1/Thu Oct  9 06:25:30 2003/-kb/Ttekkotsu-2_4
+/tekkotsu.cfg/1.63/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/ttt.col/1.1/Wed Mar  3 23:14:44 2004//Ttekkotsu-2_4
+/ttt.tm/1.1/Wed Mar  3 23:14:44 2004//Ttekkotsu-2_4
+/ttt_old.tm/1.1/Wed Mar  3 23:14:44 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/ms/config/CVS/Repository ./project/ms/config/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/config/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/config/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/config
diff -urdN ../Tekkotsu_2.3/project/ms/config/CVS/Root ./project/ms/config/CVS/Root
--- ../Tekkotsu_2.3/project/ms/config/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/config/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/config/CVS/Tag ./project/ms/config/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/config/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/config/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/config/tekkotsu.cfg ./project/ms/config/tekkotsu.cfg
--- ../Tekkotsu_2.3/project/ms/config/tekkotsu.cfg	Thu Jan 27 00:43:38 2005
+++ ./project/ms/config/tekkotsu.cfg	Wed Aug 10 11:03:00 2005
@@ -1,9 +1,9 @@
 ##################################################################
 ######################   Tekkotsu config   #######################
 ##################################################################
-##################### $Name: tekkotsu-2_3 $ ######################
-####################### $Revision: 1.58 $ ########################
-################## $Date: 2005/01/27 05:43:38 $ ##################
+##################### $Name: tekkotsu-2_4 $ ######################
+####################### $Revision: 1.63 $ ########################
+################## $Date: 2005/08/05 19:44:23 $ ##################
 ##################################################################
 #
 # Format:
@@ -33,6 +33,9 @@
 #   - Of course, whether or not the new value will be picked up depends on
 #     how it is being used...
 #
+# * Paths are assumed to be relative to the project/ms/ directory.
+#   For example, this file would be referenced as config/tekkotsu.cfg
+#
 ##################################################################
 
 
@@ -78,19 +81,6 @@
 # this is the resolution vision's object recognition system will run at
 resolution=full
 
-### Camera Parameters ###
-
-# The field of view information should be specified in degrees
-<ERS-2*>
-horizFOV=57.6
-vertFOV=47.8
-focal_length=2.18
-</ERS-2*>
-<ERS-7>
-horizFOV=56.9
-vertFOV=45.2
-focal_length=3.27
-</ERS-7>
 
 ### Color Segmentation Threshold files ###
 # Threshold (.tm) files define the mapping from full color to indexed color
@@ -106,31 +96,37 @@
 # general.tm - general colors, previously 'default'
 # ball.tm - standard Sony pink ball definition
 # pb.tm - pink and blue
-thresh=/ms/config/phb.tm
-#thresh=/ms/config/general.tm
-thresh=/ms/config/ball.tm
-#thresh=/ms/config/pb.tm
-#thresh=/ms/config/ttt.tm
+thresh=config/phb.tm
+#thresh=config/general.tm
+thresh=config/ball.tm
+#thresh=config/pb.tm
+#thresh=config/ttt.tm
 </ERS-2*>
 <ERS-7>
 # 7red.tm - just your usual pink/red/purple color detection, nothing too fancy
 # ball.tm - standard Sony pink ball definition
-thresh=/ms/config/7red.tm
-thresh=/ms/config/ball.tm
+thresh=config/7red.tm
+thresh=config/ball.tm
 </ERS-7>
 
 # the .col file gives names and a "typical" color for display
 # the indexes numbers it contains correspond to indexes in the .tm file
-colors=/ms/config/default.col
+colors=config/default.col
 
 
 ### Image Streaming Format ###
 # These parameters control the video stream over wireless ethernet
 # transport can be either 'udp' or 'tcp'
-raw_port=10011
-raw_transport=udp
+rawcam_port=10011
+rawcam_transport=udp
 rle_port=10012
 rle_transport=udp
+region_port=10013
+region_transport=tcp
+
+# pause between raw image grabs: 0 for fast-as-possible, 100 for 10 FPS, etc
+# in milliseconds
+rle_interval=0
 
 # rawcam_encoding   color | y_only | uv_only | u_only | v_only | y_dx_only | y_dy_only | y_dxdy_only
 rawcam_encoding=color
@@ -141,6 +137,10 @@
 # quality of jpeg compression 0-100
 rawcam_compress_quality=85
 
+# pause between raw image grabs: 0 for fast-as-possible, 100 for 10 FPS
+# in milliseconds
+rawcam_interval=0
+
 # apparently someone at sony thinks it's a good idea to replace some
 # pixels in each camera image with information like the frame number
 # and CDT count.  if non-zero, will replace those pixels with the
@@ -174,6 +174,38 @@
 # segmented camera images, same idea as rawcam_*_skip
 rlecam_skip=1
 
+# this is the log_2 of pixels to skip when sending Region information,
+# same idea as rawcam_*_skip (added by nvh 21-04-05)
+regioncam_skip=1
+
+
+### Camera Calibration ###
+# see Config::vision_config::{computeRay,computePixel} to convert
+# between world coordinates and pixel coordinates using these values
+  
+# focal length (in pixels)
+focal_len_x = 198.807
+focal_len_y = 200.333
+  
+# center of optical projection (in pixels)
+principle_point_x = 102.689
+principle_point_y = 85.0399
+  
+# skew of CCD
+skew = 0
+  
+# Radial distortion terms
+kc1_r2 = -0.147005
+kc2_r4 = 0.38485
+kc5_r6 = 0
+  
+# Tangential distortion terms
+kc3_tan1 = -0.00347777
+kc4_tan2 = 0.00012873
+
+# resolution at which calibration images were taken
+calibration_res_x = 208
+calibration_res_y = 160
 
 
 ##################################################################
@@ -181,6 +213,10 @@
 [Main]
 ##################################################################
 ##################################################################
+
+# if non-zero, will call srand() with a high-precision timestamp, mangled by sensor data
+seed_rng=1
+
 console_port=10001
 stderr_port=10002
 error_level=0
@@ -192,9 +228,12 @@
 aibo3d_port=10051
 headControl_port=10052
 estopControl_port=10053
+stewart_port=10055
 wmmonitor_port=10061
 use_VT100=true
-
+# pause between writes: 0 for fast-as-possible, 100 for 10 FPS, etc.
+# in milliseconds
+worldState_interval=0
 
 
 ##################################################################
@@ -241,7 +280,7 @@
 
 # Any motion related paths which are not absolute (i.e. do not
 # start with '/') will be assumed to be relative to this directory
-root=/ms/data/motion
+root=data/motion
 
 # This is the default set of walk parameters
 walk=walk.prm
@@ -252,18 +291,18 @@
 # loaded from that file
 <ERS-2*>
 <ERS-210>
-kinematics=/ms/config/ers210.kin
+kinematics=/config/ers210.kin
 kinematic_chains=Body
 kinematic_chains=Mouth
 </ERS-210>
 <ERS-220>
-kinematics=/ms/config/ers220.kin
+kinematics=/config/ers220.kin
 kinematic_chains=Body
 </ERS-220>
 kinematic_chains=IR
 </ERS-2*>
 <ERS-7>
-kinematics=/ms/config/ers7.kin
+kinematics=/config/ers7.kin
 kinematic_chains=Body
 kinematic_chains=Mouth
 kinematic_chains=NearIR
@@ -276,27 +315,21 @@
 kinematic_chains=RBk
 kinematic_chains=Camera
 
-# These calibration parameters should specify the value to multiply a
-# desired position by in order to cause the joint to actually reach
-# that position.  This is then used both to calibrate joint values
-# which are sent to the system, and also sensor values which are
-# received back.
+# These values indicate the ratio of actual movement to commanded
+# So .9 means it moves 90% as far as it was supposed to.
+# This is then used both to calibrate joint values sent to the
+# system, as well as sensor values which are received back.
 # An unspecified joint is by default '1' which will then pass values
 # through unmodified.  Only PID joints are calibrated (i.e. LEDs and
 # ears are not)
 <ERS-7>
-#Only the knees and rotors have been calibrated
-#This is just kind of a rough calibration since
-#I don't know how well it will generalize across
-#individual robots anyway.
-calibrate:LFr:rotor=0.972
-calibrate:LFr:knee~=0.944
-calibrate:RFr:rotor=0.972
-calibrate:RFr:knee~=0.944
-calibrate:LBk:rotor=0.972
-calibrate:LBk:knee~=0.944
-calibrate:RBk:rotor=0.972
-calibrate:RBk:knee~=0.944
+calibrate:LFr:rotor=1.0
+calibrate:LFr:elvtr=1.0
+calibrate:LFr:knee~=1.0
+#...
+#The calibration I performed doesn't seem to hold up well, so
+#I'm leaving these all at 1.0.  Perhaps there is a constant
+#offset involved?  To be continued...
 </ERS-7>
 <ERS-2*>
 #ERS-2xx seems to be fairly well calibrated by system, but
@@ -336,7 +369,7 @@
 [Sound]
 ##################################################################
 ##################################################################
-root=/ms/data/sound
+root=data/sound
 # volume = mute | level_1 | level_2 | level_3 | <direct dB setting: 0x8000 - 0xFFFF>
 # if you directly set the decibel level, be warned sony recommends against going above 0xF600
 # However, I believe the commercial software on the ERS-7 runs at 0xFF00
diff -urdN ../Tekkotsu_2.3/project/ms/data/CVS/Entries ./project/ms/data/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/data/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,2 @@
+D/motion////
+D/sound////
diff -urdN ../Tekkotsu_2.3/project/ms/data/CVS/Repository ./project/ms/data/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/data/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/data
diff -urdN ../Tekkotsu_2.3/project/ms/data/CVS/Root ./project/ms/data/CVS/Root
--- ../Tekkotsu_2.3/project/ms/data/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/data/CVS/Tag ./project/ms/data/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/data/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/data/motion/CVS/Entries ./project/ms/data/motion/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/data/motion/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/motion/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,36 @@
+/circles.wyp/1.1/Tue Mar 30 04:31:39 2004//Ttekkotsu-2_4
+/clearcal.txt/1.2/Thu Feb 26 01:03:05 2004//Ttekkotsu-2_4
+/dance.mot/1.3/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/dispos.pos/1.1/Sat Mar  1 21:08:28 2003//Ttekkotsu-2_4
+/gu_back.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/gu_front.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/gu_side.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_bump.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_diag.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_dive.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_fwd.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_grab.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_head.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_heads.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_hold.mot/1.3/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/k_punch.mot/1.5/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/leftkick.pos/1.1/Sun Sep 21 19:44:14 2003//Ttekkotsu-2_4
+/liedown.pos/1.1/Sat Mar  1 21:08:28 2003//Ttekkotsu-2_4
+/pace.prm/1.1/Fri Sep 12 03:36:10 2003/-kb/Ttekkotsu-2_4
+/pan_head.mot/1.2/Tue Dec 21 22:30:28 2004//Ttekkotsu-2_4
+/pounce.pos/1.1/Sat Mar  1 21:08:28 2003//Ttekkotsu-2_4
+/readme.txt/1.1/Wed Feb 18 21:14:14 2004//Ttekkotsu-2_4
+/rkick.pos/1.1/Thu Jul  8 03:04:21 2004//Ttekkotsu-2_4
+/situp.pos/1.1/Sat Mar  1 21:08:28 2003//Ttekkotsu-2_4
+/sqbasca2.wyp/1.1/Tue Mar 30 04:31:39 2004//Ttekkotsu-2_4
+/sqbasce2.wyp/1.1/Tue Mar 30 04:31:40 2004//Ttekkotsu-2_4
+/sqbasco2.wyp/1.1/Tue Mar 30 04:31:40 2004//Ttekkotsu-2_4
+/sqbasica.wyp/1.1/Tue Mar 30 04:31:40 2004//Ttekkotsu-2_4
+/sqbasice.wyp/1.1/Tue Mar 30 04:31:40 2004//Ttekkotsu-2_4
+/sqbasico.wyp/1.1/Tue Mar 30 04:31:40 2004//Ttekkotsu-2_4
+/sqpush.wyp/1.1/Tue Mar 30 04:31:40 2004//Ttekkotsu-2_4
+/stand.pos/1.1/Sat Mar  1 21:08:28 2003//Ttekkotsu-2_4
+/tiger.prm/1.1/Sun Sep 21 19:44:14 2003//Ttekkotsu-2_4
+/walk.prm/1.6/Sat Feb 28 01:58:55 2004/-kb/Ttekkotsu-2_4
+/walkcal.txt/1.3/Sat Feb 28 01:58:55 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/ms/data/motion/CVS/Repository ./project/ms/data/motion/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/data/motion/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/motion/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/data/motion
diff -urdN ../Tekkotsu_2.3/project/ms/data/motion/CVS/Root ./project/ms/data/motion/CVS/Root
--- ../Tekkotsu_2.3/project/ms/data/motion/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/motion/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/data/motion/CVS/Tag ./project/ms/data/motion/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/data/motion/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/motion/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/CVS/Entries ./project/ms/data/sound/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/data/sound/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,31 @@
+/3barks.wav/1.1/Sun Mar  9 02:45:56 2003/-kb/Ttekkotsu-2_4
+/3yips.wav/1.1/Sun Mar  9 02:45:56 2003/-kb/Ttekkotsu-2_4
+/barkhigh.wav/1.1/Sun Mar  9 02:45:56 2003/-kb/Ttekkotsu-2_4
+/barklow.wav/1.1/Sun Mar  9 02:45:57 2003/-kb/Ttekkotsu-2_4
+/barkmed.wav/1.1/Sun Mar  9 02:45:57 2003/-kb/Ttekkotsu-2_4
+/barkreal.wav/1.1/Sat Mar 15 03:45:02 2003/-kb/Ttekkotsu-2_4
+/camera.wav/1.1/Sat Mar 15 03:45:02 2003/-kb/Ttekkotsu-2_4
+/catcry.wav/1.1/Sun Mar  9 02:45:57 2003/-kb/Ttekkotsu-2_4
+/catyowl.wav/1.1/Sun Mar  9 02:45:57 2003/-kb/Ttekkotsu-2_4
+/crash.wav/1.1/Sat Mar 15 03:45:02 2003/-kb/Ttekkotsu-2_4
+/cutey.wav/1.1/Sun Mar  9 02:45:57 2003/-kb/Ttekkotsu-2_4
+/donkey.wav/1.1/Sun Mar  9 02:45:58 2003/-kb/Ttekkotsu-2_4
+/fart.wav/1.1/Sat Mar 15 03:45:03 2003/-kb/Ttekkotsu-2_4
+/glass.wav/1.1/Sat Mar 15 03:45:03 2003/-kb/Ttekkotsu-2_4
+/growl.wav/1.1/Sun Mar  9 02:45:58 2003/-kb/Ttekkotsu-2_4
+/growl2.wav/1.1/Sat Mar 15 03:45:03 2003/-kb/Ttekkotsu-2_4
+/grrr.wav/1.1/Sun Mar  9 02:45:58 2003/-kb/Ttekkotsu-2_4
+/howl.wav/1.1/Sun Mar  9 02:45:59 2003/-kb/Ttekkotsu-2_4
+/mew.wav/1.1/Sun Mar  9 02:45:59 2003/-kb/Ttekkotsu-2_4
+/ping.wav/1.1/Sat Mar 15 03:45:03 2003/-kb/Ttekkotsu-2_4
+/roar.wav/1.1/Sun Mar  9 02:45:59 2003/-kb/Ttekkotsu-2_4
+/skid.wav/1.1/Sat Mar 15 03:45:03 2003/-kb/Ttekkotsu-2_4
+/sniff.wav/1.1/Sun Mar  9 02:45:59 2003/-kb/Ttekkotsu-2_4
+/tick.wav/1.1/Sat Mar 15 03:45:03 2003/-kb/Ttekkotsu-2_4
+/toc.wav/1.1/Sat Mar 15 03:45:04 2003/-kb/Ttekkotsu-2_4
+/whiip.wav/1.1/Sat Mar 15 03:45:04 2003/-kb/Ttekkotsu-2_4
+/whimper.wav/1.1/Sun Mar  9 02:46:00 2003/-kb/Ttekkotsu-2_4
+/whoop.wav/1.1/Sat Mar 15 03:45:04 2003/-kb/Ttekkotsu-2_4
+/yap.wav/1.1/Sun Mar  9 02:46:00 2003/-kb/Ttekkotsu-2_4
+/yipper.wav/1.1/Sun Mar  9 02:46:00 2003/-kb/Ttekkotsu-2_4
+D/numbers////
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/CVS/Repository ./project/ms/data/sound/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/data/sound/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/data/sound
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/CVS/Root ./project/ms/data/sound/CVS/Root
--- ../Tekkotsu_2.3/project/ms/data/sound/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/CVS/Tag ./project/ms/data/sound/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/data/sound/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Entries ./project/ms/data/sound/numbers/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/numbers/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,13 @@
+/0.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/1.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/2.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/3.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/4.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/5.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/6.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/7.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/8.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/9.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/dot.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+/point.wav/1.1/Thu Jan 27 05:43:46 2005/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Repository ./project/ms/data/sound/numbers/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/numbers/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/data/sound/numbers
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Root ./project/ms/data/sound/numbers/CVS/Root
--- ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/numbers/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Tag ./project/ms/data/sound/numbers/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/data/sound/numbers/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/data/sound/numbers/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/CVS/Entries ./project/ms/open-r/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/open-r/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,2 @@
+D/mw////
+D/system////
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/CVS/Repository ./project/ms/open-r/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/open-r/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/open-r
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/CVS/Root ./project/ms/open-r/CVS/Root
--- ../Tekkotsu_2.3/project/ms/open-r/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/CVS/Tag ./project/ms/open-r/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/open-r/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Entries ./project/ms/open-r/mw/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,2 @@
+D/conf////
+D/objs////
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Repository ./project/ms/open-r/mw/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/open-r/mw
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Root ./project/ms/open-r/mw/CVS/Root
--- ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Tag ./project/ms/open-r/mw/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/open-r/mw/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Entries ./project/ms/open-r/mw/conf/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/conf/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,5 @@
+/connect.cfg/1.9/Wed Jun 29 22:06:47 2005//Ttekkotsu-2_4
+/object.cfg/1.3/Wed Mar 26 21:33:21 2003//Ttekkotsu-2_4
+/passwd/1.5/Tue Jul  6 22:46:12 2004//Ttekkotsu-2_4
+/robotgw.cfg/1.2/Thu Mar 27 04:25:07 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Repository ./project/ms/open-r/mw/conf/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/conf/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/open-r/mw/conf
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Root ./project/ms/open-r/mw/conf/CVS/Root
--- ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/conf/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Tag ./project/ms/open-r/mw/conf/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/open-r/mw/conf/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/conf/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/conf/connect.cfg ./project/ms/open-r/mw/conf/connect.cfg
--- ../Tekkotsu_2.3/project/ms/open-r/mw/conf/connect.cfg	Tue Sep 28 19:07:08 2004
+++ ./project/ms/open-r/mw/conf/connect.cfg	Wed Aug 10 11:03:00 2005
@@ -15,22 +15,18 @@
 MainObj.MoveJoint.OCommandVectorData.S OVirtualRobotComm.Effector.OCommandVectorData.O
 MotoObj.MoveJoint.OCommandVectorData.S OVirtualRobotComm.Effector.OCommandVectorData.O
 
-#SoundPlay -> System
-SoundPlay.Speaker.OSoundVectorData.S OVirtualRobotAudioComm.Speaker.OSoundVectorData.O
+#SndPlay -> System
+SndPlay.Speaker.OSoundVectorData.S OVirtualRobotAudioComm.Speaker.OSoundVectorData.O
 
-#SoundPlay -> Main, Motion
-SoundPlay.RegisterSoundManager.SoundManager.S MainObj.ReceiveSoundManager.SoundManager.O
-SoundPlay.RegisterSoundManager.SoundManager.S MotoObj.ReceiveSoundManager.SoundManager.O
+#SndPlay -> Main, Motion
+SndPlay.RegisterSoundManager.SoundManager.S MainObj.ReceiveSoundManager.SoundManager.O
+SndPlay.RegisterSoundManager.SoundManager.S MotoObj.ReceiveSoundManager.SoundManager.O
 
 #SoundManagerMsgs
-MainObj.SoundManagerComm.SoundManagerMsg.S SoundPlay.SoundManagerComm.SoundManagerMsg.O
-MotoObj.SoundManagerComm.SoundManagerMsg.S SoundPlay.SoundManagerComm.SoundManagerMsg.O
-
-#EventTranslatorQueue (SoundPlay, Motion -> Main)
-MainObj.RegisterEventTranslatorQueue.EventTranslatorQueue.S MotoObj.ReceiveEventTranslatorQueue.EventTranslatorQueue.O
-MainObj.RegisterEventTranslatorQueue.EventTranslatorQueue.S SoundPlay.ReceiveEventTranslatorQueue.EventTranslatorQueue.O
+MainObj.SoundManagerComm.SoundManagerMsg.S SndPlay.SoundManagerComm.SoundManagerMsg.O
+MotoObj.SoundManagerComm.SoundManagerMsg.S SndPlay.SoundManagerComm.SoundManagerMsg.O
 
-#RemoteOPENR
-MainObj.RPOPENRSendString.char.S TCPGateway.RPOPENRSendString.char.O
-TCPGateway.RPOPENRReceiveString.char.S MainObj.RPOPENRReceiveString.char.O
+#EventTranslatorQueue (SndPlay, Motion -> Main)
+MotoObj.EventTranslatorComm.EventBase.S MainObj.EventTranslatorComm.EventBase.O
+SndPlay.EventTranslatorComm.EventBase.S MainObj.EventTranslatorComm.EventBase.O
 
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Entries ./project/ms/open-r/mw/objs/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/objs/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,2 @@
+/placehld.jnk/1.1/Tue Jul  8 22:56:29 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Repository ./project/ms/open-r/mw/objs/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/objs/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/open-r/mw/objs
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Root ./project/ms/open-r/mw/objs/CVS/Root
--- ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/objs/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Tag ./project/ms/open-r/mw/objs/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/open-r/mw/objs/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/mw/objs/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Entries ./project/ms/open-r/system/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+D/conf////
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Repository ./project/ms/open-r/system/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/open-r/system
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Root ./project/ms/open-r/system/CVS/Root
--- ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Tag ./project/ms/open-r/system/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/open-r/system/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Entries ./project/ms/open-r/system/conf/CVS/Entries
--- ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/conf/CVS/Entries	Wed Aug 10 11:03:00 2005
@@ -0,0 +1,2 @@
+/wlandflt.txt/1.18/Tue Dec 23 06:33:44 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Repository ./project/ms/open-r/system/conf/CVS/Repository
--- ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/conf/CVS/Repository	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Tekkotsu/project/ms/open-r/system/conf
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Root ./project/ms/open-r/system/conf/CVS/Root
--- ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/conf/CVS/Root	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Tag ./project/ms/open-r/system/conf/CVS/Tag
--- ../Tekkotsu_2.3/project/ms/open-r/system/conf/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/ms/open-r/system/conf/CVS/Tag	Wed Aug 10 11:03:00 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/templates/CVS/Entries ./project/templates/CVS/Entries
--- ../Tekkotsu_2.3/project/templates/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./project/templates/CVS/Entries	Wed Aug 10 11:03:27 2005
@@ -0,0 +1,8 @@
+/behavior.h/1.3/Wed Jun  1 05:48:08 2005/-kk/Ttekkotsu-2_4
+/control.h/1.2/Wed Jun  1 05:48:08 2005/-kk/Ttekkotsu-2_4
+/header.h/1.1/Wed Aug 25 01:09:24 2004/-kk/Ttekkotsu-2_4
+/implementation.cc/1.3/Wed Jun  1 05:48:08 2005/-kk/Ttekkotsu-2_4
+/statemachine.h/1.4/Wed Jun  1 05:48:08 2005/-kk/Ttekkotsu-2_4
+/statenode.h/1.5/Wed Jun  1 05:48:08 2005/-kk/Ttekkotsu-2_4
+/transition.h/1.3/Wed Jun  1 05:48:08 2005/-kk/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/project/templates/CVS/Repository ./project/templates/CVS/Repository
--- ../Tekkotsu_2.3/project/templates/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./project/templates/CVS/Repository	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Tekkotsu/project/templates
diff -urdN ../Tekkotsu_2.3/project/templates/CVS/Root ./project/templates/CVS/Root
--- ../Tekkotsu_2.3/project/templates/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./project/templates/CVS/Root	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/project/templates/CVS/Tag ./project/templates/CVS/Tag
--- ../Tekkotsu_2.3/project/templates/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./project/templates/CVS/Tag	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/project/templates/behavior.h ./project/templates/behavior.h
--- ../Tekkotsu_2.3/project/templates/behavior.h	Mon Jan 24 17:24:05 2005
+++ ./project/templates/behavior.h	Wed Jun  1 01:48:08 2005
@@ -3,7 +3,7 @@
 #define INCLUDED_CLASSNAME_h_
 
 // This is an empty Behavior template file.
-// Replace YOURNAME, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
+// Replace YOURNAMEHERE, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
 
 
 #include "Behaviors/BehaviorBase.h"
@@ -51,7 +51,7 @@
 	// a good thing, unless you really intended to copy/assign a behavior, in
 	// which case simply provide implementations for the functions)
 	CLASSNAME(const CLASSNAME&); //!< don't call (copy constructor)
-	CLASSNAME operator=(const CLASSNAME&); //!< don't call (assignment operator)
+	CLASSNAME& operator=(const CLASSNAME&); //!< don't call (assignment operator)
 };
 
 /*! @file
diff -urdN ../Tekkotsu_2.3/project/templates/control.h ./project/templates/control.h
--- ../Tekkotsu_2.3/project/templates/control.h	Tue Jan 25 18:52:52 2005
+++ ./project/templates/control.h	Wed Jun  1 01:48:08 2005
@@ -30,7 +30,7 @@
 //   - 'NULL' to return to parent control
 //   - other address to activate a child control
 //
-// Replace YOURNAME, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
+// Replace YOURNAMEHERE, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
 
 
 #include "Behaviors/Controls/ControlBase.h"
diff -urdN ../Tekkotsu_2.3/project/templates/implementation.cc ./project/templates/implementation.cc
--- ../Tekkotsu_2.3/project/templates/implementation.cc	Tue Aug 24 21:09:24 2004
+++ ./project/templates/implementation.cc	Wed Jun  1 01:48:08 2005
@@ -1,5 +1,13 @@
 #include "CLASSNAME.h"
 
+//better to put this here instead of the header
+using namespace std; 
+
+
+// [add member function implementations here...]
+
+
+
 /*! @file
  * @brief 
  * @author YOURNAMEHERE (Creator)
@@ -10,4 +18,3 @@
  * $State$
  * $Date$
  */
-
diff -urdN ../Tekkotsu_2.3/project/templates/statemachine.h ./project/templates/statemachine.h
--- ../Tekkotsu_2.3/project/templates/statemachine.h	Tue Jan 25 18:52:52 2005
+++ ./project/templates/statemachine.h	Wed Jun  1 01:48:08 2005
@@ -12,7 +12,7 @@
 // execution) and a state machine (which breaks the task down into subnodes) --
 // simply add processEvent() and DoStop(), as seen in statenode.h
 //
-// Replace YOURNAME, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
+// Replace YOURNAMEHERE, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
 
 
 #include "Behaviors/StateNode.h"
@@ -94,7 +94,7 @@
 	// a good thing, unless you really intended to copy/assign a behavior, in
 	// which case simply provide implementations for the functions)
 	CLASSNAME(const CLASSNAME&); //!< don't call (copy constructor)
-	CLASSNAME operator=(const CLASSNAME&); //!< don't call (assignment operator)
+	CLASSNAME& operator=(const CLASSNAME&); //!< don't call (assignment operator)
 };
 
 /*! @file
diff -urdN ../Tekkotsu_2.3/project/templates/statenode.h ./project/templates/statenode.h
--- ../Tekkotsu_2.3/project/templates/statenode.h	Tue Jan 25 19:02:44 2005
+++ ./project/templates/statenode.h	Wed Jun  1 01:48:08 2005
@@ -14,7 +14,7 @@
 // execution) and a state machine (which breaks the task down into subnodes),
 // but statemachine.h might provide an easier starting point for such usage.
 //
-// Replace YOURNAME, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
+// Replace YOURNAMEHERE, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
 
 
 #include "Behaviors/StateNode.h"
@@ -92,7 +92,7 @@
 	// a good thing, unless you really intended to copy/assign a behavior, in
 	// which case simply provide implementations for the functions)
 	CLASSNAME(const CLASSNAME&); //!< don't call (copy constructor)
-	CLASSNAME operator=(const CLASSNAME&); //!< don't call (assignment operator)
+	CLASSNAME& operator=(const CLASSNAME&); //!< don't call (assignment operator)
 };
 
 /*! @file
diff -urdN ../Tekkotsu_2.3/project/templates/transition.h ./project/templates/transition.h
--- ../Tekkotsu_2.3/project/templates/transition.h	Tue Jan 25 19:02:44 2005
+++ ./project/templates/transition.h	Wed Jun  1 01:48:08 2005
@@ -6,9 +6,9 @@
 //
 // Note that Transitions are in fact behaviors, and indeed, there's little
 // extra.  Only now, the Transition base class provides a fire() function for
-// you to call when your transition decides it is time.
+// you to call when your transition decides it is appropriate.
 //
-// Replace YOURNAME, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
+// Replace YOURNAMEHERE, CLASSNAME, and DESCRIPTION as appropriate, and go to town!
 
 
 #include "Behaviors/Transition.h"
@@ -26,12 +26,14 @@
 	{}
 
 	//! constructor, take an instance name
+	/* usually transitions aren't named (they can autogenerate a name), so feel free to delete this one */
 	CLASSNAME(const std::string& nm, StateNode* destination)
 		: Transition("CLASSNAME",nm,destination)
 	{}
 
 protected:
   //! constructor for subclasses (which would need to provide a different class name)
+	/* needed if you want to consider the possibility that another class might inherit from this one */
   CLASSNAME(const std::string &class_name, const std::string &instance_name, StateNode* destination)
     : Transition(class_name,instance_name,destination)
 	{}
@@ -88,7 +90,7 @@
 	// a good thing, unless you really intended to copy/assign a behavior, in
 	// which case simply provide implementations for the functions)
 	CLASSNAME(const CLASSNAME&); //!< don't call (copy constructor)
-	CLASSNAME operator=(const CLASSNAME&); //!< don't call (assignment operator)
+	CLASSNAME& operator=(const CLASSNAME&); //!< don't call (assignment operator)
 };
 
 /*! @file
diff -urdN ../Tekkotsu_2.3/tools/CVS/Entries ./tools/CVS/Entries
--- ../Tekkotsu_2.3/tools/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,37 @@
+/Makefile/1.9/Wed Aug 10 01:58:36 2005//Ttekkotsu-2_4
+/buildDocs/1.1/Sun Jul 20 19:25:38 2003//Ttekkotsu-2_4
+/buildRelease/1.61/Tue Aug  9 23:22:27 2005//Ttekkotsu-2_4
+/catmemlog/1.1.1.1/Mon Sep 30 18:19:46 2002//Ttekkotsu-2_4
+/cmake/1.1/Mon Jul 28 06:34:13 2003//Ttekkotsu-2_4
+/colorfilt/1.2/Sat Nov 22 20:33:02 2003//Ttekkotsu-2_4
+/cpymem/1.3/Wed Apr 30 03:55:58 2003//Ttekkotsu-2_4
+/crashDebug/1.21/Mon Jun  6 20:23:37 2005//Ttekkotsu-2_4
+/cvsCheckoutDate/1.1/Thu Jan 20 23:17:37 2005//Ttekkotsu-2_4
+/dist_hosts.txt/1.2/Thu Sep 25 15:32:15 2003//Ttekkotsu-2_4
+/emonLogParser/1.3/Fri Nov 12 21:34:12 2004//Ttekkotsu-2_4
+/filewordreplace/1.3/Wed Jun  1 05:48:08 2005//Ttekkotsu-2_4
+/formatList/1.1/Mon Jan 31 19:51:05 2005//Ttekkotsu-2_4
+/ftpinstall/1.7/Tue Nov 16 23:52:32 2004//Ttekkotsu-2_4
+/ftpupdate/1.7/Tue Nov 16 23:52:32 2004//Ttekkotsu-2_4
+/genCommonHeader/1.2/Wed Jun  1 05:48:08 2005//Ttekkotsu-2_4
+/installXCodeTemplates/1.2/Wed Jun  1 05:48:08 2005/-ko/Ttekkotsu-2_4
+/makelowercase/1.7/Wed Nov 17 04:48:22 2004//Ttekkotsu-2_4
+/makeuppercase/1.7/Wed Nov 17 04:48:23 2004//Ttekkotsu-2_4
+/mntmem/1.3/Tue Apr 29 21:03:09 2003//Ttekkotsu-2_4
+/mstreeput/1.3/Mon Jul 28 06:34:13 2003//Ttekkotsu-2_4
+/pm.pl/1.2/Thu Sep 25 15:32:15 2003//Ttekkotsu-2_4
+/recurse/1.1.1.1/Mon Sep 30 18:19:46 2002//Ttekkotsu-2_4
+/tool_makefile/1.2/Wed Aug 10 01:58:36 2005//Ttekkotsu-2_4
+/umntmem/1.7/Thu Aug 21 22:34:43 2003//Ttekkotsu-2_4
+D/bandit-sim////
+D/binstrswap////
+D/convertmot////
+D/easytrain////
+D/evenmodtime////
+D/filtersyswarn////
+D/mipaltools////
+D/mon////
+D/safemot////
+D/seg////
+D/test////
+D/walk_calibration////
diff -urdN ../Tekkotsu_2.3/tools/CVS/Repository ./tools/CVS/Repository
--- ../Tekkotsu_2.3/tools/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/CVS/Repository	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Tekkotsu/tools
diff -urdN ../Tekkotsu_2.3/tools/CVS/Root ./tools/CVS/Root
--- ../Tekkotsu_2.3/tools/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/CVS/Root	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/CVS/Tag ./tools/CVS/Tag
--- ../Tekkotsu_2.3/tools/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/CVS/Tag	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/Makefile ./tools/Makefile
--- ../Tekkotsu_2.3/tools/Makefile	Fri Sep 24 23:14:05 2004
+++ ./tools/Makefile	Tue Aug  9 21:58:36 2005
@@ -1,4 +1,4 @@
-COMPONENTS=binstrswap filtersyswarn evenmodtime mon mipaltools
+COMPONENTS=binstrswap filtersyswarn evenmodtime mon mipaltools easytrain
 TARGETS=all clean releaseCheck
 
 .PHONY: $(TARGETS)
@@ -13,13 +13,13 @@
 	done
 
 releaseCheck:
-	@for dir in $(dir $(shell find . -name Makefile)) ; do \
-		printf "Making tool $$dir: "; \
-		(cd $$dir && $(MAKE) clean); \
+	@for dir in $(filter-out . ./,$(dir $(shell find . -name Makefile))) ; do \
+		printf "Checking tool $$dir:\n"; \
+		$(MAKE) -C "$$dir" clean; \
 		if [ $$? -ne 0 ] ; then \
 			exit $$?; \
 		fi; \
-		(cd $$dir && $(MAKE) all); \
+		$(MAKE) -C "$$dir" all; \
 		if [ $$? -ne 0 ] ; then \
 			exit $$?; \
 		fi; \
diff -urdN ../Tekkotsu_2.3/tools/bandit-sim/CVS/Entries ./tools/bandit-sim/CVS/Entries
--- ../Tekkotsu_2.3/tools/bandit-sim/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/bandit-sim/CVS/Entries	Wed Aug 10 11:03:27 2005
@@ -0,0 +1,5 @@
+/bandit.java/1.1/Sun Jun 22 17:11:53 2003//Ttekkotsu-2_4
+/loss.aif/1.1/Sun Jun 22 17:11:53 2003/-kb/Ttekkotsu-2_4
+/manifestheader/1.1/Sun Jun 22 17:11:53 2003//Ttekkotsu-2_4
+/reward.aif/1.1/Sun Jun 22 17:11:53 2003/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/bandit-sim/CVS/Repository ./tools/bandit-sim/CVS/Repository
--- ../Tekkotsu_2.3/tools/bandit-sim/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/bandit-sim/CVS/Repository	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/bandit-sim
diff -urdN ../Tekkotsu_2.3/tools/bandit-sim/CVS/Root ./tools/bandit-sim/CVS/Root
--- ../Tekkotsu_2.3/tools/bandit-sim/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/bandit-sim/CVS/Root	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/bandit-sim/CVS/Tag ./tools/bandit-sim/CVS/Tag
--- ../Tekkotsu_2.3/tools/bandit-sim/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/bandit-sim/CVS/Tag	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/binstrswap/CVS/Entries ./tools/binstrswap/CVS/Entries
--- ../Tekkotsu_2.3/tools/binstrswap/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/binstrswap/CVS/Entries	Wed Aug 10 11:03:27 2005
@@ -0,0 +1,3 @@
+/Makefile/1.2/Sun Aug 24 21:19:21 2003//Ttekkotsu-2_4
+/binstrswap.cc/1.3/Sat Jul 26 15:35:01 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/binstrswap/CVS/Repository ./tools/binstrswap/CVS/Repository
--- ../Tekkotsu_2.3/tools/binstrswap/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/binstrswap/CVS/Repository	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/binstrswap
diff -urdN ../Tekkotsu_2.3/tools/binstrswap/CVS/Root ./tools/binstrswap/CVS/Root
--- ../Tekkotsu_2.3/tools/binstrswap/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/binstrswap/CVS/Root	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/binstrswap/CVS/Tag ./tools/binstrswap/CVS/Tag
--- ../Tekkotsu_2.3/tools/binstrswap/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/binstrswap/CVS/Tag	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/buildRelease ./tools/buildRelease
--- ../Tekkotsu_2.3/tools/buildRelease	Fri Jan 28 20:06:59 2005
+++ ./tools/buildRelease	Tue Aug  9 19:22:27 2005
@@ -30,7 +30,7 @@
 rm -rf Tekkotsu_memstick_$1.tar.gz
 
 echo "Checking out source for ${newtag}..."
-cvs -q checkout -r ${newtag} -d Tekkotsu_$1 Tekkotsu
+cvs -q -d :pserver:anonymous@cvs.tekkotsu.org:/cvs checkout -r ${newtag} -d Tekkotsu_$1 Tekkotsu
 if [ ! -d Tekkotsu_$1 ] ; then
 	echo "cvs export failed"
 	exit 1;
@@ -47,16 +47,6 @@
 	exit 1;
 fi;
 
-if [ `grep -c "Tekkotsu_doc_$1.tar.gz" docs/html/index.html` -eq 0 ] ; then
-	echo "Version mismatch with docs/html/index.html - you forgot to update the documentation link URL";
-	exit 1;
-fi;
-
-if [ `grep -c "(v$1)" docs/html/index.html` -eq 0 ] ; then
-	echo "Version mismatch with docs/html/index.html - you forgot to update the documentation link's text";
-	exit 1;
-fi;
-
 for x in project/SampleMC.h project/SampleBehavior.h ; do
 	if [ -f "$x" ] ; then
 		echo "You forgot to untag the sample files"
@@ -105,17 +95,16 @@
 
 #build memstick image tarball
 
-cd ${tmp}/Tekkotsu_$1;
-cd project;
 
 export TEKKOTSU_ROOT=..
 
 for x in TGT_ERS210 TGT_ERS220 TGT_ERS2xx; do
 	export TEKKOTSU_TARGET_MODEL=$x;
 	printf "\n\nTesting $x build\n\n\n";
-	${MAKE} clean;
+	cd ${tmp}/Tekkotsu_$1;
+	${MAKE}
 	if [ $? -ne 0 ] ; then
-		echo "Framework clean failed for $x"
+		echo "Framework build failed for $x"
 		exit 1;
 	fi;
 	cd ${tmp}/Tekkotsu_$1/tools;
@@ -127,7 +116,12 @@
 	cd ${tmp}/Tekkotsu_$1/project;
 	${MAKE};
 	if [ $? -ne 0 ] ; then
-		echo "Framework Build failed for $x"
+		echo "Project Build failed for $x"
+		exit 1;
+	fi;
+	${MAKE} sim;
+	if [ $? -ne 0 ] ; then
+		echo "sim build failed for $x"
 		exit 1;
 	fi;
 done;
@@ -159,15 +153,14 @@
 
 
 # ERS-7 build
-cd ${tmp}/Tekkotsu_$1;
-cd project;
 
 for x in TGT_ERS7; do
 	export TEKKOTSU_TARGET_MODEL=$x;
 	printf "\n\nTesting $x build\n\n\n";
-	${MAKE} clean
+	cd ${tmp}/Tekkotsu_$1;
+	${MAKE}
 	if [ $? -ne 0 ] ; then
-		echo "Framework clean failed for $x"
+		echo "Framework build failed for $x"
 		exit 1;
 	fi;
 	cd ${tmp}/Tekkotsu_$1/tools;
@@ -179,7 +172,12 @@
 	cd ${tmp}/Tekkotsu_$1/project;
 	${MAKE};
 	if [ $? -ne 0 ] ; then
-		echo "Framework Build failed for $x"
+		echo "Project Build failed for $x"
+		exit 1;
+	fi;
+	${MAKE} sim;
+	if [ $? -ne 0 ] ; then
+		echo "sim build failed for $x"
 		exit 1;
 	fi;
 done;
diff -urdN ../Tekkotsu_2.3/tools/convertmot/CVS/Entries ./tools/convertmot/CVS/Entries
--- ../Tekkotsu_2.3/tools/convertmot/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,6 @@
+/Makefile/1.8/Wed Aug 10 01:58:36 2005//Ttekkotsu-2_4
+/README.txt/1.3/Fri Apr 16 20:20:56 2004//Ttekkotsu-2_4
+/convertmot.cc/1.6/Sat Feb 12 07:38:39 2005//Ttekkotsu-2_4
+/tekkotsu.cfg/1.1/Mon Nov  8 21:48:19 2004//Ttekkotsu-2_4
+D/cmpack02-littleendian////
+D/cmpack03-littleendian////
diff -urdN ../Tekkotsu_2.3/tools/convertmot/CVS/Repository ./tools/convertmot/CVS/Repository
--- ../Tekkotsu_2.3/tools/convertmot/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/CVS/Repository	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/convertmot
diff -urdN ../Tekkotsu_2.3/tools/convertmot/CVS/Root ./tools/convertmot/CVS/Root
--- ../Tekkotsu_2.3/tools/convertmot/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/CVS/Root	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/convertmot/CVS/Tag ./tools/convertmot/CVS/Tag
--- ../Tekkotsu_2.3/tools/convertmot/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/CVS/Tag	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/convertmot/Makefile ./tools/convertmot/Makefile
--- ../Tekkotsu_2.3/tools/convertmot/Makefile	Tue Nov  9 17:15:03 2004
+++ ./tools/convertmot/Makefile	Tue Aug  9 21:58:36 2005
@@ -1,76 +1,69 @@
 
+# This Makefile will handle most aspects of compiling and
+# linking a tool against the Tekkotsu framework.  You probably
+# won't need to make any modifications, but here's the major controls
 
-#if you want to change the target model, it is recommended
-#to set the TEKKOTSU_TARGET_MODEL environment variable
+# Executable name, defaults to:
+#   `basename \`pwd\``-$(TEKKOTSU_TARGET_MODEL)
+TEKKOTSU_TARGET_MODEL?=TGT_ERS7
+BIN:=$(shell pwd | sed 's@.*/@@')-$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)))
 
-.PHONY: all tk_bd
+# Build directory
+PROJECT_BUILDDIR:=build
 
-# We use this TK_RT instead of TEKKOTSU_ROOT so things will
-# still work if TEKKOTSU_ROOT is a relative path
-TK_RT:=../..
+# Source files, defaults to all files ending matching *$(SRCSUFFIX)
+SRCSUFFIX:=.cc
+PROJ_SRC:=$(shell find . -name "*$(SRCSUFFIX)")
 
-TEMPLATE_PROJECT:=$(TK_RT)/project
-TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
-TEKKOTSU_TARGET_PLATFORM = PLATFORM_LOCAL
-include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
-FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(FILTERSYSWARN))
-COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(COLORFILT))
+# Use the containing framework, regardless of TEKKOTSU_ROOT setting (no '?=')
+TEKKOTSU_ROOT=../..
 
-BIN:=convertmot_$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)) | tr [:upper:] [:lower:])
+.PHONY: all test
 
-SRCSUFFIX=.cc
+TEMPLATE_PROJECT:=$(TEKKOTSU_ROOT)/project
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
+$(if $(shell if [ \! -r $(TEKKOTSU_ENVIRONMENT_CONFIGURATION) ] \; then echo failure \; fi),$(error An error has occured, `$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)' could not be found.  You may need to edit TEKKOTSU_ROOT in the Makefile))
 
-PROJ_OBJ:= \
-	$(PROJ_BD)/convertmot.o \
+TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(FILTERSYSWARN))
+COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(COLORFILT))
+$(shell mkdir -p $(PROJ_BD))
 
-TK_TGTS:= \
-	$(TK_BD)/Events/EventBase.o \
-	$(TK_BD)/Events/EventRouter.o \
-	$(TK_BD)/Motion/MotionManager.o \
-	$(TK_BD)/Motion/MotionSequenceMC.o \
-	$(TK_BD)/Motion/PostureEngine.o \
-	$(TK_BD)/Motion/Kinematics.o \
-	$(TK_BD)/Motion/OldKinematics.o \
-	$(TK_BD)/Shared/get_time.o \
-	$(TK_BD)/Shared/LoadSave.o \
-	$(TK_BD)/Shared/Config.o \
-	$(TK_BD)/Shared/Profiler.o \
-	$(TK_BD)/Shared/TimeET.o \
-	$(TK_BD)/Shared/WorldState.o \
-	$(TK_BD)/Wireless/Socket.o \
-	$(TK_BD)/Shared/newmat/libnewmat.a \
-	$(TK_BD)/Motion/roboop/libroboop.a
+PROJ_OBJ:=$(patsubst ./%$(SRCSUFFIX),$(PROJ_BD)/%.o,$(PROJ_SRC))
 
-LIBS:= $(TK_BD)/Motion/roboop/libroboop.a $(TK_BD)/Shared/newmat/libnewmat.a
+LIBS:= $(TK_BD)/libtekkotsu.a $(TK_BD)/../Motion/roboop/libroboop.a $(TK_BD)/../Shared/newmat/libnewmat.a
 
 DEPENDS:=$(PROJ_OBJ:.o=.d)
 
-CXXFLAGS=-g -Wall -O2 \
-         -I$(TK_RT)  \
+CXXFLAGS:=-g -Wall -O2 \
+         -I$(TEKKOTSU_ROOT) \
+         -I../../Shared/jpeg-6b $(shell xml2-config --cflags) \
          -D$(TEKKOTSU_TARGET_PLATFORM) -D$(TEKKOTSU_TARGET_MODEL) 
 
 
 all: $(BIN)
 
-$(BIN): tk_bd $(PROJ_OBJ)
+$(BIN): $(PROJ_OBJ) $(LIBS)
 	@echo "Linking $@..."
-	@g++ $(PROJ_OBJ) $(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(TK_TGTS) $(LIBS)) -o $@
+	@$(CXX) $(PROJ_OBJ) $(LIBS) $(shell xml2-config --libs) -lpthread -o $@
 
 ifeq ($(findstring clean,$(MAKECMDGOALS)),)
 -include $(DEPENDS)
 endif
 
+%.a :
+	@echo "ERROR: $@ was not found.  You may need to compile the Tekkotsu framework."
+	@echo "Press return to attempt to build it, ctl-C to cancel."
+	@read;
+	$(MAKE) -C $(TEKKOTSU_ROOT) compile
+
 %.d :
 	@mkdir -p $(dir $@)
 	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
 	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
 	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
 
-tk_bd:
-	@echo "Making Tekkotsu files..."
-	@export TEKKOTSU_TARGET_PLATFORM=PLATFORM_LOCAL && $(MAKE) -C $(TEMPLATE_PROJECT) $(TK_TGTS)
-
-
 %.o:
 	@mkdir -p $(dir $@)
 	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
@@ -81,5 +74,15 @@
 	test $$retval -eq 0; \
 
 clean:
-	rm -f $(BIN) $(PROJ_OBJ) $(DEPENDS) *~
+	rm -rf $(BIN) $(PROJECT_BUILDDIR) *~
 
+test: $(BIN)
+	@for x in * ; do \
+		if [ -r "ideal-$$x" ] ; then \
+			if diff -u "ideal-$$x" "$$x" ; then \
+				echo "Test '$$x' passed"; \
+			else \
+				echo "Test output '$$x' does not match ideal"; \
+			fi; \
+		fi; \
+	done
\ No newline at end of file
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Entries ./tools/convertmot/cmpack02-littleendian/CVS/Entries
--- ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack02-littleendian/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,13 @@
+/dance.mot/1.1/Sat Apr 26 21:17:15 2003/-kb/Ttekkotsu-2_4
+/gu_back.mot/1.1/Sat Apr 26 21:17:15 2003/-kb/Ttekkotsu-2_4
+/gu_front.mot/1.1/Sat Apr 26 21:17:15 2003/-kb/Ttekkotsu-2_4
+/gu_side.mot/1.1/Sat Apr 26 21:17:15 2003/-kb/Ttekkotsu-2_4
+/k_bump.mot/1.1/Sat Apr 26 21:17:15 2003/-kb/Ttekkotsu-2_4
+/k_dive.mot/1.1/Sat Apr 26 21:17:15 2003/-kb/Ttekkotsu-2_4
+/k_fwd.mot/1.1/Sat Apr 26 21:17:16 2003/-kb/Ttekkotsu-2_4
+/k_head.mot/1.1/Sat Apr 26 21:17:16 2003/-kb/Ttekkotsu-2_4
+/k_heads.mot/1.1/Sat Apr 26 21:17:16 2003/-kb/Ttekkotsu-2_4
+/k_hold.mot/1.1/Sat Apr 26 21:17:16 2003/-kb/Ttekkotsu-2_4
+/k_punch.mot/1.1/Sat Apr 26 21:17:16 2003/-kb/Ttekkotsu-2_4
+/readme.txt/1.1/Fri Apr 16 20:21:23 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Repository ./tools/convertmot/cmpack02-littleendian/CVS/Repository
--- ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack02-littleendian/CVS/Repository	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/convertmot/cmpack02-littleendian
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Root ./tools/convertmot/cmpack02-littleendian/CVS/Root
--- ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack02-littleendian/CVS/Root	Wed Aug 10 11:03:27 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Tag ./tools/convertmot/cmpack02-littleendian/CVS/Tag
--- ../Tekkotsu_2.3/tools/convertmot/cmpack02-littleendian/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack02-littleendian/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Entries ./tools/convertmot/cmpack03-littleendian/CVS/Entries
--- ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack03-littleendian/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,49 @@
+/b_gcntr.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/b_gdive.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/b_supp.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/bw_back.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/chicken_dance.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/dance1.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/dance2.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/dance3.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/enter_field.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/gu_back.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/gu_front.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/gu_side.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_bump.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_bw.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_diag.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_dive.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_fwd.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_fwd1.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_fwd2.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_grab.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_head.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_headh.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_heads.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_hold.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_ldive.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_punch.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_rdive.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_sdive.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_spin.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_swing.mot/1.1/Fri Apr 16 20:21:40 2004/-kb/Ttekkotsu-2_4
+/k_swing1.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_10.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_11.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_12_front.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_13.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_14_power_chunky.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_15.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_17_lightning.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_18.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_4_chest.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_5.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_6.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_8.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/k_unsw_9.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/readme.txt/1.1/Fri Apr 16 20:21:41 2004//Ttekkotsu-2_4
+/sad.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/sb_climb.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+/warmup.mot/1.1/Fri Apr 16 20:21:41 2004/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Repository ./tools/convertmot/cmpack03-littleendian/CVS/Repository
--- ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack03-littleendian/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/convertmot/cmpack03-littleendian
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Root ./tools/convertmot/cmpack03-littleendian/CVS/Root
--- ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack03-littleendian/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Tag ./tools/convertmot/cmpack03-littleendian/CVS/Tag
--- ../Tekkotsu_2.3/tools/convertmot/cmpack03-littleendian/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/convertmot/cmpack03-littleendian/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/convertmot/convertmot.cc ./tools/convertmot/convertmot.cc
--- ../Tekkotsu_2.3/tools/convertmot/convertmot.cc	Mon Nov  8 16:48:19 2004
+++ ./tools/convertmot/convertmot.cc	Sat Feb 12 02:38:39 2005
@@ -105,9 +105,9 @@
 	return 2;
 }
 
-int load_cmpack_mot(const char* filename, MotionSequence& ms);
+int load_cmpack_mot(const char* filename, MotionSequenceEngine& ms);
 void Complete(BodyState &body);
-void convert(const BodyStateMotion* frame, unsigned int num_frames, MotionSequence& ms);
+void convert(const BodyStateMotion* frame, unsigned int num_frames, MotionSequenceEngine& ms);
 
 bool convertDeg=false;
 bool compress=false;
@@ -195,7 +195,7 @@
 }
 
 
-int load_cmpack_mot(const char* filename, MotionSequence& ms) {
+int load_cmpack_mot(const char* filename, MotionSequenceEngine& ms) {
 	unsigned int num;
 	FILE * in = fopen(filename,"rb");
 	if(!in) {
@@ -253,12 +253,12 @@
 	}
 }
 
-void convert(const BodyStateMotion* frame, unsigned int num, MotionSequence& ms) {
+void convert(const BodyStateMotion* frame, unsigned int num, MotionSequenceEngine& ms) {
 	//	long initdelay=frame[0].time;
-	ms.setPlayTime(0);
+	ms.setTime(0);
 	for(unsigned int f=skip; f<num; f++) {
 		int c=0;
-		ms.setPlayTime(ms.getPlayTime()+std::max(frame[f].time,1l));
+		ms.setTime(ms.getTime()+std::max(frame[f].time,1l));
 		for(int leg=0; leg<4; leg++) //4 legs, 3 joints
 			for(int a=0; a<3; a++)
 				ms.setOutputCmd(c++,frame[f].body.leg[leg].angles[a]*(convertDeg?M_PI/180:1));
diff -urdN ../Tekkotsu_2.3/tools/convertmot/tekkotsu.cfg ./tools/convertmot/tekkotsu.cfg
--- ../Tekkotsu_2.3/tools/convertmot/tekkotsu.cfg	Mon Nov  8 16:48:19 2004
+++ ./tools/convertmot/tekkotsu.cfg	Mon Nov  8 16:48:19 2004
@@ -1,7 +1,7 @@
 ##################################################################
 ################   Tekkotsu::convertmot config   #################
 ##################################################################
-##################### $Name: tekkotsu-2_3 $ ######################
+##################### $Name: tekkotsu-2_4 $ ######################
 ####################### $Revision: 1.1 $ ########################
 ################## $Date: 2004/11/08 21:48:19 $ ##################
 ##################################################################
diff -urdN ../Tekkotsu_2.3/tools/crashDebug ./tools/crashDebug
--- ../Tekkotsu_2.3/tools/crashDebug	Fri Nov 12 16:55:47 2004
+++ ./tools/crashDebug	Mon Jun  6 16:23:37 2005
@@ -122,19 +122,16 @@
 	options=-2;
 fi;
 
-cd "$BUILDDIR"
+cd "$BUILDDIR/aperios"
 
+ln -sf MMCombo.nosnap.elf MainObj.nosnap.elf;
+ln -sf MMCombo.nosnap.elf MotoObj.nosnap.elf;
+ln -sf SndPlay.nosnap.elf SoundPlay.nosnap.elf;
 if [ "$FILENAME_CASE"="lower" ] ; then
-	ln -sf mmcombo.nosnap.elf MainObj.nosnap.elf;
-	ln -sf mmcombo.nosnap.elf MotoObj.nosnap.elf;
-	ln -sf sndplay.nosnap.elf SoundPlay.nosnap.elf;
 	if [ -z "$emonfile" ] ; then
 		emonfile=${MEMSTICK_ROOT}/open-r/emon.log;
 	fi;
 else
-	ln -sf MMCOMBO.nosnap.elf MainObj.nosnap.elf;
-	ln -sf MMCOMBO.nosnap.elf MotoObj.nosnap.elf;
-	ln -sf SNDPLAY.nosnap.elf SoundPlay.nosnap.elf;
 	if [ -z "$emonfile" ] ; then
 		emonfile=${MEMSTICK_ROOT}/OPEN-R/EMON.LOG;
 	fi;
@@ -146,11 +143,17 @@
 touch aiboDis0.ass;
 
 if [ -z "$usefile" ] ; then
+	echo "Copying emon.log from memory stick...";
 	${TEKKOTSU_ROOT}/tools/mntmem;
 	if [ $? -ne 0 ] ; then
 		echo "ERROR: Memory stick not mounted.";
 		exit 1;
 	fi;
+	cp "${emonfile}" "/tmp/${USER}_emon.log";
+	emonfile="/tmp/${USER}_emon.log";
+	${TEKKOTSU_ROOT}/tools/umntmem;
+	echo "I'm done copying the emon file from the memory stick, ${MEMSTICK_ROOT} unmounted";
+	echo "";
 fi;
 
 if [ "$runquick" ] ; then
diff -urdN ../Tekkotsu_2.3/tools/easytrain/CVS/Entries ./tools/easytrain/CVS/Entries
--- ../Tekkotsu_2.3/tools/easytrain/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,16 @@
+/ColorControlPanel.java/1.2/Thu Aug  4 20:58:05 2005//Ttekkotsu-2_4
+/ColorConverter.java/1.1/Thu Aug  4 00:27:38 2005//Ttekkotsu-2_4
+/EasyTrain.java/1.2/Thu Aug  4 20:58:05 2005//Ttekkotsu-2_4
+/HelpBox.java/1.1/Thu Aug  4 00:27:38 2005//Ttekkotsu-2_4
+/ImageData.java/1.1/Thu Aug  4 00:27:38 2005//Ttekkotsu-2_4
+/ImageShowArea.java/1.1/Thu Aug  4 00:27:38 2005//Ttekkotsu-2_4
+/Makefile/1.1/Thu Aug  4 20:58:05 2005//Ttekkotsu-2_4
+/README/1.1/Thu Aug  4 00:27:38 2005//Ttekkotsu-2_4
+/SegmentedImage.java/1.2/Thu Aug  4 20:58:05 2005//Ttekkotsu-2_4
+/TrainCanvas.java/1.2/Thu Aug  4 20:58:05 2005//Ttekkotsu-2_4
+/help.txt/1.1/Thu Aug  4 00:27:38 2005//Ttekkotsu-2_4
+/test1.png/1.1/Thu Aug  4 00:27:38 2005/-kb/Ttekkotsu-2_4
+/test2.png/1.1/Thu Aug  4 00:27:38 2005/-kb/Ttekkotsu-2_4
+/test3.png/1.1/Thu Aug  4 00:27:38 2005/-kb/Ttekkotsu-2_4
+/test4.png/1.1/Thu Aug  4 00:27:39 2005/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/easytrain/CVS/Repository ./tools/easytrain/CVS/Repository
--- ../Tekkotsu_2.3/tools/easytrain/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/easytrain
diff -urdN ../Tekkotsu_2.3/tools/easytrain/CVS/Root ./tools/easytrain/CVS/Root
--- ../Tekkotsu_2.3/tools/easytrain/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/easytrain/CVS/Tag ./tools/easytrain/CVS/Tag
--- ../Tekkotsu_2.3/tools/easytrain/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/easytrain/ColorControlPanel.java ./tools/easytrain/ColorControlPanel.java
--- ../Tekkotsu_2.3/tools/easytrain/ColorControlPanel.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/ColorControlPanel.java	Thu Aug  4 16:58:05 2005
@@ -0,0 +1,353 @@
+/** @file ColorControlPanel.java
+ *  @brief Frame for the Control panel allowing you to switch
+ *		   colors and do actions of the selected colors.
+ *
+ *	@author editted by: Eric Durback
+ *  @bug No known bugs.
+ */
+
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.io.*;
+import javax.swing.JScrollPane;
+import java.util.prefs.Preferences;
+
+public class ColorControlPanel extends JFrame implements ActionListener,
+    ListSelectionListener, ComponentListener 
+{
+	Container root;
+	JTextField colorname;
+	JList colorlist;
+	DefaultListModel list;
+	JScrollPane colorlistscroll;
+	JButton remove, clear, save, autoSelect, load, undo, help;
+	JCheckBox showColors,invert;
+	JFileChooser chooser;
+
+	String defaultName;
+
+	int curcolor;
+	int numDefault;
+
+	TrainCanvas trainCanvas;
+	ImageShowArea imageShow;
+
+	static Preferences prefs = Preferences.userNodeForPackage(ColorControlPanel.class);
+
+
+	public ColorControlPanel (TrainCanvas trainCanvas, ImageShowArea imageShow) 
+	{
+		this.trainCanvas=trainCanvas;
+		this.imageShow=imageShow;
+		imageShow.addMouseMotionListener(trainCanvas);
+		imageShow.addMouseListener(trainCanvas);
+		
+
+		numDefault = 1;
+		setSize(new Dimension (120,460));
+		setTitle("Control Panel");
+		setLocation(prefs.getInt("ColorControlPanel.location.x",50),prefs.getInt("ColorControlPanel.location.y",50));
+
+
+		setResizable(false);
+		root=this.getContentPane();
+		root.setLayout(new FlowLayout());
+
+		colorname=new JTextField(10);
+		colorname.addActionListener(this);
+		root.add(colorname);
+
+		list=new DefaultListModel();
+		colorlist=new JList(list);
+		colorlist.setFixedCellWidth(90);
+		colorlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+		colorlist.addListSelectionListener(this);
+
+		colorlistscroll=new JScrollPane(colorlist,
+		                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
+		                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+		root.add(colorlistscroll);
+		
+		addComponentListener(this);
+		
+		chooser = new JFileChooser();
+		chooser.setSelectedFile(new File("default"));
+		
+		//Adding Buttons
+
+		undo=new JButton("undo");
+		undo.addActionListener(this);
+		undo.setEnabled(false);
+		root.add(undo);
+
+		remove=new JButton("remove");
+		remove.addActionListener(this);
+		root.add(remove);
+
+		clear=new JButton("clear");
+		clear.addActionListener(this);
+		root.add(clear);
+
+		invert=new JCheckBox("invert");
+		invert.addActionListener(this);
+		root.add(invert);
+
+		showColors=new JCheckBox("all colors");
+		showColors.addActionListener(this);
+		root.add(showColors);
+
+		autoSelect=new JButton("auto select");
+		autoSelect.addActionListener(this);
+		//root.add(autoSelect);
+
+		help=new JButton("help");
+		help.addActionListener(this);
+		root.add(help);
+
+
+		save=new JButton("save");
+		save.addActionListener(this);
+		root.add(save);
+
+		load =new JButton("load");
+		load.addActionListener(this);
+		root.add(load);
+
+		setCurColor(-1);
+		setVisible(true);
+
+		
+	}
+
+
+	    
+	public void actionPerformed(ActionEvent e)
+	{
+		if (e.getSource()==save) 
+		{
+			
+			
+			int returnval=chooser.showSaveDialog(save);
+			if (returnval==JFileChooser.APPROVE_OPTION) 
+			{
+				try{
+					trainCanvas.save(chooser.getSelectedFile().getAbsolutePath());
+				    chooser.setSelectedFile(chooser.getSelectedFile());
+				    
+				}catch(Exception e2){}
+			}
+		}
+
+		if (e.getSource()==load) 
+		{
+			
+			int returnval=chooser.showOpenDialog(load);
+			if (returnval==JFileChooser.APPROVE_OPTION) 
+			{
+				
+				try{
+				    if(preLoad(chooser.getSelectedFile().getAbsolutePath()))
+				    {	        	
+				    	trainCanvas.load(chooser.getSelectedFile().getAbsolutePath());   
+				    	chooser.setSelectedFile(chooser.getSelectedFile());
+				    
+				    }
+				}
+				catch(Exception w){}
+
+			}
+			
+			setCurColor(0);
+		}
+		 
+		else if (e.getSource()==clear) 
+		{
+			trainCanvas.clear();
+		} 
+		else if (e.getSource()==invert) 
+		{
+			trainCanvas.invert();
+		} 
+		else if (e.getSource()==showColors) 
+		{
+			trainCanvas.showColors();
+		}
+		else if (e.getSource()==autoSelect) 
+		{
+		 	trainCanvas.autoSelect();
+		} 
+		else if (e.getSource()==undo) 
+		{
+		  	trainCanvas.undo();
+		} 
+		else if (e.getSource()==help) 
+		{
+		 	trainCanvas.help();
+		} 
+		else if (e.getSource()==remove) 
+		{
+		  	trainCanvas.remove((String)list.get(curcolor));
+		  	list.remove(curcolor);
+		  	setCurColor(-1);
+		  /*} else if (e.getSource()==imageview) {
+		imageShow.show();*/
+		} 
+		else if (e.getSource()==colorname) 
+		{
+			String s=e.getActionCommand();
+			if (!s.equals("")) 
+			{
+				int i;
+				for (i=0; i<list.getSize() && !list.get(i).equals(s); i++) {}
+				
+				if (i==list.getSize()) 
+				{
+				  list.addElement(s);
+				  colorname.setText("");
+				  colorlist.setSelectedIndex(i);
+				}
+			}
+		}
+	}
+
+	public void addDefaultColor()
+	{
+		String s="default" + numDefault++;
+		if (!s.equals("")) 
+		{
+			int i=0;
+		    while (i<list.getSize() && !list.get(i).equals(s)) 
+		    {
+		      	i++;
+		    }
+		    if (i==list.getSize()) 
+		    {
+		      	list.addElement(s);
+		      	colorname.setText("");
+		      	colorlist.setSelectedIndex(i);
+		    }
+
+		}
+	}
+
+	public void valueChanged(ListSelectionEvent e) 
+	{
+
+		if (!e.getValueIsAdjusting()) 
+		{
+			setCurColor(colorlist.getSelectedIndex());
+		}
+
+		if(colorlist.getSelectedIndex() < 0)
+		{
+			trainCanvas.setCurColor(null);
+			imageShow.setCurArea(null);
+			trainCanvas.plotImage();
+		}
+
+	}
+	//sets up the control panel for the new saved environment
+	public boolean preLoad(String filename) throws FileNotFoundException, IOException
+	{
+		int dotpos=filename.lastIndexOf('.');
+		if (dotpos>0) filename=filename.substring(0,dotpos);
+
+		BufferedReader areaFile=new BufferedReader(new FileReader(filename + ".save"));
+
+		areaFile.readLine();
+
+		int numColors = Integer.parseInt(areaFile.readLine());
+
+		//Clearing current color list
+		
+		int sizeL = list.getSize();
+
+		
+		for(int i=0; i<sizeL; i++ )
+		{
+		 
+		  	trainCanvas.remove((String)list.get(0));
+		  	list.remove(0);	
+		}
+
+		for(int j=0; j<numColors; j++)
+		{
+			String s = areaFile.readLine();
+			if (!s.equals("")) 
+		    {
+			    
+			    list.addElement(s);
+			    colorname.setText("");
+			    colorlist.setSelectedIndex(j);
+		  	}
+		}
+
+		//load all files into imageData
+		for(int i=0; i<imageShow.imglist.length; i++)
+		{
+			imageShow.imageData.setCurimg(i);
+			if(imageShow.isRGB)
+		    {
+				imageShow.imageData.loadRGBFileAsRGB(imageShow.imglist[i]);
+			
+		    }
+		 	else
+		    {
+				imageShow.imageData.loadYUVFileAsRGB(imageShow.imglist[i]);
+			
+		    }
+		}
+
+		
+
+		return true;
+
+	}
+
+	void setCurColor(int index) 
+	{
+		curcolor=index;
+
+		if (index<0) 
+		{
+		  	remove.setEnabled(false);
+		  	clear.setEnabled(false);
+		  	trainCanvas.setCurColor(null);
+		} 
+		else 
+		{
+		  	remove.setEnabled(true);
+		  	clear.setEnabled(true);
+		  	trainCanvas.setCurColor((String)list.get(curcolor));
+		}
+	}
+	
+	public void componentResized(ComponentEvent e) {}
+	public void componentHidden(ComponentEvent e) {}
+
+	public void componentMoved(ComponentEvent e)
+	{ 
+	
+		prefs.putInt("ColorControlPanel.location.x",getLocation().x);
+		prefs.putInt("ColorControlPanel.location.y",getLocation().y);
+
+	}
+	public void componentShown(ComponentEvent e) {}
+
+	public void enableUndo()
+	{
+		undo.setEnabled(true);
+	}
+
+	public void disableUndo()
+	{
+		undo.setEnabled(false);
+	}
+
+  
+}
diff -urdN ../Tekkotsu_2.3/tools/easytrain/ColorConverter.java ./tools/easytrain/ColorConverter.java
--- ../Tekkotsu_2.3/tools/easytrain/ColorConverter.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/ColorConverter.java	Wed Aug  3 20:27:38 2005
@@ -0,0 +1,13 @@
+public abstract class ColorConverter 
+{
+  	ColorConverter() { }
+  	public final float[] getColor(int rgb) 
+  	{
+	    int r=(rgb>>16)&0xff;
+	    int g=(rgb>>8)&0xff;
+	    int b=rgb&0xff;
+	    return getColor(r, g, b);
+  	}
+  	public abstract float[] getColor(int r, int g, int b);
+}
+
diff -urdN ../Tekkotsu_2.3/tools/easytrain/EasyTrain.java ./tools/easytrain/EasyTrain.java
--- ../Tekkotsu_2.3/tools/easytrain/EasyTrain.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/EasyTrain.java	Thu Aug  4 16:58:05 2005
@@ -0,0 +1,192 @@
+
+/** @file EasyTrain.java
+ *  @brief
+ *
+ *  Color segmentation tool for the Tekkotsu framework based on the VisionTrain and TileTrain tools
+ *
+ *	@author editted by: Eric Durback
+ *  @bug No known bugs.
+
+
+
+
+
+** NOTE FOR LINUX USERS **
+If your using linux, and you are receiving warnings about preferences, look at
+the installation notes for java on linux at the link below will help
+http://java.sun.com/j2se/1.5.0/install-linux.html 
+**************************
+
+
+TODO
+
+1. array of thumbnails - long term
+
+2. loading with incorrect images
+*/
+
+
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.io.*;
+import java.util.prefs.Preferences;
+
+public class EasyTrain extends JFrame implements ComponentListener
+{
+	int height=700, width=700;
+	public ColorControlPanel controlPanel;
+	public static ColorConverter colorConverter;
+
+	static Preferences prefs = Preferences.userNodeForPackage(EasyTrain.class);
+
+	public static void main(String args[]) 
+	{
+		if (args.length<1) 
+		{
+			usageAndExit();
+		}
+
+		colorConverter=new ColorConverter() 
+		{
+			public final float[] getColor(int r, int g, int b) 
+			{
+				float[] hsb=new float[3];
+				Color.RGBtoHSB(r, g, b, hsb);
+				float[] res=new float[2];
+				res[0]=hsb[0];
+				res[1]=hsb[1];
+				return res;
+			}
+		};
+
+		boolean isRGB=true;
+		if(args[0].equals("-isRGB"))
+			isRGB=true;
+		else if(args[0].equals("-isYUV"))
+			isRGB=false;
+		else 
+		{
+			System.out.println(args[0]+" is not valid color mode");
+			usageAndExit();
+		}
+			//get picture files
+		String files[]=new String[args.length-1];
+		for(int i=0; i<files.length; i++)
+			files[i]=args[i+1];
+			
+		//init training tool
+		EasyTrain easyTrain = new EasyTrain(isRGB,files);
+		
+		easyTrain.addWindowListener(new WindowAdapter() {
+		    public void windowClosing(WindowEvent e) { System.exit(0); } });
+		easyTrain.controlPanel.addWindowListener(new WindowAdapter() {
+		    public void windowClosing(WindowEvent e) { System.exit(0); } });
+	}
+
+	public static void usageAndExit() 
+	{
+		System.out.println("usage: java EasyTrain (-isRGB|-isYUV) filename [filename ..]");
+		System.out.println("       Using YUV images is recommended.");
+		System.out.println("       A mode must be specified.");
+		System.exit(1);
+	}
+
+	public EasyTrain(boolean isRGB, String files[]) 
+	{
+		System.out.println("Interpreting images as "+(isRGB?"RGB":"YUV")+" colorspace");
+
+		//opening image panel
+
+		try{
+		if(prefs.keys() == null) //no prefs yet
+		{
+			setDefaultPrefs();    
+		}
+		}catch(Exception e){}
+
+		setBackground(Color.black);
+		setSize(new Dimension(width, height));
+		setLocation(prefs.getInt("EasyTrain.location.x",50),prefs.getInt("EasyTrain.location.y",50));
+		setTitle("Color Spectrum");
+		Container root=this.getContentPane();
+		root.setLayout(new BorderLayout());
+
+		ImageData imageData=new ImageData(files.length);
+		ImageData YUVimageData = new ImageData(files.length);
+
+		//Thanks to martin.mueller at mni.fh-giessen.de for the bug fix:
+		if(isRGB)
+		{
+			imageData.loadRGBFileAsRGB(files[0]);
+			YUVimageData.loadRGBFileAsYUV(files[0]);
+		}
+		else
+		{ 
+			imageData.loadYUVFileAsRGB(files[0]);
+			YUVimageData.loadYUVFileAsYUV(files[0]);
+		}
+
+		ImageShowArea imageShow=new ImageShowArea(isRGB,files,imageData);
+		
+		SegmentedImage segImage = new SegmentedImage(YUVimageData,imageShow);
+		segImage.setSize(imageShow.getSize());
+
+		HelpBox helpBox = new HelpBox();
+
+		TrainCanvas trainCanvas=new TrainCanvas(segImage, imageShow, imageData, YUVimageData, controlPanel, helpBox, files);
+		root.add(trainCanvas);
+		
+		addComponentListener(this);
+		setVisible(true);
+		trainCanvas.plotImage(imageData.getSpecialHS(), imageData.getSpecialPixels());
+
+		controlPanel=new ColorControlPanel(trainCanvas, imageShow);
+		
+		trainCanvas.setControlPanel(controlPanel);
+		imageShow.setTrainCanvas(trainCanvas);
+		
+
+		imageShow.setVisible(true);
+		segImage.toFront();
+		segImage.repaint();
+	}
+
+	public void componentResized(ComponentEvent e) {}
+	public void componentHidden(ComponentEvent e) {}
+	
+	public void componentMoved(ComponentEvent e)
+	{ 	
+		prefs.putInt("EasyTrain.location.x",getLocation().x);
+		prefs.putInt("EasyTrain.location.y",getLocation().y);
+	}
+	public void componentShown(ComponentEvent e) { }
+
+	public void setDefaultPrefs()
+	{
+		prefs.putInt("EasyTrain.location.x",10);
+		prefs.putInt("EasyTrain.location.y",10);
+
+		prefs.putInt("ColorControlPanel.location.x",780);
+		prefs.putInt("ColorControlPanel.location.y",50);
+
+		prefs.putInt("HelpBox.location.x",100);
+		prefs.putInt("HelpBox.location.y",100);
+
+		prefs.putInt("ImageShowArea.location.x",50);
+		prefs.putInt("ImageShowArea.location.y",200);
+
+		prefs.putInt("SegmentedImage.location.x",400);
+		prefs.putInt("SegmentedImage.location.y",200);
+
+	}  
+  
+}
+
+
+
+
diff -urdN ../Tekkotsu_2.3/tools/easytrain/HelpBox.java ./tools/easytrain/HelpBox.java
--- ../Tekkotsu_2.3/tools/easytrain/HelpBox.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/HelpBox.java	Wed Aug  3 20:27:38 2005
@@ -0,0 +1,88 @@
+/** @file HelpBox.java
+ *  @brief Frame for a help window
+ *
+ *	@author Eric Durback
+ *  @bug No known bugs.
+ */
+
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.io.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.util.prefs.Preferences;
+
+public class HelpBox extends JFrame implements ComponentListener, FocusListener 
+{
+	
+
+	static Preferences prefs = Preferences.userNodeForPackage(ImageShowArea.class);
+
+	JTextArea jtextArea;
+	JScrollPane HelpScroll;
+
+
+  	public static void main(String args[]) 
+  	{}
+ 
+ 	public void focusGained(FocusEvent e) {} 
+ 
+ 	public void focusLost(FocusEvent e) {}
+
+	public static void usageAndExit() 
+	{
+		System.out.println("usage: java ImageShow (-isRGB|-isYUV) raw_image [raw images]");
+		System.exit(1);		
+	}
+
+  	public HelpBox ()
+  	{
+     
+	    setBackground(Color.black);
+	    setSize(450,600);
+	    setTitle("EasyTrain Help");
+	    setLocation(prefs.getInt("HelpBox.location.x",50),prefs.getInt("HelpBox.location.y",50));
+	    
+	    jtextArea = new JTextArea();
+	    char buf[] = new char[8192];
+		int n;
+	    
+	    try{
+	    
+		    BufferedReader in = new BufferedReader(new FileReader("help.txt"));
+			while ((n = in.read(buf, 0, buf.length)) > 0)
+			{
+			    jtextArea.append(new String(buf, 0, n));
+			}
+			in.close();
+		} catch(Exception e){}
+	    
+	    HelpScroll = new JScrollPane(jtextArea,
+		                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
+		                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+	    
+	    
+	  	this.getContentPane().add(HelpScroll);
+	 
+		jtextArea.setEditable(false);
+	  	
+	    addComponentListener(this);
+	    addFocusListener(this);  
+    
+	}
+
+	public void componentResized(ComponentEvent e) {    }
+	public void componentHidden(ComponentEvent e) { }
+  
+	public void componentMoved(ComponentEvent e)
+  	{ 
+		prefs.putInt("HelpBox.location.x",getLocation().x);
+		prefs.putInt("HelpBox.location.y",getLocation().y);
+  
+  	}
+  	public void componentShown(ComponentEvent e) { }
+
+}
diff -urdN ../Tekkotsu_2.3/tools/easytrain/ImageData.java ./tools/easytrain/ImageData.java
--- ../Tekkotsu_2.3/tools/easytrain/ImageData.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/ImageData.java	Wed Aug  3 20:27:38 2005
@@ -0,0 +1,336 @@
+/** @file ImageData.java
+ *  @brief 
+ *
+ *  File that contains the functions for the data
+ *  contained in each image.
+ *
+ *	@author editted by: Eric Durback
+ *  @bug No known bugs.
+ */
+
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.io.*;
+import java.awt.image.Raster;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.ImageInputStream;
+import javax.imageio.stream.MemoryCacheImageInputStream;
+
+
+public class ImageData extends Frame {
+  Toolkit toolkit;
+
+  public int[][]retdata;
+  public int[][] data;
+  public int[] alldata;
+
+  public float[][] RG;  //change all to [][]
+  public float[][] HS;
+  public float[][] HB;
+  public float[][] SB;
+  
+  public float[] allHS;
+
+  public int image_width;
+  public int image_height;
+  
+  public int numImages;
+  public int curImage;
+  
+  public ImageData()
+  {
+  	this(1);
+  }
+  
+  public ImageData(int numI) 
+  {
+    toolkit=Toolkit.getDefaultToolkit();
+    curImage = 0;
+    numImages = numI;
+    data = new int[numI][];
+    retdata = new int[numI][];
+    HS = new float[numI][];
+    HB = new float[numI][];
+    RG = new float[numI][];
+    SB = new float[numI][];
+    
+  }
+
+  public int[] getPixels() 
+  {
+  	return retdata[curImage];
+  }
+  
+  public int[][] getAllPixels() {
+    return retdata;
+  }
+  
+   public int[] getSpecialPixels() {
+    return alldata;
+  }
+
+	// assumes retdata holds RGB
+  public float[] getRG() {
+    if (RG[curImage]==null) {
+      RG[curImage]=new float[retdata[curImage].length*2];
+      for (int i=0; i<retdata[curImage].length; i++) {
+        float r=(float)((retdata[curImage][i]>>16)&0xFF);
+        float g=(float)((retdata[curImage][i]>>8)&0xFF);
+        float b=(float)(retdata[curImage][i]&0xFF);
+        RG[curImage][i*2]=r/(r+g+b);
+        RG[curImage][i*2+1]=g/(r+g+b);
+      }
+    }
+    return RG[curImage];
+  }
+
+	// assumes retdata holds RGB
+  public float[] getHS() 
+  {
+    if (HS[curImage]==null) 
+    {
+      HS[curImage]=new float[retdata[curImage].length*2];
+      float[] hsb=new float[3];
+      for (int i=0; i<retdata[curImage].length; i++) 
+      {
+        int r=(retdata[curImage][i]>>16)&0xFF;
+        int g=(retdata[curImage][i]>>8)&0xFF;
+        int b=retdata[curImage][i]&0xFF;
+        Color.RGBtoHSB(r, g, b, hsb);
+        HS[curImage][i*2]=hsb[0];
+        HS[curImage][i*2+1]=hsb[1];
+      }
+    }
+    return HS[curImage];
+  }
+  
+  public float[] getSpecialHS() 
+  {
+  	if (allHS==null) 
+    {
+      allHS=new float[alldata.length*2];
+      float[] hsb=new float[3];
+      for (int i=0; i<alldata.length; i++) 
+      {
+        int r=(alldata[i]>>16)&0xFF;
+        int g=(alldata[i]>>8)&0xFF;
+        int b=alldata[i]&0xFF;
+        Color.RGBtoHSB(r, g, b, hsb);
+        allHS[i*2]=hsb[0];
+        allHS[i*2+1]=hsb[1];
+      }
+    }
+    return allHS;
+  	
+  }
+
+  public float[][] getAllHS()
+  {
+    
+    for(int k=0; k<numImages; k++)
+    {
+	    if (HS[k]==null && retdata[k] != null) 
+	    {
+	      HS[k]=new float[retdata[k].length*2];
+	      float[] hsb=new float[3];
+	      for (int i=0; i<retdata[k].length; i++) 
+	      {
+	        int r=(retdata[k][i]>>16)&0xFF;
+	        int g=(retdata[k][i]>>8)&0xFF;
+	        int b=retdata[k][i]&0xFF;
+	        Color.RGBtoHSB(r, g, b, hsb);
+	        HS[k][i*2]=hsb[0];
+	        HS[k][i*2+1]=hsb[1];
+	      }
+	    }
+    }
+    return HS;
+  }
+
+	// assumes retdata holds RGB
+  public float[] getHB() {
+    if (HB[curImage]==null) {
+      HB[curImage]=new float[retdata[curImage].length*2];
+      float[] hsb=new float[3];
+      for (int i=0; i<retdata[curImage].length; i++) {
+        int r=(retdata[curImage][i]>>16)&0xFF;
+        int g=(retdata[curImage][i]>>8)&0xFF;
+        int b=retdata[curImage][i]&0xFF;
+        Color.RGBtoHSB(r, g, b, hsb);
+        HB[curImage][i*2]=hsb[0];
+        HB[curImage][i*2+1]=hsb[2];
+      }
+    }
+    return HB[curImage];
+  }
+
+	// assumes retdata holds RGB
+  public float[] getSB() {
+    if (SB[curImage]==null) {
+      SB[curImage]=new float[retdata[curImage].length*2];
+      float[] hsb=new float[3];
+      for (int i=0; i<retdata[curImage].length; i++) {
+        int r=(retdata[curImage][i]>>16)&0xFF;
+        int g=(retdata[curImage][i]>>8)&0xFF;
+        int b=retdata[curImage][i]&0xFF;
+        Color.RGBtoHSB(r, g, b, hsb);
+        SB[curImage][i*2]=hsb[1];
+        SB[curImage][i*2+1]=hsb[2];
+      }
+    }
+    return SB[curImage];
+  }
+  
+ 
+
+  void loadFile(String filename) 
+  {
+    // System.out.println("Loading: " + filename);
+    Image image=toolkit.createImage(filename);
+    MediaTracker mediaTracker=new MediaTracker(this);
+    mediaTracker.addImage(image, 0);
+    try {
+      mediaTracker.waitForID(0);
+    } catch (InterruptedException e) {
+      System.out.println(e);
+      System.exit(1);
+    }
+    image_width=image.getWidth(this);
+    image_height=image.getHeight(this);
+
+    BufferedImage bi = new BufferedImage(image_width, image_height,
+                                         BufferedImage.TYPE_INT_RGB);
+    Graphics big = bi.createGraphics();
+    big.drawImage(image,0,0,null);
+    data[curImage]=bi.getRGB(0,0,image_width,image_height,null,0,image_width);
+    
+  }
+
+	public void loadYUVJPEG(String filename) {
+		try {
+			ImageInputStream jpegStream=new MemoryCacheImageInputStream(new FileInputStream(filename));
+			ImageReader jpegReader=(ImageReader)ImageIO.getImageReadersByFormatName("jpeg").next();
+			jpegReader.setInput(jpegStream); 
+			Raster decoded=jpegReader.readRaster(0,null);
+			image_width=decoded.getWidth();
+			image_height=decoded.getHeight();
+			data[curImage] = new int[image_width*image_height];
+			int off=0;
+			for(int y=0; y<image_height; y++)
+				for(int x=0; x<image_width; x++) {
+					int yc=decoded.getSample(x,y,0);
+					int uc=decoded.getSample(x,y,2);
+					int vc=decoded.getSample(x,y,1);
+					data[curImage][off++]=(yc<<16) | (uc<<8) | vc;
+				}
+		} catch(Exception ex) { ex.printStackTrace(); }
+	}
+
+  public void loadYUVFileAsRGB(String filename) {
+    loadFile(filename);
+    YUV2RGB();
+    retdata[curImage]=data[curImage];
+  }
+
+	public void loadRGBFileAsYUV(String filename) {
+		if(filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".JPG") || filename.endsWith(".JPEG"))
+			loadYUVJPEG(filename);
+		else {
+			loadFile(filename);
+			RGB2YUV();
+		}
+    retdata[curImage]=data[curImage];
+	}
+
+	public void loadRGBFileAsRGB(String filename) {
+    loadFile(filename);
+    retdata[curImage]=data[curImage];
+	}
+
+	public void loadYUVFileAsYUV(String filename) {
+    loadFile(filename);
+    retdata[curImage]=data[curImage];
+	}
+
+	// this isn't the "real" conversion, but a quick approx.
+	// it's the same that's used in tekkotsumon's VisionListener
+  public void YUV2RGB() {
+    for (int i=0; i<data[curImage].length; i++) {
+      int y=(int)((data[curImage][i]>>16)&0xFF);
+      int u=(int)((data[curImage][i]>>8)&0xFF);
+      int v=(int)(data[curImage][i]&0xFF);
+      u=u*2-255;
+      v=v*2-255;
+      int r=y+u;
+      int b=y+v;
+      u=u>>1;
+      v=(v>>2)-(v>>4);
+      int g=y-u-v;
+      if (r<0) r=0; if (g<0) g=0; if (b<0) b=0;
+      if (r>255) r=255; if (g>255) g=255; if (b>255) b=255;
+
+      data[curImage][i]= (r<<16) | (g<<8) | b;
+    }
+  }
+
+	// this isn't the "real" conversion, nor a quick approx, but
+	// it will get as close as possible to an exact undo of the YUV2RGB conversion
+	// we use in VisionListener (and here)
+  public void RGB2YUV() {
+    for (int i=0; i<data[curImage].length; i++) {
+      int r=(int)((data[curImage][i]>>16)&0xFF);
+      int g=(int)((data[curImage][i]>>8)&0xFF);
+      int b=(int)(data[curImage][i]&0xFF);
+			int y=(int)( 8*r/27 +  g/ 9  + 16*b/27 - 203/27);
+			int u=(int)(19*r/54 -  g/18  -  8*b/27 +3544/27);
+			int v=(int)(-4*r/27 +4*g/ 9  -  8*b/27 +3544/27); 
+      if (y<0) y=0; if (u<0) u=0; if (v<0) v=0;
+      if (y>255) y=255; if (u>255) u=255; if (v>255) v=255;
+      data[curImage][i]= (y<<16) | (u<<8) | v;
+    }
+  }
+
+  public void loadFullRGBFilesAsRGB(String files[]) 
+  {
+    for (int i=0; i<files.length; i++) 
+    {
+	  
+	  loadFile(files[i]);
+      
+      if (i==0) alldata=new int[files.length*data[curImage].length];
+			//for (int j=0; j<data.length; j++)
+			//retdata[j+(i*data.length)]=data[j];
+      int l=0;
+	  for (int j=i; j<retdata[curImage].length; j+=files.length)
+	  {
+	  	alldata[j]=data[curImage][l++];
+	  }
+    }
+  }
+
+  public void loadFullYUVFilesAsRGB(String files[]) 
+  {
+    for (int i=0; i<files.length; i++) 
+    {
+      loadFile(files[i]);
+      if (i==0) alldata=new int[files.length*data[curImage].length];
+      YUV2RGB();
+      int l=0;
+      for (int j=i; j<alldata.length; j+=files.length)
+        alldata[j]=data[curImage][l++];
+    }
+  }
+  
+  public void setCurimg(int curimg)
+  {
+  	curImage = curimg; 
+  
+  }
+  
+}
diff -urdN ../Tekkotsu_2.3/tools/easytrain/ImageShowArea.java ./tools/easytrain/ImageShowArea.java
--- ../Tekkotsu_2.3/tools/easytrain/ImageShowArea.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/ImageShowArea.java	Wed Aug  3 20:27:38 2005
@@ -0,0 +1,277 @@
+/** @file ImageShowArea.java
+ *  @brief 
+ *
+ *  Frame for showing the image
+ *
+ *	@author editted by: Eric Durback
+ *  @bug No known bugs.
+ */
+
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.io.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.util.prefs.Preferences;
+
+public class ImageShowArea extends JFrame implements KeyListener, ComponentListener, FocusListener 
+{
+	BufferedImage _image;
+	String[] imglist;
+	byte[] tmap;
+	ImageData imageData,YUVimageData;
+	int curimg;
+	int numImages;
+	boolean isRGB;
+	boolean sizeFixed;
+
+	Polygon curPoly;
+	Area curArea;
+	TrainCanvas trainCanvas;
+	double resizedX;
+	double resizedY;
+	double lastX,lastY;
+	
+	static Preferences prefs = Preferences.userNodeForPackage(ImageShowArea.class);
+ 
+	public void focusGained(FocusEvent e) {} 
+
+	public void focusLost(FocusEvent e) {}
+
+	public static void usageAndExit() 
+	{
+		System.out.println("usage: java ImageShow (-isRGB|-isYUV) raw_image [raw images]");
+		System.exit(1);		
+	}
+
+	public ImageShowArea (boolean isRGB, String args[], ImageData imgData) 
+	{
+	  	curPoly = null;
+	  	curArea = null;
+	  	resizedX=1.0;
+	  	resizedY=1.0;
+	  
+	  
+		numImages = args.length;
+		imageData=imgData;
+		YUVimageData = new ImageData(1);
+		sizeFixed = false;
+
+		this.isRGB=isRGB;
+		if(isRGB)
+		{
+			imageData.loadRGBFileAsRGB(args[0]);
+			imageData.loadFullRGBFilesAsRGB(args);
+		}
+		else
+		{
+			imageData.loadYUVFileAsRGB(args[0]);
+			imageData.loadFullYUVFilesAsRGB(args);
+		}
+
+		int[] data=imageData.getPixels();
+
+		setBackground(Color.black);
+		setSize(imageData.image_width*2, imageData.image_height*2);
+		setTitle((curimg+1) + ": " + args[0]);
+		setLocation(prefs.getInt("ImageShowArea.location.x",50),prefs.getInt("ImageShowArea.location.y",50));
+
+		_image=new BufferedImage(imageData.image_width, imageData.image_height,
+		    BufferedImage.TYPE_INT_RGB);
+		    
+		lastX = (double)getWidth();
+		lastY = (double)getHeight();
+
+		showImage(data, tmap, imageData.image_width, imageData.image_height);
+
+		imglist=new String[numImages];
+		curimg=0;
+		imageData.setCurimg(curimg);
+		
+		//putting images names into the image list
+		for (int i=0; i<numImages; i++) 
+		{
+			imglist[i]=args[i];
+		}
+
+		addKeyListener(this);
+		addComponentListener(this);
+		addFocusListener(this);  
+
+	}
+
+	void showImage(int[] data, byte[] tmap, int width, int height) 
+	{
+		_image.getRaster().setDataElements(0,0,width,height,data);
+		repaint();
+	}
+
+	public void setCurArea(Area _curArea)
+	{
+		curArea = _curArea;
+		repaint();
+	}
+
+	public void setCurPoly(Polygon _curPoly)
+	{
+		curPoly = _curPoly;
+		repaint();
+	}
+
+	public void paint(Graphics graphics) 
+	{
+		Dimension sz=getSize();
+		if (_image!=null)
+		  graphics.drawImage(_image, 0, 0, sz.width, sz.height, null);
+
+		graphics.setColor(Color.white);
+		if (curArea!=null)
+		  ((Graphics2D)graphics).draw(curArea);
+
+		if (curPoly!=null)
+		  ((Graphics2D)graphics).draw(curPoly);
+	}
+
+	public int getPixel(int x, int y) 
+	{
+		Dimension sz=getSize();
+		x=(x*_image.getWidth())/sz.width;
+		y=(y*_image.getHeight())/sz.height;
+		return _image.getRGB(x, y);
+	}
+
+	public void imageChange(int curimg)
+	{
+		imageData.setCurimg(curimg);
+
+		if(isRGB)
+		{
+		  	imageData.loadRGBFileAsRGB(imglist[curimg]);
+		  	YUVimageData.loadRGBFileAsYUV(imglist[curimg]);
+		}
+		else
+		{
+		  	imageData.loadYUVFileAsRGB(imglist[curimg]);
+		  	YUVimageData.loadYUVFileAsYUV(imglist[curimg]);
+		}
+					
+		setTitle(getNewTitle());
+		trainCanvas.segImage.setTitle("Segmented " + getNewTitle());
+		  
+		if(trainCanvas.curImageArea != null)
+		 	setCurArea(trainCanvas.curImageArea[curimg]);
+		  
+		trainCanvas.segImage.setImageData(YUVimageData);
+		  			
+		int[] data=imageData.getPixels();
+		showImage(data, tmap, imageData.image_width, imageData.image_height);	
+
+	}
+
+	public String getNewTitle()
+	{
+		return (curimg+1) + ": " +imglist[curimg];
+	}
+
+	public void keyPressed(KeyEvent e) 
+	{
+		if (e.getKeyCode()==KeyEvent.VK_LEFT ||
+		    e.getKeyCode()==KeyEvent.VK_UP ||
+		    e.getKeyCode()==KeyEvent.VK_PAGE_UP ||
+		    e.getKeyCode()==KeyEvent.VK_KP_UP ||
+		    e.getKeyCode()==KeyEvent.VK_KP_LEFT) 
+		{
+		  	curimg--;
+		  
+		  	if (curimg<0) curimg+=imglist.length;
+				
+		  	imageChange(curimg);
+		} 
+		else if (e.getKeyCode()==KeyEvent.VK_RIGHT ||
+		    e.getKeyCode()==KeyEvent.VK_DOWN ||
+		    e.getKeyCode()==KeyEvent.VK_PAGE_DOWN ||
+		    e.getKeyCode()==KeyEvent.VK_KP_DOWN ||
+		    e.getKeyCode()==KeyEvent.VK_KP_RIGHT) 
+		{
+		  	curimg++;
+		  	
+		  	if (curimg>=imglist.length) curimg-=imglist.length;
+		  
+		  	imageChange(curimg);
+		}
+	}
+	
+	public void keyReleased(KeyEvent e) { }
+	public void keyTyped(KeyEvent e) { }
+
+	public void componentResized(ComponentEvent e) 
+	{            	
+
+		double changeX = (double)getWidth() / lastX;
+		double changeY = (double)getHeight() / lastY;
+
+
+		if(!sizeFixed)
+		{
+		  	
+		  	//maintain aspect ratio at min sizes
+		  	if(getWidth()<= 120 || getHeight() <= 98)
+		  	{
+		  		
+		  		changeX = 120 / lastX;
+		        changeY = 98 / lastY;
+		  		this.setSize(120,98);	  		
+		  	}
+		  	
+		  	else if(   (changeX > changeY && getWidth() > lastX  ) 
+		  	   || (changeX < changeY && getWidth() < lastX  )  )
+		  	{
+		  		changeY = changeX;
+		  		this.setSize(getWidth(),(int)(lastY*changeX));
+		  	}
+		  	else
+		  	{
+		  		changeX = changeY;
+		  		this.setSize((int)(lastX*changeY),getHeight());
+		  	}
+		  	sizeFixed = true;
+
+		}
+		else
+		{
+		  	lastX = (double)getWidth(); 
+		  	lastY = (double)getHeight();
+		  	
+		  	resizedX = ((double)getWidth()) / (double)(imageData.image_width * 2);
+		  	resizedY = ((double)getHeight()) / (double)(imageData.image_height * 2);
+		  	  	
+		  	trainCanvas.resizeAreas(resizedX,resizedY,changeX,changeY);
+		  	
+		  	sizeFixed = false;
+		}  	
+	}
+
+	public void componentHidden(ComponentEvent e) { }
+	public void componentMoved(ComponentEvent e)
+	{ 
+	
+		prefs.putInt("ImageShowArea.location.x",getLocation().x);
+		prefs.putInt("ImageShowArea.location.y",getLocation().y);
+
+	}
+	public void componentShown(ComponentEvent e) { }
+
+	public void setTrainCanvas(TrainCanvas t)
+	{
+		trainCanvas = t;
+	}
+
+	public int getCurImage()
+	{
+		return curimg;
+	}
+  
+}
diff -urdN ../Tekkotsu_2.3/tools/easytrain/Makefile ./tools/easytrain/Makefile
--- ../Tekkotsu_2.3/tools/easytrain/Makefile	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/Makefile	Thu Aug  4 16:58:05 2005
@@ -0,0 +1,35 @@
+SRCS:=$(shell find . -name "*.java")
+
+OBJS:=${SRCS:.java=.class}
+
+CXX=javac
+CURDIR:=$(shell pwd | sed 's/.*\///')
+
+# SEP is to use ';' on windows and ':' on unix because windows is mentally deficient
+SEP:=$(shell if [ "`uname`" = "CYGWIN" -o "`uname`" \> "CYGWIN" -a "`uname`" \< "CYGWIO" ] ; then echo ";" ; else echo ":" ; fi )
+CXXFLAGS=-deprecation -classpath ".$(SEP)../mon/ftp.jar"
+
+.PHONY: all clean msg build clearbuildlist
+
+all: clearbuildlist build
+
+%.class: %.java
+	@printf " $<" >> tmp_buildList.txt;
+
+clearbuildlist:
+	@rm -f tmp_buildList.txt;
+
+tmp_buildList.txt: ${OBJS}
+#	@echo "Build list constructed...";
+
+build: tmp_buildList.txt
+	@if [ -r tmp_buildList.txt ] ; then \
+		$(if $(shell which $(CXX)), \
+			echo "Compiling`cat tmp_buildList.txt`..."; \
+			$(CXX) $(CXXFLAGS) `cat tmp_buildList.txt`; , \
+			printf "  ***** WARNING: You don't have java... skipping EasyTrain *****\n"; \
+		) \
+	fi;
+
+clean:
+	rm -f $(OBJS) *~ 
diff -urdN ../Tekkotsu_2.3/tools/easytrain/README ./tools/easytrain/README
--- ../Tekkotsu_2.3/tools/easytrain/README	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/README	Wed Aug  3 20:27:38 2005
@@ -0,0 +1,19 @@
+EasyTrain -- color image segmentation training program for CMVision.
+
+To compile EasyTrain, do:
+
+  javac *.java
+
+To try out EasyTrain after compilation, do:
+
+  java EasyTrain -isYUV *.png
+
+Some test images are provided along with the source.
+
+========================================================
+
+Credits:  EasyTrain was created by Eric Durback, Matt Carson, and
+Dave Touretzky, with help from Ethan Tira-Thompson, based on an earlier
+program (VisionTrain) by Alok Ladsariya, all at Carnegie Mellon, and 
+using design ideas from yet another program (TileTrain) by Rob Salkin
+and Shawn Turner at SUNY Albany.
diff -urdN ../Tekkotsu_2.3/tools/easytrain/SegmentedImage.java ./tools/easytrain/SegmentedImage.java
--- ../Tekkotsu_2.3/tools/easytrain/SegmentedImage.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/SegmentedImage.java	Thu Aug  4 16:58:05 2005
@@ -0,0 +1,235 @@
+/** @file SegmentedImage.java
+ *  @brief Frame for displaying the segmented image        
+ *
+ *	@author editted by: Eric Durback
+ *  @bug No known bugs.
+ */
+
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.io.*;
+import java.util.prefs.Preferences;
+
+
+public class SegmentedImage extends JFrame implements KeyListener, MouseListener, ComponentListener
+{
+	BufferedImage image;
+	ImageData imageData;
+	ImageShowArea imageShow;
+	byte[] tmap;
+	int [][] averageColors;
+	Point hint;
+	
+	static Preferences prefs = Preferences.userNodeForPackage(SegmentedImage.class);
+
+  
+	public SegmentedImage (ImageData _imageData, ImageShowArea _imageShow) 
+	{
+		//STUB
+		
+		imageData = _imageData;
+		image = null;
+		imageShow = _imageShow;
+		
+		setBackground(Color.GRAY);
+		setLocation(prefs.getInt("SegmentedImage.location.x",50),prefs.getInt("SegmentedImage.location.y",50));
+        setTitle("Segmented " + imageShow.getNewTitle());
+	
+		addKeyListener(this);
+		addComponentListener(this);
+		addMouseListener(this);
+
+		setVisible(true);
+		repaint();
+	}
+
+	public void setImageData(ImageData _imageData)
+	{
+	
+		imageData = _imageData;
+		reSegment(tmap,averageColors);
+	}
+
+	public void reSegment(byte[] _tmap, int[][]_averageColors)
+	{
+
+		tmap = _tmap;
+		averageColors = _averageColors;
+
+		int[] data=imageData.getPixels();
+
+		IndexColorModel cmodel=makeColorModel(averageColors);
+
+		if (tmap==null || cmodel==null) return;
+
+		setSize(imageData.image_width*2, imageData.image_height*2);
+		image = new BufferedImage(imageData.image_width, imageData.image_height,
+		    BufferedImage.TYPE_BYTE_INDEXED,cmodel);
+
+		segmentImage(data, tmap, imageData.image_width, imageData.image_height);
+
+		repaint();
+	}
+
+	public void paint(Graphics graphics) 
+	{
+		
+		Dimension sz=getSize();
+		if (image!=null)
+		    graphics.drawImage(image, 0, 0, sz.width, sz.height, null);
+	  
+
+		if(hint!=null && image!=null)
+		{
+			graphics.drawRect(hint.x-2, hint.y-2, 5, 5);
+		}
+
+
+
+	}
+
+	public void showHint(Point p)
+	{
+
+		hint = p;
+		repaint();
+	}
+
+
+	public void segmentImage(int[] data, byte[] tmap, int width, int height) 
+	{
+		
+		int size_y=16, size_u=64, size_v=64;
+		byte[] imgdata=new byte[data.length];
+
+		for (int i=0; i<data.length; i++) 
+		{
+		    int y=(data[i]>>16)&0xff;
+		    int u=(data[i]>>8)&0xff;
+		    int v=data[i]&0xff;
+		    y=y>>4;
+		    u=u>>2;
+		    v=v>>2;
+		    imgdata[i]=tmap[(y*size_u+u)*size_v+v];
+		}
+
+		image.getRaster().setDataElements(0,0,width,height,imgdata);
+		repaint();
+	}
+
+	public IndexColorModel makeColorModel(int[][] averageColors) 
+	{
+		if (averageColors == null)
+		    return null;
+		
+		byte[] byte_cmap=new byte[(averageColors.length+1)*3];
+
+
+		int i;
+		for (i=1; i<averageColors.length+1; i++) 
+		{
+		    //byte_cmap[i*3]=(byte) ((cmap[i]>>16) & 0xff);
+		    //byte_cmap[i*3+1]=(byte) ((cmap[i]>>8) & 0xff);
+		    //byte_cmap[i*3+2]=(byte) (cmap[i] & 0xff);
+		    byte_cmap[i*3] = (byte)(averageColors[i-1][0]&0xff);
+		    byte_cmap[i*3+1] = (byte)(averageColors[i-1][1]&0xff);
+		    byte_cmap[i*3+2] = (byte)(averageColors[i-1][2]&0xff);
+		}
+
+		byte_cmap[0] = (byte)128;
+		byte_cmap[1] = (byte)128;
+		byte_cmap[2] = (byte)128;
+
+		IndexColorModel cmodel=new IndexColorModel(7, averageColors.length + 1, byte_cmap,
+						   0, false); 
+		return cmodel;
+	}
+
+	public int getPixel(int x, int y) 
+	{
+		Dimension sz=getSize();
+		x=(x * image.getWidth()) / sz.width;
+		y=(y * image.getHeight()) / sz.height;
+		return image.getRGB(x, y);
+	}
+
+	public void keyPressed(KeyEvent e) 
+	{
+		if (e.getKeyCode()==KeyEvent.VK_LEFT ||
+		    e.getKeyCode()==KeyEvent.VK_UP ||
+		    e.getKeyCode()==KeyEvent.VK_PAGE_UP ||
+		    e.getKeyCode()==KeyEvent.VK_KP_UP ||
+		    e.getKeyCode()==KeyEvent.VK_KP_LEFT) 
+		{
+			imageShow.curimg--;
+
+			if (imageShow.curimg<0) imageShow.curimg+=imageShow.imglist.length;
+				
+			imageShow.imageChange(imageShow.curimg);
+		} 
+		else if (e.getKeyCode()==KeyEvent.VK_RIGHT ||
+		    e.getKeyCode()==KeyEvent.VK_DOWN ||
+		    e.getKeyCode()==KeyEvent.VK_PAGE_DOWN ||
+		    e.getKeyCode()==KeyEvent.VK_KP_DOWN ||
+		    e.getKeyCode()==KeyEvent.VK_KP_RIGHT) 
+		{
+			imageShow.curimg++;
+
+			if (imageShow.curimg>=imageShow.imglist.length) imageShow.curimg-=imageShow.imglist.length;
+
+			imageShow.imageChange(imageShow.curimg);
+		}
+	}
+	public void keyReleased(KeyEvent e) { }
+	public void keyTyped(KeyEvent e) { }
+
+	public void mousePressed(MouseEvent e) 
+	{
+		
+	}
+
+	public void mouseDragged(MouseEvent e) 
+	{	  
+		
+	}
+
+	public void mouseReleased(MouseEvent e) 
+	{
+
+	}
+
+	public void mouseMoved(MouseEvent e)
+	{
+		
+	}
+
+	public void mouseClicked(MouseEvent e){}
+
+	public void mouseExited(MouseEvent e)
+	{
+
+		//imagePlace = null;
+		repaint();
+
+	}
+
+	public void mouseEntered(MouseEvent e){}
+	
+	public void componentResized(ComponentEvent e) {}
+	public void componentHidden(ComponentEvent e) { }
+	
+	public void componentMoved(ComponentEvent e)
+	{ 
+	
+		prefs.putInt("SegmentedImage.location.x",getLocation().x);
+		prefs.putInt("SegmentedImage.location.y",getLocation().y);
+
+	}
+	public void componentShown(ComponentEvent e) { }
+
+}
diff -urdN ../Tekkotsu_2.3/tools/easytrain/TrainCanvas.java ./tools/easytrain/TrainCanvas.java
--- ../Tekkotsu_2.3/tools/easytrain/TrainCanvas.java	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/TrainCanvas.java	Thu Aug  4 16:58:05 2005
@@ -0,0 +1,1205 @@
+/** @file TrainCanvas.java
+ *  @brief Canvas for EasyTrain        
+ *
+ *	@author editted by: Eric Durback
+ *  @bug No known bugs.
+ */
+
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.io.*;
+import java.util.prefs.Preferences;
+
+public class TrainCanvas extends Canvas implements MouseListener,
+MouseMotionListener
+{
+	BufferedImage image;
+	BufferedImage cachedplot;
+	
+	ColorControlPanel ControlPanel;
+
+	Graphics2D graphics;
+	Polygon curPoly;
+	int lastx, lasty;
+	float f_width, f_height, f_offset;
+	int numImages, curImage;
+	String [] files;
+	String defaultName;
+
+	Area curColorArea;
+	Area [] curImageArea;
+	Area [] originalImageArea;
+
+	String curColor;
+
+	Point imageHint, imagePlace;
+
+	Hashtable colorAreasHash;
+	Hashtable imageAreasHash;
+	Hashtable originalImageAreasHash;
+
+	Hashtable colorMaskHash;
+
+	boolean inverted, colorshow, autoSelect, dirtyOriginal;
+	
+	public final static int NOTHING = 0;
+	public final static int IMAGE_AREA = 1;
+	public final static int COLOR_AREA = 2;
+	
+	Object undoObj;
+	int lastAction;
+	int uImg;
+	
+	float[] xy;
+	int[] rgb;
+
+	SegmentedImage segImage;
+	ImageShowArea imageShow;
+	ImageData imageData;
+	ImageData YUVimageData;
+	HelpBox helpBox;
+
+	boolean areaInImage = false;
+	
+	static Preferences prefs = Preferences.userNodeForPackage(EasyTrain.class);
+
+
+	public TrainCanvas(SegmentedImage _segImage, ImageShowArea _imageShow, ImageData _imageData, ImageData _YUVimageData, ColorControlPanel c_panel, HelpBox _helpBox, String [] files_ ) 
+	{
+
+		//setBackground(Color.black);
+		addMouseListener(this);
+		addMouseMotionListener(this);
+	
+		colorAreasHash=new Hashtable();
+		imageAreasHash = new Hashtable();
+		colorMaskHash = new Hashtable();
+		originalImageAreasHash = new Hashtable();
+		ControlPanel = c_panel;
+		helpBox = _helpBox;
+		
+		inverted=false;
+		colorshow=false;
+		dirtyOriginal = true;
+		imageHint=null;
+		imagePlace=null;
+		segImage = _segImage;
+		imageShow = _imageShow;
+		imageData = _imageData;
+		YUVimageData = _YUVimageData;
+		numImages = files_.length;
+		curImage = 0;
+		undoObj = null;
+		lastAction = NOTHING;
+		uImg = 0;		
+		
+		curImageArea=new Area[numImages];
+		for(int i=0; i<numImages; i++)
+		{
+			curImageArea[i] = new Area();
+		}
+		originalImageArea = new Area[numImages];
+
+		files = files_;    
+
+	}
+
+	public void setControlPanel(ColorControlPanel c)
+	{
+		ControlPanel = c;
+	}
+
+
+	public void plotImage() 
+	{
+		plotImage(this.xy,this.rgb);
+	}
+
+	public void plotImage(float[] xy, int[] rgb) 
+	{
+		
+		this.xy=xy;
+		this.rgb=rgb;
+		
+		Dimension d=getSize();
+		f_width=(float)d.width-41;
+		f_height=(float)d.height-41;
+		f_offset=20;
+
+		cachedplot=new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
+		graphics=(Graphics2D)cachedplot.getGraphics();
+		
+		if(inverted)
+		{
+			graphics.setColor(Color.white);
+			graphics.fillRect(0,0,d.width, d.height);
+		}
+		
+		for (int i=0; i<rgb.length; i++) 
+		{
+		 
+		  graphics.setColor(new Color(rgb[i]));
+		  graphics.drawRect((int)(xy[i*2]*f_width+f_offset),
+		                    (int)(xy[i*2+1]*f_height+f_offset), 1,1);
+		}
+
+		image=new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
+		graphics=(Graphics2D)image.getGraphics();
+				
+		redrawScene();
+		repaint();
+	}
+
+	public void plotImageArea(Area [] area)
+	{ 
+				
+		float[][] xy = imageData.getAllHS();		
+		int[][] rgb = imageData.getAllPixels();
+		
+		double xMod = imageShow.resizedX;
+		double yMod = imageShow.resizedY;
+
+		double width = imageShow.getSize().getWidth();
+		double height = imageShow.getSize().getHeight();		
+		
+		Rectangle curRect;
+
+		Dimension d=getSize();
+		image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
+		Graphics2D graphics = (Graphics2D)image.getGraphics();		
+		
+		if(inverted)
+		{
+			graphics.setColor(Color.white);
+			graphics.fillRect(0,0,d.width, d.height);
+		}
+
+		for(double y=0; y<height; y+=2.0 * yMod)
+		{
+		    for (double x=0; x<width; x+=2.0 * xMod)
+			{
+				for(int k=0; k<numImages; k++)
+				{
+				    if(area[k].contains((int)x,(int)y))
+					{
+					    int i=(int) ((((double)y/yMod)/2.0)*(((double)width/xMod)/2.0)+((double)x/xMod)/2.0);
+					    
+					    int w = (int)(xy[k][i*2]*f_width+f_offset);	//int w = (int)(xy[k][i*2]*f_width+f_offset);
+					    int h = (int)(xy[k][i*2+1]*f_height+f_offset);	//int h = (int)(xy[k][i*2+1]*f_height+f_offset);
+					     
+					    graphics.setColor(new Color(rgb[k][i]));	//graphics.setColor(new Color(rgb[k][i]));
+					    graphics.drawRect(w, h, 1,1);
+						
+						/*if(autoSelect && !curColorArea.contains(w,h))
+						{						
+							curRect=new Rectangle(w -1, h-1,3,3); 								    
+					    	curColorArea.add(new Area(curRect));
+						}*/
+					}
+				}
+			}
+		}
+
+		repaint();
+	}
+
+
+	
+	public void paint(Graphics g) 
+	{
+		update(g);
+	}
+
+	public void update(Graphics g) 
+	{
+		Graphics2D g2d=(Graphics2D) g;
+		if (image!=null) 
+			g.drawImage(image, 0, 0, this);
+
+		if (inverted)
+			g2d.setColor(Color.black);
+		else
+			g2d.setColor(Color.white);
+
+		if (curColorArea!=null)
+			g2d.draw(curColorArea);
+
+		if (curPoly!=null && !areaInImage)
+			g2d.draw(curPoly);
+
+		if (imageHint!=null) 
+		{
+			g2d.drawRect(imageHint.x-2, imageHint.y-2, 5, 5);
+		}
+	}
+
+	public void setCurColor(String color) 
+	{
+
+		if (color==null) 
+		{
+			curImageArea=null;
+			curColorArea = null;
+			return;
+		}
+		
+		undoObj = null;
+		lastAction = NOTHING;
+		ControlPanel.disableUndo();
+
+		curImage = imageShow.getCurImage();
+
+		curColorArea = (Area)colorAreasHash.get(color);
+		curImageArea = (Area[])imageAreasHash.get(color);
+		originalImageArea = (Area[])originalImageAreasHash.get(color);
+
+		if (curImageArea==null) 
+		{
+			curImageArea=new Area[numImages];
+			for(int i=0; i<numImages; i++)
+			{
+				curImageArea[i] = new Area();
+			}
+
+			imageAreasHash.put(color, curImageArea);
+			curColorArea = new Area();
+
+			colorAreasHash.put(color, curColorArea);
+		}
+
+		imageShow.setCurArea(curImageArea[curImage]);
+
+		if(!colorshow)
+		{
+			plotImageArea(curImageArea);
+		}
+		else
+		{
+			plotImage();
+		}
+
+		redrawScene();
+	}
+	
+	public void undo ()
+	{
+	
+		if(lastAction == IMAGE_AREA)
+		{		
+			curImageArea[uImg] = ((Area)undoObj).createTransformedArea(AffineTransform.getScaleInstance(imageShow.resizedX,imageShow.resizedY));
+			imageShow.setCurArea(curImageArea[curImage]);
+			plotImageArea(curImageArea);	
+			dirtyOriginal = true;	
+		}
+		else if(lastAction == COLOR_AREA)
+		{
+			curColorArea.reset();
+			curColorArea.add((Area)((Area)undoObj));
+						
+		}
+		
+		repaint();
+		ControlPanel.disableUndo();
+		segImage.reSegment(makeTmap(), getAverageColors());
+		
+	}
+	
+	public void help()
+	{
+		
+		helpBox.setVisible(true);
+		helpBox.setState(helpBox.NORMAL);
+		
+	}
+	
+	public void clear () 
+	{
+		if (curImageArea==null) return;
+
+		curImage = imageShow.getCurImage();
+		curImageArea[curImage].reset();
+		curColorArea.reset();
+		
+		ControlPanel.disableUndo();
+		
+		
+		imageShow.setCurArea(null);
+		redrawScene();
+		segImage.reSegment(makeTmap(), getAverageColors());		
+		
+		if(colorshow)
+		{
+			plotImage();
+		}
+	}
+
+	public void invert () 
+	{
+		inverted=!inverted;
+		
+		if(inverted)
+		{
+			setBackground(Color.white);
+		}
+		else
+		{
+			setBackground(Color.black);
+		}
+		
+		if(curImageArea != null && !colorshow)
+		{
+			plotImageArea(curImageArea);
+		}
+		else
+		{
+			plotImage();
+		}
+
+	}
+
+	public void showColors () 
+	{
+		colorshow=!colorshow;
+		
+		if(colorshow)
+		{
+			plotImage();
+		}
+		else if(curImageArea != null)
+		{
+			plotImageArea(curImageArea);
+		}		
+		repaint();
+	}
+
+	public void autoSelect () //not being used
+	{
+		autoSelect=true;
+
+		if(autoSelect)
+		{
+			plotImageArea(curImageArea);
+			segImage.reSegment(makeTmap(), getAverageColors());
+		}
+		
+		if(colorshow)
+		{
+			plotImage();
+		}
+
+		autoSelect = false;
+
+	}
+
+	public void remove(String color) 
+	{
+		curColor=null;
+		curColorArea=null;
+		curImageArea=null;
+		colorAreasHash.remove(color);
+		imageAreasHash.remove(color);		
+
+		imageShow.setCurArea(null);
+
+		redrawScene();
+	}
+
+	public void redrawScene()
+	{
+		graphics.drawImage(cachedplot,0,0,this);
+		  		
+		if (curColorArea != null)
+		graphics.draw(curColorArea);
+		
+	}
+
+	
+	public byte[] makeTmap()
+	{
+		ArrayList areas = makeAreas();
+		//boolean maps[][][] = makeMasks();
+
+		int size_y=16, size_u=64, size_v=64;
+		byte[] tmap=new byte[size_y*size_u*size_v];
+
+		float[] hsb=new float[3];
+		int y, u, v, r, g, b, h, s;
+		int iy, iu, iv, i;
+
+		for (iy=0; iy<16; iy++) 
+		{
+			for (iu=0; iu<64; iu++) 
+			{
+				for (iv=0; iv<64; iv++) 
+				{
+				    y=iy<<4; u=iu<<2; v=iv<<2;
+				    u=u*2-255;
+				    v=v*2-255;
+				    r=y+u;
+				    b=y+v;
+				    u=u>>1;
+				    v=(v>>2)-(v>>4);
+				    g=y-u-v;
+				    if (r<0) r=0; 
+				    if (g<0) g=0; 
+				    if (b<0) b=0;
+				    if (r>255) r=255; 
+				    if (g>255) g=255; 
+				    if (b>255) b=255;
+				    
+				    float[] xy=EasyTrain.colorConverter.getColor(r, g, b);
+				    h=(int)(xy[0]*f_width+f_offset);
+				    s=(int)(xy[1]*f_height+f_offset);
+				    Point point=new Point(h, s);
+				    
+				    for (i=0; i<areas.size(); i++) 
+				    {
+						
+						Area area = (Area) areas.get(i);
+						if (area.contains(point)) 
+						{
+						    tmap[(iy*size_u+iu)*size_v+iv]=(byte)(i+1);
+						    break;
+						}
+				    }
+				}
+	    	}
+		}
+
+		return tmap;
+	
+	}   
+	//TODO make a weighted average version
+	public int[][] getAverageColors()
+	{
+		ArrayList areas = makeAreas();
+
+		rgb=imageData.getSpecialPixels();
+
+		int[][] avgcolors=new int[areas.size()][4]; 
+
+		int skip=(rgb.length/10000)+1;
+		
+		for (int i=0; i<rgb.length; i+=skip) 
+		{
+		    for (int a=0; a<areas.size(); a++) 
+		    {
+			
+				Area area=(Area)areas.get(a);
+				Point p=new Point((int)(xy[i*2]*f_width+f_offset),
+						  (int)(xy[i*2+1]*f_height+f_offset));
+				
+				if (area.contains(p)) 
+				{
+				    avgcolors[a][0]+=(rgb[i]>>16)&0xff;
+				    avgcolors[a][1]+=(rgb[i]>>8)&0xff;
+				    avgcolors[a][2]+=rgb[i]&0xff;
+				    avgcolors[a][3]++;
+				    
+				}
+		    }	    
+		}
+
+		for (int i=0; i<avgcolors.length; i++) 
+		{
+		    if (avgcolors[i][3]>0) 
+		    {
+				avgcolors[i][0]=avgcolors[i][0]/avgcolors[i][3];
+				avgcolors[i][1]=avgcolors[i][1]/avgcolors[i][3];
+				avgcolors[i][2]=avgcolors[i][2]/avgcolors[i][3];
+		    } 
+		    else 
+		    {
+				avgcolors[i][0]=0;
+				avgcolors[i][1]=0;
+				avgcolors[i][2]=0;
+		    }
+		}
+		return avgcolors;
+	}
+
+	public ArrayList makeAreas()
+	{
+	
+		Enumeration colors=colorAreasHash.keys();
+		ArrayList colornames=new ArrayList(20);
+
+		while (colors.hasMoreElements()) colornames.add(colors.nextElement());
+
+		Collections.sort(colornames);
+		ArrayList areas=new ArrayList(20);
+
+		for (Iterator i=colornames.iterator(); i.hasNext();
+		     areas.add(colorAreasHash.get(i.next())));
+
+		return areas;
+
+	}	
+
+	public ArrayList makeImageAreas()
+	{
+
+		Enumeration colors=imageAreasHash.keys();
+		ArrayList colornames=new ArrayList(20);
+
+		while (colors.hasMoreElements()) colornames.add(colors.nextElement());
+
+		Collections.sort(colornames);
+		ArrayList areas=new ArrayList(20);
+
+		for (Iterator i=colornames.iterator(); i.hasNext();
+		     areas.add(imageAreasHash.get(i.next())));
+
+		return areas;
+	}
+
+	public boolean[][][] makeMasks()
+	{
+		
+		Enumeration colors=imageAreasHash.keys();
+		ArrayList colornames=new ArrayList(20);
+		while (colors.hasMoreElements()) colornames.add(colors.nextElement());
+		Collections.sort(colornames);
+		ArrayList areas=new ArrayList(20);
+
+		for (Iterator i=colornames.iterator(); i.hasNext();
+		     areas.add(imageAreasHash.get(i.next())));
+
+		boolean[][][] masks = new boolean[areas.size()][(int)f_width+1][(int)f_height+1];
+
+		for (int i=0; i<areas.size(); i++){
+		    for(int x=0; x<f_width; x++){
+				for(int y=0; y<f_height; y++)
+			    {
+					masks[i][x][y]=false;
+			    }
+			}
+		}
+		//something wrong here
+		//xy = hue saturation, this is probably from segmenter
+		float xy[][] = imageData.getAllHS();
+		double imageWidth = imageShow.getSize().getWidth();
+		double imageHeight = imageShow.getSize().getHeight();
+		for (int i=0; i<areas.size(); i++)
+		{
+			for (int y=0; y<imageHeight; y+=2)
+			{
+			    for (int x=0; x<imageWidth; x+=2)
+				{
+				    Area[] a = (Area[])areas.get(i);
+				    for(int k=0; k<numImages; k++)
+					{
+				    	if (a[k].contains(x,y))
+						{
+					    	int j=(y/2)*(((int)imageWidth)/2)+x/2;
+					    	masks[i][(int)(xy[k][2*j]*f_width)][(int)(xy[k][2*j+1]*f_height)] = true;
+					    
+					    	//int j=(y/2)*(((int)imageWidth))+x/2;
+					    	//masks[i][(int)(xy[j]*f_width)][(int)(xy[j+1]*f_height)] = true;
+						}
+					}
+				}	
+			}
+		}
+
+		return masks;
+	}
+
+	public void load (String filename) throws FileNotFoundException, IOException
+	{
+		int dotpos=filename.lastIndexOf('.');
+		if (dotpos>0) filename=filename.substring(0,dotpos);
+
+		colorAreasHash = new Hashtable();
+		imageAreasHash = new Hashtable();
+
+		curImageArea[curImage].reset();
+		curColorArea.reset();
+
+		BufferedReader saveFile=new BufferedReader(new FileReader(filename + ".save"));
+		BufferedReader areaFile;
+
+		saveFile.readLine();
+
+		int numColors = Integer.parseInt(saveFile.readLine());
+		String [] colors = new String[numColors];
+		Polygon curPoly = new Polygon();;
+		StringTokenizer inTok;
+		int x,y;
+
+		for(int j=0; j<numColors; j++)
+		{
+			String s = saveFile.readLine();
+			colors[j] = s;
+		}
+
+		if(!saveFile.readLine().equals("NEXT"))
+		{
+			System.out.println("Error File Format is incorrect");
+			return;
+		}
+
+		for(int i=0; i<numColors; i++)
+		{
+			
+			for(String in = saveFile.readLine(); !((in.equals("NEXT")) || in.equals("")); in = saveFile.readLine())
+			{
+				inTok = new StringTokenizer(in);
+				in = inTok.nextToken();
+				
+				if(in.equals("START"))
+				{
+					curPoly = new Polygon();
+					x = (int)Double.parseDouble(inTok.nextToken());
+					y = (int)Double.parseDouble(inTok.nextToken());
+					curPoly.addPoint(x,y);
+				}
+				else if(in.equals("LINE"))
+				{
+					x = (int)Double.parseDouble(inTok.nextToken());
+					y = (int)Double.parseDouble(inTok.nextToken());
+					curPoly.addPoint(x,y);
+				}
+				else if(in.equals("CLOSE"))
+				{
+					//System.out.println("adding area");	
+					curColorArea.add(new Area(curPoly));
+				}
+				
+				//System.out.println("S");				
+			}
+			
+			colorAreasHash.put(colors[i],curColorArea);
+			curColorArea = new Area();
+		}
+
+			
+		for(int l=0; l<files.length; l++)
+		{
+				
+			try
+			{
+				areaFile = new BufferedReader(new FileReader(filename +"_"+files[l]+ ".area"));
+			
+				areaFile.readLine();
+				for(int k=0; k<numColors; k++)
+				{		
+				
+					curImageArea =(Area[])imageAreasHash.get(colors[k]);
+					
+					if(curImageArea == null)
+					{
+						curImageArea = new Area[numImages];
+						for(int i=0; i<numImages; i++)
+					    {
+					      	curImageArea[i] = new Area();
+					    }
+		    		}
+				    
+				    
+					for(String in = areaFile.readLine(); (!(in.equals("NEXT")) && areaFile.ready()); in = areaFile.readLine())
+					{
+						inTok = new StringTokenizer(in);
+						in = inTok.nextToken();
+						
+						if(in.equals("START"))
+						{
+							curPoly = new Polygon();
+							x = (int)Double.parseDouble(inTok.nextToken());
+							y = (int)Double.parseDouble(inTok.nextToken());
+							curPoly.addPoint(x,y);
+						}
+						else if(in.equals("LINE"))
+						{
+							x = (int)Double.parseDouble(inTok.nextToken());
+							y = (int)Double.parseDouble(inTok.nextToken());
+							curPoly.addPoint(x,y);
+						}
+						else if(in.equals("CLOSE"))
+						{
+							curImageArea[l].add(new Area(curPoly));
+						}
+						
+					}
+					imageAreasHash.put(colors[k],curImageArea);
+				}
+				
+			}
+			catch(Exception e)
+			{
+				for(int k=0; k<numColors; k++)
+				{		
+				
+					curImageArea =(Area[])imageAreasHash.get(colors[k]);
+					
+					if(curImageArea == null)
+					{
+						curImageArea = new Area[numImages];
+						for(int i=0; i<numImages; i++)
+					    {
+					      	curImageArea[i] = new Area();
+					    }
+		    		}
+		    		
+		    		imageAreasHash.put(colors[k],curImageArea);
+		    	}
+							
+			}
+			
+		}
+		segImage.reSegment(makeTmap(), getAverageColors());
+		//setCurColor(null);
+	}
+
+	public void save (String filename) 
+	{
+		int dotpos=filename.lastIndexOf('.');
+		if (dotpos>0) filename=filename.substring(0,dotpos);
+
+		Enumeration colors=colorAreasHash.keys();
+		ArrayList colornames=new ArrayList(20);
+		while (colors.hasMoreElements()) colornames.add(colors.nextElement());
+		Collections.sort(colornames);
+		ArrayList areas=makeAreas();
+		ArrayList imageAreas = makeImageAreas();
+
+		int size_y=16, size_u=64, size_v=64;
+
+		int i;
+		byte[] tmap = makeTmap();
+
+		try 
+		{
+			FileOutputStream file_tm_fos=new FileOutputStream(filename + ".tm");
+			OutputStreamWriter file_tm_osw=new OutputStreamWriter(file_tm_fos);
+			file_tm_osw.write("TMAP\nYUV8\n" +
+			  size_y + " " + size_u + " " + size_v + "\n");
+			file_tm_osw.flush();
+			file_tm_fos.write(tmap);
+			file_tm_osw.close();
+		} 
+		catch (Exception ex) 
+		{
+			System.out.println("Error saving to "+filename +".tm: " + ex);
+		}
+		
+		int [][] avgcolors = getAverageColors();
+
+		try 
+		{
+			FileWriter file_col_fw=new FileWriter(filename + ".col");
+			file_col_fw.write("0 (128 128 128) \"unclassified\" 8 1.00\n");
+			
+			for (i=0; i<areas.size(); i++) 
+			{
+				file_col_fw.write((i+1)+ " (" +
+				              avgcolors[i][0] + " " +
+				              avgcolors[i][1] + " " +
+				              avgcolors[i][2] + ") " +
+				              "\"" + colornames.get(i)+ "\" 8 0.75\n");
+			}
+			
+			file_col_fw.close();
+		} 
+		catch (Exception ex) 
+		{
+			System.out.println("Error saving to "+filename + ".col: " + ex);
+		}
+
+		try 
+		{
+			FileWriter file_save_fw=new FileWriter(filename + ".save");
+			FileWriter file_area_fw;
+			file_save_fw.write(filename + "\n");
+			file_save_fw.write(areas.size() + "\n");
+
+			for(int j=0; j<colornames.size(); j++)
+			{
+				file_save_fw.write(colornames.get(j) + "\n");	
+			}      
+
+			for (i=0; i<areas.size(); i++) 
+			{
+				Area a = (Area)areas.get(i);
+				PathIterator path = a.getPathIterator(null);
+
+				String pathString = createPathString(path);
+				file_save_fw.write(pathString);  
+
+			}
+
+			file_save_fw.write("\n");
+			file_save_fw.close();
+
+
+			for(int l=0; l<files.length; l++)
+			{
+				
+				String areaname = filename + "_"+ files[l];
+	
+				file_area_fw=new FileWriter(areaname + ".area");	
+
+				for (i=0; i<imageAreas.size(); i++) 
+				{
+				    Area [] a = (Area[])imageAreas.get(i);
+				    PathIterator path = a[l].getPathIterator(null);
+				      	
+				    String pathString = createPathString(path);
+				    file_area_fw.write(pathString);  
+				   
+				}
+
+				file_area_fw.write("\n");
+				file_area_fw.close();
+
+			}		  
+
+		} catch (Exception ex) {
+		  System.out.println("Error saving to "+filename + ".area: " + ex);
+		}
+
+
+	}
+
+	String createPathString(PathIterator path)
+	{
+
+		String retPath = "NEXT\n";
+
+		double[] coords = new double[6];
+		int type;	
+
+		while(!path.isDone())
+		{
+		  	type = path.currentSegment(coords); 
+		  	
+		  	
+		  	if( (type == PathIterator.SEG_MOVETO)) //new polygon
+		  	{
+		  		retPath += "START " + coords[0] + " " + coords[1] + "\n";		
+		  	}
+		  	else if( (type == PathIterator.SEG_LINETO)) //line 
+		  	{
+		  		retPath += "LINE " + coords[0] + " " + coords[1] + "\n";
+		  	}
+		  	else if( (type == PathIterator.SEG_CLOSE))  //end of curr polygon
+		  	{
+		  		retPath += "CLOSE\n";
+			}
+			
+			path.next();
+			
+		}
+
+		return retPath;
+
+	}
+
+	byte[] readThresholdMap(String thresholdfile) 
+	{
+		try 
+		{
+			byte[] tmdata=new byte[65536];
+			FileInputStream file_tm_fis=new FileInputStream(thresholdfile);
+			file_tm_fis.read(tmdata,0,19);
+			file_tm_fis.read(tmdata);
+			file_tm_fis.close();
+			return tmdata;
+		} 
+		catch (Exception ex) 
+		{
+			System.out.println("Error reading file "+thresholdfile+": "+ex);
+			return null;
+		}
+	}
+
+
+
+	void resizeAreas(double x, double y, double changeX, double changeY)
+	{
+		if(curImageArea != null)
+		{
+			Area[] curAreaList;
+			Area curArea;
+			
+			updateAreas(x,y,changeX,changeY);			
+			
+			imageShow.setCurArea(curImageArea[curImage]);
+			plotImageArea(curImageArea);
+
+			repaint();
+		}	  
+	}
+	
+	void updateAreas(double x, double y, double changeX, double changeY)
+	{
+		Area[] curAreaList;
+		Area curArea;
+		Area[] origAreaList;
+		Area origArea;
+		Object o;
+		
+		Enumeration colors=imageAreasHash.keys();
+		ArrayList colornames=new ArrayList();
+		while (colors.hasMoreElements()) colornames.add(colors.nextElement());
+		
+		for (int i=0; i<colornames.size(); i++)
+		{
+			curAreaList = (Area[])imageAreasHash.get(colornames.get(i));
+			
+			o = originalImageAreasHash.get(colornames.get(i));
+			
+			if(o == null)
+			{
+				origAreaList = new Area[numImages];
+			}
+			else
+			{
+				origAreaList = (Area[])o;
+			}
+				
+			for(int j = 0; j < numImages; j++)
+			{
+				if(dirtyOriginal == true)
+				{
+					curAreaList[j] = curAreaList[j].createTransformedArea(AffineTransform.getScaleInstance(changeX,changeY));
+					origAreaList[j] = curAreaList[j].createTransformedArea(AffineTransform.getScaleInstance(1.0/x,1.0/y));
+				}
+				else
+				{
+					curAreaList[j] = origAreaList[j].createTransformedArea(AffineTransform.getScaleInstance(x,y));
+				}
+				
+			}
+				
+			originalImageAreasHash.put(colornames.get(i),origAreaList);
+			imageAreasHash.put(colornames.get(i),curAreaList);
+		}	
+		
+		dirtyOriginal = false;
+	}
+	
+	//******* MOUSE CONTROLS ********
+    
+    public void mousePressed(MouseEvent e) 
+	{
+		if (e.getButton()!=MouseEvent.BUTTON1) return;
+
+		if (curImageArea==null || curColorArea==null)
+		{
+			ControlPanel.addDefaultColor();    
+		}
+
+		if (e.getSource() instanceof ImageShowArea)
+		{
+		    areaInImage = true;
+		    curPoly=new Polygon();
+		    lastx=e.getX();
+		    lasty=e.getY();
+		    curPoly.addPoint(e.getX(), e.getY());
+		    imageShow.setCurPoly(curPoly);		    
+		}
+		else
+		{
+		    areaInImage = false;		    
+		    curPoly=new Polygon();
+		    lastx=e.getX();
+		    lasty=e.getY();
+		    curPoly.addPoint(e.getX(), e.getY());
+		    repaint();
+		}
+	}
+
+	public void mouseDragged(MouseEvent e) 
+	{	  
+		if (e.getSource() instanceof ImageShowArea)
+		{   	      
+			int x=e.getX();
+			int y=e.getY();
+
+			if ((Math.abs(x-lastx)+Math.abs(y-lasty))>2) 
+			{
+				curPoly.addPoint(e.getX(), e.getY());
+				lastx=x;
+				lasty=y;
+				imageShow.setCurPoly(curPoly);
+			}
+		}
+		else
+		{	      
+			int x=e.getX();
+			int y=e.getY();
+
+			if ((Math.abs(x-lastx)+Math.abs(y-lasty))>2) 
+			{
+				curPoly.addPoint(e.getX(), e.getY());
+				lastx=x;
+				lasty=y;
+				repaint();
+			}
+		}
+	}
+
+	public void mouseReleased(MouseEvent e) 
+	{
+		if (e.getButton()!=MouseEvent.BUTTON1) return;
+
+		if (e.getSource() instanceof ImageShowArea)
+		{
+		    if (curImageArea==null)
+		    {
+		    	ControlPanel.addDefaultColor();		    
+		    } 
+		    
+		    curImage = imageShow.getCurImage();
+
+		    curPoly.addPoint(e.getX(), e.getY());
+		    
+		    if (curPoly.npoints>=3) 
+		    {
+				
+				if(originalImageArea != null && originalImageArea[curImage] != null)
+				{
+					undoObj = new Area(originalImageArea[curImage]);
+				}
+				else
+				{
+					undoObj = curImageArea[curImage].createTransformedArea(AffineTransform.getScaleInstance(1.0/imageShow.resizedX,1.0/imageShow.resizedY));
+				}
+				
+				ControlPanel.enableUndo();
+				lastAction = IMAGE_AREA;
+				uImg = curImage; 
+				 
+				if (e.isControlDown())
+				{ 
+				    curImageArea[curImage].subtract(new Area(curPoly));
+				}
+				else if (e.isShiftDown())
+				{ 
+					curImageArea[curImage].add(new Area(curPoly));
+				}
+				else
+				{
+					curImageArea[curImage].reset();
+				 	
+					curImageArea[curImage].add(new Area(curPoly));
+				}
+				dirtyOriginal = true;
+		    }
+		    
+		    curPoly=null;
+		    imageShow.setCurArea(curImageArea[curImage]);
+		    imageShow.setCurPoly(null);
+		    
+		    
+
+		    if(!colorshow)
+		    {
+		    	plotImageArea(curImageArea);
+		    }
+		}
+		else //color area
+		{
+		    if (curColorArea==null) return;
+
+		    curPoly.addPoint(e.getX(), e.getY());
+		    
+		    if (curPoly.npoints>=3) 
+		    {
+				
+				undoObj = new Area(curColorArea);
+				ControlPanel.enableUndo();
+				lastAction = COLOR_AREA;
+				
+				
+				if (e.isControlDown())
+				{ 
+				    curColorArea.subtract(new Area(curPoly));
+				}
+				else if (e.isShiftDown())
+				{ 
+				    curColorArea.add(new Area(curPoly));
+				}
+				else
+				{
+					curColorArea.reset();
+					curColorArea.add(new Area(curPoly));
+				}
+			}
+			
+		    curPoly=null;
+		    repaint();
+		}
+		
+		segImage.reSegment(makeTmap(), getAverageColors());
+	}
+
+	public void mouseMoved(MouseEvent e)
+	{
+		Object source=e.getSource();
+		curImage = imageShow.getCurImage();
+		if (source instanceof ImageShowArea) 
+		{
+		  	
+			ImageShowArea imageShow=(ImageShowArea)source;
+			int rgb=imageShow.getPixel(e.getX(), e.getY());
+			float[] xy=EasyTrain.colorConverter.getColor(rgb);
+			int x=(int)(xy[0]*f_width+f_offset);
+			int y=(int)(xy[1]*f_height+f_offset);
+			imageHint=new Point(x,y);
+			
+			segImage.showHint(new Point((int) ((double)e.getX() / imageShow.resizedX),(int) ( (double)e.getY() / imageShow.resizedY)));
+				
+			repaint();
+		}
+		/* this currently is not working
+		else if (source instanceof SegmentedImage) 
+		{
+			SegmentedImage seg=(SegmentedImage)source;
+			int rgb=seg.getPixel(e.getX(), e.getY());
+			float[] xy=TrainingTool.colorConverter.getColor(rgb);
+			int x=(int)(xy[0]*f_width+f_offset);
+			int y=(int)(xy[1]*f_height+f_offset);
+			imageHint=new Point(x,y);
+				
+			segImage.showHint(null);
+			
+			repaint();
+		 
+		}*/
+		else
+		{
+			segImage.showHint(null);
+			imageHint = null;			
+			repaint();
+		}    
+	}
+
+	public void mouseClicked(MouseEvent e){}
+	
+	public void mouseExited(MouseEvent e)
+	{
+		if (e.getSource() instanceof ImageShowArea) 
+		{
+			imageHint=null;
+			repaint();
+		}
+		else if(e.getSource() instanceof SegmentedImage)
+		{
+			imagePlace = null;
+			repaint();
+		}
+	}
+	
+	public void mouseEntered(MouseEvent e){}
+	public void updateLocation(MouseEvent e){}
+
+ 	
+
+}
diff -urdN ../Tekkotsu_2.3/tools/easytrain/help.txt ./tools/easytrain/help.txt
--- ../Tekkotsu_2.3/tools/easytrain/help.txt	Wed Dec 31 19:00:00 1969
+++ ./tools/easytrain/help.txt	Wed Aug  3 20:27:38 2005
@@ -0,0 +1,67 @@
+EastyTrain instructions:
+
+Usage:
+  java EasyTrain [-isYUV | -isRGB] imagefile...
+
+Image files should be saved from the Tekkotsu RawCam window as PNG
+files with YUV encoding (the default), but the program can also handle
+images in RGB encoding.  EasyTrain displays the images as RGB in
+either case.
+
+1. Raw image window: displays the current image file.  Use the up and
+down arrow keys to cycle through all the image files.
+
+2. Segmented image window: displays the color-segmented version of the
+current image file.  (If no colors are defined yet, it will be all
+black.)
+
+3. Color space window: displays pixels from selected image regions in
+a 2D color space representation.  Draw a bounding region with the
+mouse to select pixel clusters.
+
+4. GUI window: contains buttons to add or remove colors, load or save
+files, etc.
+
+================
+
+Start by entering a color name, say, "pink".  (Type the color name in
+the dialog box at the top of the GUI window, and hit "enter".)
+
+Now use the mouse to circle a pink region in the raw image window.
+This will cause a cloud of pink pixels to appear in the color space
+window.  (Note: if you have a pink object on a green background and
+you just draw a big box around it, so that some green pixels are
+included in the box, that's okay, because the green pixels will be far
+enough away from the pink ones in color space that you can easily
+separate them.)
+
+Use the mouse to circle just the cloud of pink pixels in color space.
+Once you've done that, the pink regions should appear in the color
+segmented image window.
+
+You can add to a region by holding down the shift key and drawing with
+the mouse.  You can subtract from a region by holding down the control
+key and drawing.
+
+You can use the up and down arrow keys in the raw or segmented image
+windows to cycle though the images.  You can circle zero or more
+regions in each image.  Pixels from all the images will be lumped
+together in the color space window.
+
+If no color name is selected, EasyTrain will show you the color space
+with all the pixels from all the images.  If you do have a color name
+selected, you can deselect it by holding down the control key and
+clicking on the color name in the GUI window.
+
+After you've defined all your colors, use the "Save" button to save
+your work.  The area boundary info for each image will be saved, along
+with the .col and .tm files needed by CMVision.  That means if you
+come back later and run the program again, loading in the same image
+files, the program will also load in the boundaries you defined, so
+you can continue to edit them.
+
+================
+
+Note to Linux users: if you're receiving warnings about inability to locate
+a system preferences file, this is because of the way Java was installed.
+See http://java.sun.com/j2se/1.5.0/install-linux.html for a fix.
Binary files ../Tekkotsu_2.3/tools/easytrain/test1.png and ./tools/easytrain/test1.png differ
Binary files ../Tekkotsu_2.3/tools/easytrain/test2.png and ./tools/easytrain/test2.png differ
Binary files ../Tekkotsu_2.3/tools/easytrain/test3.png and ./tools/easytrain/test3.png differ
Binary files ../Tekkotsu_2.3/tools/easytrain/test4.png and ./tools/easytrain/test4.png differ
diff -urdN ../Tekkotsu_2.3/tools/evenmodtime/CVS/Entries ./tools/evenmodtime/CVS/Entries
--- ../Tekkotsu_2.3/tools/evenmodtime/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/evenmodtime/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,3 @@
+/Makefile/1.2/Sun Aug 24 21:19:27 2003//Ttekkotsu-2_4
+/evenmodtime.cc/1.1/Mon Jul 28 18:39:19 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/evenmodtime/CVS/Repository ./tools/evenmodtime/CVS/Repository
--- ../Tekkotsu_2.3/tools/evenmodtime/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/evenmodtime/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/evenmodtime
diff -urdN ../Tekkotsu_2.3/tools/evenmodtime/CVS/Root ./tools/evenmodtime/CVS/Root
--- ../Tekkotsu_2.3/tools/evenmodtime/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/evenmodtime/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/evenmodtime/CVS/Tag ./tools/evenmodtime/CVS/Tag
--- ../Tekkotsu_2.3/tools/evenmodtime/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/evenmodtime/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/filewordreplace ./tools/filewordreplace
--- ../Tekkotsu_2.3/tools/filewordreplace	Tue Jan  4 14:51:41 2005
+++ ./tools/filewordreplace	Wed Jun  1 01:48:08 2005
@@ -14,6 +14,8 @@
 	esac;
 done;
 
+cmd="`cd \`dirname \"$0\"\`; pwd`/`basename $0`"
+
 if [ $# -lt 3 ] ; then
 	echo "$usage";
 	exit 1;
@@ -27,17 +29,17 @@
 				if $status; then
 					echo "Processing $1";
 				fi;
-				sed "s${sepchar}${old}${sepchar}${new}${sepchar}g" "$1" > $tmpname;
-				mv $tmpname "$1";
+				sed "s${sepchar}${old}${sepchar}${new}${sepchar}g" "$1" > "$tmpname";
+				mv "$tmpname" "$1";
 			fi;
+		elif [ -d "$1" ] ; then
+			cd "$1";
+			for x in * ; do
+				#echo "evaling: " "$0" $recurseflags "\"$old\"" "\"$new\"" "\"$x\"";
+				eval "$cmd" $recurseflags "\"$old\"" "\"$new\"" "\"$x\"";
+			done;
 		else
-			if [ -d "$1" ] ; then
-				for x in "$1"/* ; do
-					eval "$0" $recurseflags "$old" "$new" "$x";
-				done;
-			else
-				echo "$1 not found";
-			fi;
+			echo "$1 not found";
 		fi;
 		shift;
 	done;
diff -urdN ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Entries ./tools/filtersyswarn/CVS/Entries
--- ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/filtersyswarn/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,3 @@
+/Makefile/1.2/Sun Aug 24 21:19:32 2003//Ttekkotsu-2_4
+/filtersyswarn.cc/1.8/Wed Jun  1 05:48:08 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Repository ./tools/filtersyswarn/CVS/Repository
--- ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/filtersyswarn/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/filtersyswarn
diff -urdN ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Root ./tools/filtersyswarn/CVS/Root
--- ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/filtersyswarn/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Tag ./tools/filtersyswarn/CVS/Tag
--- ../Tekkotsu_2.3/tools/filtersyswarn/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/filtersyswarn/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/filtersyswarn/filtersyswarn.cc ./tools/filtersyswarn/filtersyswarn.cc
--- ../Tekkotsu_2.3/tools/filtersyswarn/filtersyswarn.cc	Fri Jul 23 23:12:34 2004
+++ ./tools/filtersyswarn/filtersyswarn.cc	Wed Jun  1 01:48:08 2005
@@ -32,7 +32,8 @@
 	regcomp(&sysmsg,OPENR.c_str(),REG_EXTENDED|REG_NOSUB);
 	regcomp(&instbegin,instbeginstr.c_str(),REG_EXTENDED|REG_NOSUB);
 	regcomp(&inststat,inststatstr.c_str(),REG_EXTENDED|REG_NOSUB);
-	regcomp(&ignorebegin,(OPENR+".*: warning: ").c_str(),REG_EXTENDED|REG_NOSUB);
+	string pliststr_no_vdtor=".*plist.h:[0-9]*: warning: base class";
+	regcomp(&ignorebegin,(OPENR+".*: warning: |"+pliststr_no_vdtor).c_str(),REG_EXTENDED|REG_NOSUB);
 	regcomp(&warnstat,"^   ",REG_EXTENDED|REG_NOSUB);
 
 	string file, instant;
@@ -63,6 +64,7 @@
 			warnclipped=false;
 		}
 		if(regexec(&ignorebegin,s.c_str(),0,NULL,0)==0) {
+			instant="";
 			do {
 				getline(cin,s);
 			} while(regexec(&warnstat,s.c_str(),0,NULL,0)==0);
diff -urdN ../Tekkotsu_2.3/tools/formatList ./tools/formatList
--- ../Tekkotsu_2.3/tools/formatList	Wed Dec 31 19:00:00 1969
+++ ./tools/formatList	Mon Jan 31 14:51:05 2005
@@ -0,0 +1,21 @@
+#!/bin/sh
+
+if [ $# -lt 2 -o "$1" = "-h" -o "$1" = "--help" ] ; then
+  echo "Usage: $0 class long_list.html";
+  echo "       class should be one of 'features', 'api_changes', 'bug_fixes', 'known_bugs'";
+  echo ""
+  echo "       This tool will convert a "long format" bug list saved from"
+  echo "       Tekkotsu's bugzilla installation into a format for use on the"
+  echo "       version history page."
+  exit 2;
+fi;
+
+prefix="^ *<font =\"+3\">Bug ";
+postfix="<\/font>";
+
+echo "<html><head></head><body><ul class=\"$1\">"
+grep "$prefix" "$2" | sed "s/${prefix}\([0-9]*\) - \(.*\)${postfix}/\1 \2/" | \
+while read idnum desc ; do
+echo "<li>$desc <a href=\"http://bugs.tekkotsu.org/show_bug.cgi?id=$idnum\">&raquo;</a></li>"
+done;
+echo "</ul></body></html>"
diff -urdN ../Tekkotsu_2.3/tools/genCommonHeader ./tools/genCommonHeader
--- ../Tekkotsu_2.3/tools/genCommonHeader	Wed Dec 31 19:00:00 1969
+++ ./tools/genCommonHeader	Wed Jun  1 01:48:08 2005
@@ -0,0 +1,78 @@
+#!/bin/sh
+
+dest=common.h;
+src=build;
+thresh=40;
+root=`cd \`dirname "$0"\`/..; pwd`/
+
+usage="\
+$0 [-d|--dest <output_file>] [-b|--builddir <builddir>] \n \
+   [-t|--threshold <threshold_value>] [-r|--root <tekkotsu_root>] \n \
+   [-f|--force <file>] [-p|--force-pattern <regexp>] \n \
+   \n \
+   If unspecified, destination is $dest and builddir is $src, both \n \
+   relative to the current directory (`pwd`). \n \
+   \n \
+   Threshold defaults to $thresh.\n \
+   \n \
+   force and force-pattern allow you to explicitly add files to the \n \
+   list, even if  they wouldn't otherwise break the threshold.  You can \n \
+   use --force multiple times to specify several files, but you can only \n \
+   specify one regexp pattern (the last one specified will be used -- use \n \
+   the 'or' token '|' to get around this) \n \
+   \n \
+   root defaults to '$root', and will be removed from \n \
+   each of the file names for portability. \n \
+   \n";
+
+while [ $# -gt 0 ] ; do
+    case "$1" in
+	-r|--root) root="$2"; shift; shift ;;
+	-d|--dest) dest="$2"; shift; shift ;;
+	-b|--builddir) src="$2"; shift; shift ;;
+	-t|--threshold) thresh=$2; shift; shift ;;
+	-f|--force) forced="$forced $2"; shift; shift ;;
+	-p|--force-pattern) pattern="$2"; shift; shift;;
+	*) printf "$usage"; exit 2 ;;
+    esac;
+done;
+
+rm -f $dest;
+echo "/* This is a file lists the most depended-upon header files used by" >> "$dest"
+echo " * the project.  It is automatically generated by tools/genCommonHeader." >> "$dest"
+echo " * When compiling for PLATFORM_LOCAL, this header will be precompiled. " >> "$dest"
+echo " * It was created at `date` and checked into " >> "$dest"
+echo " * CVS at \$Date: 2005/06/01 05:48:08 $ */" >> "$dest"
+echo "" >> "$dest"
+
+echo "#ifdef __cplusplus //lets us blindly apply to C files as well" >> "$dest"
+echo "" >> "$dest"
+
+for plat in PLATFORM_LOCAL PLATFORM_APERIOS ; do
+
+    if [ ! -d "$src/$plat" ] ; then
+	echo Warning: "$src/$plat" not found or not a directory;
+	continue;
+    fi;
+    echo "#ifdef $plat" >> "$dest"
+    for modelbuild in "$src/$plat/TGT"* ; do
+	echo "Processing $modelbuild...";
+	model=`echo "$modelbuild" | sed "s@$src/$plat/@@"`;
+	echo "#ifdef $model" >> "$dest";
+	( find "$modelbuild" -name "*.d" | xargs sed -n 's/\(.*\.h\):$/\1/p' ) | sed "s@^$root@@" | sort | uniq -c | sort -nr | \
+	while read n file ; do
+	    if [ $n -ge $thresh ] ; then
+		echo "#include \"$file\" //$n" >> "$dest" ;
+	    elif echo "$file" | grep -q "$pattern" ; then
+		echo "#include \"$file\" //forced (pattern match)" >> "$dest" ;
+	    fi;
+	done;
+	for f in $forced ; do
+	    echo "#include \"$f\" //forced" >> "$dest" ;
+	done;
+	echo "#endif //$model" >> "$dest";
+    done;
+    echo "#endif //$plat" >> "$dest"
+    echo "" >> "$dest"
+done;
+echo "#endif //cplusplus" >> "$dest"
diff -urdN ../Tekkotsu_2.3/tools/installXCodeTemplates ./tools/installXCodeTemplates
--- ../Tekkotsu_2.3/tools/installXCodeTemplates	Wed Dec 31 19:00:00 1969
+++ ./tools/installXCodeTemplates	Wed Jun  1 01:48:08 2005
@@ -0,0 +1,209 @@
+#!/bin/sh
+
+# installXCodeTemplates
+# Created by Ethan Tira-Thompson on 3/8/05.
+
+DEFAULT="/Library/Application Support/Apple/Developer Tools/File Templates/Tekkotsu"
+ORIGDIR="`pwd`";
+cd "`dirname \"$0\"`/../project/templates";
+SOURCE="`pwd`"
+TIFILE="TemplateInfo.plist"
+
+INSTALL="$1"
+ISSYSTEMWIDE=false
+ISHOME=false
+if [ "$INSTALL" == "--system" ] ; then
+	INSTALL="$DEFAULT"
+	ISSYSTEMWIDE=true
+elif [ -z "$INSTALL" ] ; then
+	cd;
+	INSTALL="`pwd`/$DEFAULT"
+	ISHOME=true
+fi
+
+cd "$ORIGDIR";
+cd "`dirname \"$0\"`";
+
+echo "This will install the template files from:"
+echo "  $SOURCE"
+echo "to:"
+echo "  $INSTALL"
+if $ISSYSTEMWIDE ; then
+	echo "This will allow systemwide usage";
+fi;
+if $ISHOME ; then
+	echo "This will only provide access for the current user";
+	echo "(pass --system flag to install into the system-wide directory)";
+fi;
+
+if [ -d "$INSTALL" ] ; then
+	echo "";
+	echo "WARNING: The target directory already exists, continuing will replace it";
+fi;
+
+echo "";
+echo "Press enter to continue, ctl-C to cancel";
+read;
+
+if [ -d "$INSTALL" ] ; then
+	rm -r "$INSTALL";
+fi;
+
+mkdir -p "$INSTALL";
+
+CUR="$INSTALL/Generic Class.pbfiletemplate"
+mkdir "$CUR";
+echo "Made dir $CUR";
+cp "$SOURCE/header.h" "$SOURCE/implementation.cc" "$CUR";
+cat > "$CUR/$TIFILE" << EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLis
+t-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>Description</key>
+	<string>A C++ class, with an optional implementation file.</string>
+	<key>MainTemplateFile</key>
+	<string>implementation.cc</string>
+	<key>FileToDisplay</key>
+	<string>%@.h</string>
+	<key>ImplicitCounterpartTemplateFiles</key>
+	<dict>
+		<key>header.h</key>
+		<string>%@.h</string>
+	</dict>
+</dict>
+</plist>
+EOF
+
+CUR="$INSTALL/Behavior.pbfiletemplate"
+mkdir "$CUR";
+echo "Made dir $CUR";
+cp "$SOURCE/behavior.h" "$SOURCE/implementation.cc" "$CUR";
+cat > "$CUR/$TIFILE" << EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLis
+t-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>Description</key>
+	<string>A blank Tekkotsu behavior, with an optional implementation file.</string>
+	<key>MainTemplateFile</key>
+	<string>implementation.cc</string>
+	<key>FileToDisplay</key>
+	<string>%@.h</string>
+	<key>ImplicitCounterpartTemplateFiles</key>
+	<dict>
+		<key>behavior.h</key>
+		<string>%@.h</string>
+	</dict>
+</dict>
+</plist>
+EOF
+
+CUR="$INSTALL/Control.pbfiletemplate"
+mkdir "$CUR";
+echo "Made dir $CUR";
+cp "$SOURCE/control.h" "$SOURCE/implementation.cc" "$CUR";
+cat > "$CUR/$TIFILE" << EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLis
+t-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>Description</key>
+	<string>A blank Tekkotsu control, with an optional implementation file.</string>
+	<key>MainTemplateFile</key>
+	<string>implementation.cc</string>
+	<key>FileToDisplay</key>
+	<string>%@.h</string>
+	<key>ImplicitCounterpartTemplateFiles</key>
+	<dict>
+		<key>control.h</key>
+		<string>%@.h</string>
+	</dict>
+</dict>
+</plist>
+EOF
+
+CUR="$INSTALL/StateNode.pbfiletemplate"
+mkdir "$CUR";
+echo "Made dir $CUR";
+cp "$SOURCE/statenode.h" "$SOURCE/implementation.cc" "$CUR";
+cat > "$CUR/$TIFILE" << EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLis
+t-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>Description</key>
+	<string>A blank Tekkotsu StateNode (element of a state machine), with an optional implementation file.</string>
+	<key>MainTemplateFile</key>
+	<string>implementation.cc</string>
+	<key>FileToDisplay</key>
+	<string>%@.h</string>
+	<key>ImplicitCounterpartTemplateFiles</key>
+	<dict>
+		<key>statenode.h</key>
+		<string>%@.h</string>
+	</dict>
+</dict>
+</plist>
+EOF
+
+CUR="$INSTALL/StateMachine.pbfiletemplate"
+mkdir "$CUR";
+echo "Made dir $CUR";
+cp "$SOURCE/statemachine.h" "$SOURCE/implementation.cc" "$CUR";
+cat > "$CUR/$TIFILE" << EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLis
+t-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>Description</key>
+	<string>A blank Tekkotsu state machine (a StateNode with subnodes), with an optional implementation file.</string>
+	<key>MainTemplateFile</key>
+	<string>implementation.cc</string>
+	<key>FileToDisplay</key>
+	<string>%@.h</string>
+	<key>ImplicitCounterpartTemplateFiles</key>
+	<dict>
+		<key>statemachine.h</key>
+		<string>%@.h</string>
+	</dict>
+</dict>
+</plist>
+EOF
+
+CUR="$INSTALL/Transition.pbfiletemplate"
+mkdir "$CUR";
+echo "Made dir $CUR";
+cp "$SOURCE/transition.h" "$SOURCE/implementation.cc" "$CUR";
+cat > "$CUR/$TIFILE" << EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLis
+t-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>Description</key>
+	<string>A blank Tekkotsu state transition, with an optional implementation file.</string>
+	<key>MainTemplateFile</key>
+	<string>implementation.cc</string>
+	<key>FileToDisplay</key>
+	<string>%@.h</string>
+	<key>ImplicitCounterpartTemplateFiles</key>
+	<dict>
+		<key>transition.h</key>
+		<string>%@.h</string>
+	</dict>
+</dict>
+</plist>
+EOF
+
+echo "Translating keywords";
+./filewordreplace -q "CLASSNAME" "ÇFILEBASENAMEÈ" "$INSTALL";
+./filewordreplace -q "YOURNAMEHERE" "ÇFULLUSERNAMEÈ\ \(ÇUSERNAMEÈ\)" "$INSTALL";
+./filewordreplace -q '\\\\\\\$Date\\\\\\$' '\\\$Date:\ ÇDATEÈ\ ÇTIMEÈ\\$' "$INSTALL";
+
+echo "Done!";
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/CVS/Entries ./tools/mipaltools/CVS/Entries
--- ../Tekkotsu_2.3/tools/mipaltools/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,6 @@
+/Makefile/1.5/Thu Oct  9 19:51:28 2003//Ttekkotsu-2_4
+/README.txt/1.2/Wed Sep 10 19:21:53 2003//Ttekkotsu-2_4
+/elp.pl/1.4/Wed Sep 10 20:19:57 2003//Ttekkotsu-2_4
+/modifications.diff/1.1/Wed Sep 10 20:21:00 2003//Ttekkotsu-2_4
+D/doc////
+D/src////
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/CVS/Repository ./tools/mipaltools/CVS/Repository
--- ../Tekkotsu_2.3/tools/mipaltools/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mipaltools
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/CVS/Root ./tools/mipaltools/CVS/Root
--- ../Tekkotsu_2.3/tools/mipaltools/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/CVS/Tag ./tools/mipaltools/CVS/Tag
--- ../Tekkotsu_2.3/tools/mipaltools/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Entries ./tools/mipaltools/doc/CVS/Entries
--- ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/doc/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,4 @@
+/ELPREADME.TXT/1.1/Wed Sep 10 19:21:58 2003//Ttekkotsu-2_4
+/StackedIt_Readme.txt/1.2/Thu Oct  9 15:23:27 2003//Ttekkotsu-2_4
+/license.txt/1.1/Wed Sep 10 19:21:58 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Repository ./tools/mipaltools/doc/CVS/Repository
--- ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/doc/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mipaltools/doc
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Root ./tools/mipaltools/doc/CVS/Root
--- ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/doc/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Tag ./tools/mipaltools/doc/CVS/Tag
--- ../Tekkotsu_2.3/tools/mipaltools/doc/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/doc/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Entries ./tools/mipaltools/src/CVS/Entries
--- ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/src/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,15 @@
+/EmonLog.cc/1.1/Wed Sep 10 19:22:01 2003//Ttekkotsu-2_4
+/EmonLog.h/1.1/Wed Sep 10 19:22:01 2003//Ttekkotsu-2_4
+/Function.cc/1.1/Wed Sep 10 19:22:01 2003//Ttekkotsu-2_4
+/Function.h/1.1/Wed Sep 10 19:22:01 2003//Ttekkotsu-2_4
+/FunctionStore.cc/1.3/Thu Oct  9 15:29:24 2003//Ttekkotsu-2_4
+/FunctionStore.h/1.1/Wed Sep 10 19:22:02 2003//Ttekkotsu-2_4
+/Makefile/1.3/Tue Dec  2 07:00:41 2003//Ttekkotsu-2_4
+/StackAnalyser.cc/1.1/Wed Sep 10 19:22:02 2003//Ttekkotsu-2_4
+/StackAnalyser.h/1.1/Wed Sep 10 19:22:02 2003//Ttekkotsu-2_4
+/StackAnalyserException.h/1.1/Wed Sep 10 19:22:02 2003//Ttekkotsu-2_4
+/StackDump.cc/1.2/Thu Oct  9 15:23:32 2003//Ttekkotsu-2_4
+/StackDump.h/1.1/Wed Sep 10 19:22:02 2003//Ttekkotsu-2_4
+/Trace.h/1.1/Wed Sep 10 19:22:02 2003//Ttekkotsu-2_4
+/main.cc/1.1/Wed Sep 10 19:22:02 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Repository ./tools/mipaltools/src/CVS/Repository
--- ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/src/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mipaltools/src
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Root ./tools/mipaltools/src/CVS/Root
--- ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/src/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Tag ./tools/mipaltools/src/CVS/Tag
--- ../Tekkotsu_2.3/tools/mipaltools/src/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mipaltools/src/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/CVS/Entries ./tools/mon/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,40 @@
+/ControllerGUI/1.7/Wed Jun 29 21:59:24 2005//Ttekkotsu-2_4
+/Makefile/1.20/Thu Mar 31 21:54:08 2005//Ttekkotsu-2_4
+/README/1.1/Fri Jul 25 20:02:48 2003//Ttekkotsu-2_4
+/aibo3d.lws/1.1/Wed Aug 27 02:52:02 2003//Ttekkotsu-2_4
+/c_DepthMap.m/1.3/Tue Jul  1 16:20:40 2003//Ttekkotsu-2_4
+/c_FastSLAM.m/1.1/Wed May 28 14:55:54 2003//Ttekkotsu-2_4
+/c_HeightMap.m/1.1/Thu Mar  6 18:21:17 2003//Ttekkotsu-2_4
+/c_MechaControl.m/1.3/Sun Jun 22 01:30:05 2003//Ttekkotsu-2_4
+/c_statejoints.m/1.2/Wed Jan 28 20:38:50 2004//Ttekkotsu-2_4
+/c_statepids.m/1.1/Thu Feb 20 19:51:18 2003//Ttekkotsu-2_4
+/c_terminal.m/1.1/Wed Apr  9 03:37:31 2003//Ttekkotsu-2_4
+/c_visionraw.m/1.2/Sun Apr  6 20:57:48 2003//Ttekkotsu-2_4
+/c_visionseg.m/1.1/Thu Feb 20 19:51:19 2003//Ttekkotsu-2_4
+/close.m/1.1/Thu Feb 20 19:51:19 2003//Ttekkotsu-2_4
+/closecomponents.m/1.1/Thu Feb 20 19:51:19 2003//Ttekkotsu-2_4
+/colormap_rle_NSHA431.mat/1.1/Thu Feb 20 19:51:20 2003//Ttekkotsu-2_4
+/config.m/1.13/Wed Jan 28 20:38:50 2004//Ttekkotsu-2_4
+/default.col/1.7/Fri Jul 16 22:12:10 2004//Ttekkotsu-2_4
+/defines.m/1.3/Tue Apr 15 20:02:43 2003//Ttekkotsu-2_4
+/ers220info.m/1.1/Wed Jan 28 21:07:44 2004//Ttekkotsu-2_4
+/ers2xxinfo.m/1.1/Wed Jan 28 21:07:44 2004//Ttekkotsu-2_4
+/ftp.jar/1.1/Tue Jul  1 09:00:18 2003/-kb/Ttekkotsu-2_4
+/itercomponents.m/1.1/Thu Feb 20 19:51:20 2003//Ttekkotsu-2_4
+/jargs.jar/1.1/Mon Jul 28 06:30:48 2003/-kb/Ttekkotsu-2_4
+/launcher.m/1.1/Thu Feb 20 19:51:20 2003//Ttekkotsu-2_4
+/loadcomponents.m/1.1/Thu Feb 20 19:51:21 2003//Ttekkotsu-2_4
+/lognow/1.2/Tue Mar 16 17:47:09 2004//Ttekkotsu-2_4
+/plotlog.m/1.4/Tue Feb 24 21:27:27 2004//Ttekkotsu-2_4
+/plotpath.m/1.1/Wed Jan 28 21:07:44 2004//Ttekkotsu-2_4
+/plotpos.m/1.2/Fri Feb  6 00:45:57 2004//Ttekkotsu-2_4
+/run.m/1.2/Sat Jun  7 21:57:21 2003//Ttekkotsu-2_4
+/setslide.m/1.1/Wed Jan 28 21:07:44 2004//Ttekkotsu-2_4
+/togglecomponents.m/1.1/Thu Feb 20 19:51:21 2003//Ttekkotsu-2_4
+/updateAxes.m/1.1/Wed Jan 28 21:07:44 2004//Ttekkotsu-2_4
+/yuv2rgb.m/1.1/Thu Feb 20 19:51:21 2003//Ttekkotsu-2_4
+/zoomin.m/1.1/Wed Jan 28 21:07:44 2004//Ttekkotsu-2_4
+/zoomout.m/1.1/Wed Jan 28 21:07:44 2004//Ttekkotsu-2_4
+D/images////
+D/objects////
+D/org////
diff -urdN ../Tekkotsu_2.3/tools/mon/CVS/Repository ./tools/mon/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon
diff -urdN ../Tekkotsu_2.3/tools/mon/CVS/Root ./tools/mon/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/CVS/Tag ./tools/mon/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/ControllerGUI ./tools/mon/ControllerGUI
--- ../Tekkotsu_2.3/tools/mon/ControllerGUI	Wed Sep  1 00:56:58 2004
+++ ./tools/mon/ControllerGUI	Wed Jun 29 17:59:24 2005
@@ -15,4 +15,4 @@
 	exit 1;
 fi;
 
-java -Xmx256M org.tekkotsu.mon.ControllerGUI $*
+java -Xmx256M org.tekkotsu.mon.ControllerGUI $* &
diff -urdN ../Tekkotsu_2.3/tools/mon/Makefile ./tools/mon/Makefile
--- ../Tekkotsu_2.3/tools/mon/Makefile	Thu Sep 16 14:45:30 2004
+++ ./tools/mon/Makefile	Thu Mar 31 16:54:08 2005
@@ -12,7 +12,7 @@
 
 # SEP is to use ';' on windows and ':' on unix because windows is mentally deficient
 SEP:=$(shell if [ "`uname`" = "CYGWIN" -o "`uname`" \> "CYGWIN" -a "`uname`" \< "CYGWIO" ] ; then echo ";" ; else echo ":" ; fi )
-CXXFLAGS=-deprecation -classpath ".$(SEP)./ftp.jar$(SEP)./jargs.jar"
+CXXFLAGS=-deprecation -classpath ".$(SEP)./ftp.jar$(SEP)./jargs.jar" 
 
 .PHONY: all clean build clearbuildlist
 
diff -urdN ../Tekkotsu_2.3/tools/mon/images/CVS/Entries ./tools/mon/images/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/images/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/images/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,15 @@
+/chasingarrows.gif/1.1/Tue Oct  7 04:14:51 2003/-kb/Ttekkotsu-2_4
+/chasingarrows.png/1.3/Wed Aug 27 02:06:55 2003/-kb/Ttekkotsu-2_4
+/disconnect.gif/1.1/Tue Oct  7 04:14:52 2003/-kb/Ttekkotsu-2_4
+/disconnect.png/1.1/Tue Oct  7 03:28:42 2003/-kb/Ttekkotsu-2_4
+/go.gif/1.1/Tue Oct  7 04:14:52 2003/-kb/Ttekkotsu-2_4
+/go.png/1.1/Tue Oct  7 03:28:42 2003/-kb/Ttekkotsu-2_4
+/larrow.gif/1.1/Tue Oct  7 04:14:52 2003/-kb/Ttekkotsu-2_4
+/larrow.png/1.3/Wed Aug 27 02:06:55 2003/-kb/Ttekkotsu-2_4
+/offline.gif/1.1/Wed Oct  8 19:09:26 2003/-kb/Ttekkotsu-2_4
+/online.gif/1.1/Wed Oct  8 19:09:26 2003/-kb/Ttekkotsu-2_4
+/rarrow.gif/1.1/Tue Oct  7 04:14:52 2003/-kb/Ttekkotsu-2_4
+/rarrow.png/1.3/Wed Aug 27 02:06:55 2003/-kb/Ttekkotsu-2_4
+/stop.gif/1.1/Tue Oct  7 04:14:52 2003/-kb/Ttekkotsu-2_4
+/stop.png/1.1/Tue Oct  7 03:28:42 2003/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/mon/images/CVS/Repository ./tools/mon/images/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/images/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/images/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/images
diff -urdN ../Tekkotsu_2.3/tools/mon/images/CVS/Root ./tools/mon/images/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/images/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/images/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/images/CVS/Tag ./tools/mon/images/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/images/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/images/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/objects/CVS/Entries ./tools/mon/objects/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/objects/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/objects/CVS/Entries	Wed Aug 10 11:03:28 2005
@@ -0,0 +1,28 @@
+/LED_g01.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/LED_g02.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/LED_g03.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/LED_r01.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/LED_r02.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/LED_r03.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/LED_r04.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/LED_tail.lwo/1.1/Wed Aug 27 02:52:06 2003/-kb/Ttekkotsu-2_4
+/body2.lwo/1.1/Wed Aug 27 02:52:07 2003/-kb/Ttekkotsu-2_4
+/ear-l.lwo/1.1/Wed Aug 27 02:52:07 2003/-kb/Ttekkotsu-2_4
+/ear-r.lwo/1.1/Wed Aug 27 02:52:07 2003/-kb/Ttekkotsu-2_4
+/foot-b-l.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/foot-b-r.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/foot-f-l.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/foot-f-r.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/head.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/jaw.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/leg-b-low-l.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/leg-b-low-r.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/leg-b-up-l.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/leg-b-up-r.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/leg-f-low-l.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/leg-f-low-r.lwo/1.1/Wed Aug 27 02:52:08 2003/-kb/Ttekkotsu-2_4
+/leg-f-up-l.lwo/1.1/Wed Aug 27 02:52:09 2003/-kb/Ttekkotsu-2_4
+/leg-f-up-r.lwo/1.1/Wed Aug 27 02:52:09 2003/-kb/Ttekkotsu-2_4
+/neck.lwo/1.1/Wed Aug 27 02:52:09 2003/-kb/Ttekkotsu-2_4
+/tail2.lwo/1.1/Wed Aug 27 02:52:09 2003/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/mon/objects/CVS/Repository ./tools/mon/objects/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/objects/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/objects/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/objects
diff -urdN ../Tekkotsu_2.3/tools/mon/objects/CVS/Root ./tools/mon/objects/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/objects/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/objects/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/objects/CVS/Tag ./tools/mon/objects/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/objects/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/objects/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/org/CVS/Entries ./tools/mon/org/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/org/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+D/tekkotsu////
diff -urdN ../Tekkotsu_2.3/tools/mon/org/CVS/Repository ./tools/mon/org/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/org/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/CVS/Repository	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/org
diff -urdN ../Tekkotsu_2.3/tools/mon/org/CVS/Root ./tools/mon/org/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/org/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/CVS/Root	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/org/CVS/Tag ./tools/mon/org/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/org/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/CVS/Tag	Wed Aug 10 11:03:28 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Entries ./tools/mon/org/tekkotsu/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,3 @@
+D/aibo3d////
+D/mon////
+D/sketch////
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Repository ./tools/mon/org/tekkotsu/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/CVS/Repository	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/org/tekkotsu
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Root ./tools/mon/org/tekkotsu/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/CVS/Root	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Tag ./tools/mon/org/tekkotsu/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/CVS/Tag	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Entries ./tools/mon/org/tekkotsu/aibo3d/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/aibo3d/CVS/Entries	Wed Aug 10 11:03:29 2005
@@ -0,0 +1,12 @@
+/Aibo3D.java/1.2/Thu Oct  9 19:11:26 2003//Ttekkotsu-2_4
+/Aibo3DForward.java/1.1/Fri Sep 26 04:36:17 2003//Ttekkotsu-2_4
+/Aibo3DPick.java/1.2/Thu Oct  2 02:07:33 2003//Ttekkotsu-2_4
+/AiboJoint.java/1.1/Fri Sep 26 04:36:17 2003//Ttekkotsu-2_4
+/AiboPicker.java/1.1/Fri Sep 26 04:36:17 2003//Ttekkotsu-2_4
+/InverseKinematics.java/1.1/Fri Sep 26 04:36:17 2003//Ttekkotsu-2_4
+/Java3DTest.java/1.1/Wed Oct  1 23:45:16 2003//Ttekkotsu-2_4
+/Kinematics.java/1.1/Fri Sep 26 04:36:17 2003//Ttekkotsu-2_4
+/LegConfiguration.java/1.1/Fri Sep 26 04:36:17 2003//Ttekkotsu-2_4
+/PickMoveBehavior.java/1.1/Fri Sep 26 04:36:17 2003//Ttekkotsu-2_4
+/WorldStateJointsWriter.java/1.3/Thu Oct  9 19:12:03 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Repository ./tools/mon/org/tekkotsu/aibo3d/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/aibo3d/CVS/Repository	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/org/tekkotsu/aibo3d
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Root ./tools/mon/org/tekkotsu/aibo3d/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/aibo3d/CVS/Root	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Tag ./tools/mon/org/tekkotsu/aibo3d/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/aibo3d/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/aibo3d/CVS/Tag	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/AgentShapeInfo.java ./tools/mon/org/tekkotsu/mon/AgentShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/AgentShapeInfo.java	Thu Apr 22 18:46:02 2004
+++ ./tools/mon/org/tekkotsu/mon/AgentShapeInfo.java	Wed Dec 31 19:00:00 1969
@@ -1,38 +0,0 @@
-package org.tekkotsu.mon;
-
-import java.awt.Graphics2D;
-import javax.swing.Icon;
-import javax.swing.ImageIcon;
-
-public class AgentShapeInfo extends ShapeInfo {
-	static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/agent.png");
-	float orientation; // orientation of agent
-
-	public AgentShapeInfo(int _id, int _parentId, String _name, int _color,
-			float _centroidx, float _centroidy, float _centroidz,
-			float _orientation) {
-		super(_id, _parentId, _name, _color, _centroidx,_centroidy, _centroidz);
-		orientation = _orientation;
-	}
-
-	// returns left-most coordinate of object (want some buffer)
-	public float getLeft() { return centroidx-2; }
-	// returns right-most coordinate of object
-	public float getRight() { return centroidx+2; }
-	// returns top-most coordinate of object
-	public float getTop() { return centroidy-2; }
-	// returns bottom-most coordinate of object
-	public float getBottom() { return centroidy+2; }
-
-	public String toString() {
-		return (super.toString() + "(orientation " + orientation + ")");
-	}	
-	
-	public Icon getIcon() { return icon; }
-
-	public void renderTo(Graphics2D graphics) {
-		graphics.drawOval((int)(getCentroidX()+1),
-			(int)(getCentroidY()+1), 5, 5);
-	}
-	public float getOrientation() { return orientation; }
-}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/Base64.java ./tools/mon/org/tekkotsu/mon/Base64.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/Base64.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/Base64.java	Wed Jun  1 01:48:08 2005
@@ -0,0 +1,159 @@
+
+//*********************************************************************
+//* Base64 - a simple base64 encoder and decoder.
+//*
+//*     Copyright (c) 1999, Bob Withers - bwit@pobox.com
+//*
+//* This code may be freely used for any purpose, either personal
+//* or commercial, provided the authors copyright notice remains
+//* intact.
+//*********************************************************************
+
+
+public class Base64
+{
+    public static String encode(String data)
+    {
+        return(getString(encode(getBinaryBytes(data))));
+    }
+
+    public static byte[] encode(byte[] data)
+    {
+        int c;
+        int len = data.length;
+        StringBuffer ret = new StringBuffer(((len / 3) + 1) * 4);
+        for (int i = 0; i < len; ++i)
+        {
+            c = (data[i] >> 2) & 0x3f;
+            ret.append(cvt.charAt(c));
+            c = (data[i] << 4) & 0x3f;
+            if (++i < len)
+                c |= (data[i] >> 4) & 0x0f;
+
+            ret.append(cvt.charAt(c));
+            if (i < len)
+            {
+                c = (data[i] << 2) & 0x3f;
+                if (++i < len)
+                    c |= (data[i] >> 6) & 0x03;
+
+                ret.append(cvt.charAt(c));
+            }
+            else
+            {
+                ++i;
+                ret.append((char) fillchar);
+            }
+
+            if (i < len)
+            {
+                c = data[i] & 0x3f;
+                ret.append(cvt.charAt(c));
+            }
+            else
+            {
+                ret.append((char) fillchar);
+            }
+        }
+
+        return(getBinaryBytes(ret.toString()));
+    }
+
+    public static String decode(String data)
+    {
+        return(getString(decode(getBinaryBytes(data))));
+    }
+
+    public static byte[] decode(byte[] data)
+    {
+        int c;
+        int c1;
+        int len = data.length;
+        StringBuffer ret = new StringBuffer((len * 3) / 4);
+        for (int i = 0; i < len; ++i)
+        {
+            c = cvt.indexOf(data[i]);
+            ++i;
+            c1 = cvt.indexOf(data[i]);
+            c = ((c << 2) | ((c1 >> 4) & 0x3));
+            ret.append((char) c);
+            if (++i < len)
+            {
+                c = data[i];
+                if (fillchar == c)
+                    break;
+
+                c = cvt.indexOf((char) c);
+                c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
+                ret.append((char) c1);
+            }
+
+            if (++i < len)
+            {
+                c1 = data[i];
+                if (fillchar == c1)
+                    break;
+
+                c1 = cvt.indexOf((char) c1);
+                c = ((c << 6) & 0xc0) | c1;
+                ret.append((char) c);
+            }
+        }
+
+        return(getBinaryBytes(ret.toString()));
+    }
+
+    private static String getString(byte[] arr)
+    {
+        StringBuffer buf = new StringBuffer();
+        for (int i = 0; i < arr.length; ++i)
+            buf.append((char) arr[i]);
+
+        return(buf.toString());
+    }
+
+    private static byte[] getBinaryBytes(String str)
+    {
+        byte[] b = new byte[str.length()];
+        for (int i = 0; i < b.length; ++i)
+            b[i] = (byte) str.charAt(i);
+
+        return(b);
+    }
+
+    private static final int    fillchar = '=';
+
+                                    // 00000000001111111111222222
+                                    // 01234567890123456789012345
+    private static final String cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+
+                                    // 22223333333333444444444455
+                                    // 67890123456789012345678901
+                                    + "abcdefghijklmnopqrstuvwxyz"
+
+                                    // 555555556666
+                                    // 234567890123
+                                    + "0123456789+/";
+
+    public static void main(String[] args)
+    {
+        String str;
+        if (args.length > 0)
+            str = args[0];
+        else
+            str = "Now is the time for all good men";
+
+        System.out.println("Encoding string [" + str + "]");
+        str = encode(str);
+        System.out.println("Encoded string  [" + str + "]");
+        str = decode(str);
+        System.out.println("Decoded string  [" + str + "]");
+        System.out.println();
+        byte[] b = getBinaryBytes(str);
+        System.out.println("Encoding bytes  [" + getString(b) + "]");
+        b = encode(b);
+        System.out.println("Encoded bytes   [" + getString(b) + "]");
+        b = decode(b);
+        System.out.println("Decoded bytes   [" + getString(b) + "]");
+    }
+}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Entries ./tools/mon/org/tekkotsu/mon/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,63 @@
+/AiboComm.java/1.1/Fri Sep 26 04:36:18 2003//Ttekkotsu-2_4
+/Base64.java/1.1/Wed Jun  1 05:48:08 2005//Ttekkotsu-2_4
+/ClassPathModifier.java/1.1/Fri Sep 26 04:36:18 2003//Ttekkotsu-2_4
+/ControllerErr.java/1.1/Sun Jan 11 07:57:29 2004//Ttekkotsu-2_4
+/ControllerGUI.java/1.27/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/ControllerListener.java/1.13/Fri Jun 10 19:15:25 2005//Ttekkotsu-2_4
+/ControllerMsg.java/1.3/Sun Jan 11 07:57:30 2004//Ttekkotsu-2_4
+/DogConfig.java/1.2/Wed Jan 21 06:59:17 2004//Ttekkotsu-2_4
+/DogConfigFTP.java/1.1/Fri Sep 26 04:36:18 2003//Ttekkotsu-2_4
+/EStopButton.java/1.8/Tue Aug  2 21:33:36 2005//Ttekkotsu-2_4
+/EStopGUI.java/1.3/Fri Jan 21 23:31:39 2005//Ttekkotsu-2_4
+/EStopListener.java/1.6/Tue Aug  2 22:25:04 2005//Ttekkotsu-2_4
+/EStopPanel.java/1.3/Tue Aug  2 21:33:36 2005//Ttekkotsu-2_4
+/EditScriptGUI.java/1.4/Fri Jan 21 23:31:39 2005//Ttekkotsu-2_4
+/GraphCanvas.java/1.1/Fri Sep 26 04:36:19 2003//Ttekkotsu-2_4
+/HeadPointGUI.java/1.3/Fri Jan 21 23:31:39 2005//Ttekkotsu-2_4
+/HeadPointListener.java/1.5/Wed Jun 22 20:06:17 2005//Ttekkotsu-2_4
+/ImageSequenceWriterThread.java/1.8/Tue Jan 20 20:05:31 2004//Ttekkotsu-2_4
+/JointLogger.java/1.1/Wed Jan 28 21:08:46 2004//Ttekkotsu-2_4
+/JointRelay.java/1.3/Fri Nov 12 22:07:40 2004//Ttekkotsu-2_4
+/JointRequestor.java/1.1/Wed Jan 28 21:08:46 2004//Ttekkotsu-2_4
+/JointWriter.java/1.2/Tue Feb 24 21:13:27 2004//Ttekkotsu-2_4
+/Joints.java/1.3/Fri Apr 16 05:51:29 2004//Ttekkotsu-2_4
+/Listener.java/1.9/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/MechaController.java/1.4/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+/MicrophoneClient.java/1.2/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+/NetDebug.java/1.1/Fri Sep 26 04:36:20 2003//Ttekkotsu-2_4
+/PIDs.java/1.1/Fri Sep 26 04:36:20 2003//Ttekkotsu-2_4
+/ParamListener.java/1.3/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+/PointPick.java/1.2/Fri Jan 21 23:31:39 2005//Ttekkotsu-2_4
+/PrintDuties.java/1.1/Fri Sep 26 04:36:20 2003//Ttekkotsu-2_4
+/ScriptEntry.java/1.1/Fri Sep 26 04:36:20 2003//Ttekkotsu-2_4
+/SpeakerClient.java/1.1/Fri Nov 12 22:07:40 2004//Ttekkotsu-2_4
+/SquareRightLayout.java/1.1/Fri Sep 26 04:36:20 2003//Ttekkotsu-2_4
+/TCPListener.java/1.5/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+/TCPVisionListener.java/1.12/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/TableMap.java/1.1/Fri Sep 26 04:36:20 2003//Ttekkotsu-2_4
+/TableSorter.java/1.1/Fri Sep 26 04:36:20 2003//Ttekkotsu-2_4
+/Terminal.java/1.2/Fri Jan 21 23:31:39 2005//Ttekkotsu-2_4
+/TestGraph.java/1.2/Fri Jan 21 23:31:39 2005//Ttekkotsu-2_4
+/TextListener.java/1.3/Fri Nov 12 22:07:40 2004//Ttekkotsu-2_4
+/TextWatchableMemory.java/1.1/Fri Sep 26 04:36:21 2003//Ttekkotsu-2_4
+/TwoParamPanel.java/1.2/Wed Jun  1 05:48:09 2005//Ttekkotsu-2_4
+/UDPListener.java/1.10/Fri Jul 29 23:08:03 2005//Ttekkotsu-2_4
+/UDPVisionListener.java/1.15/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/VisionGUI.java/1.17/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/VisionListener.java/1.13/Fri Aug  5 19:44:23 2005//Ttekkotsu-2_4
+/VisionPanel.java/1.20/Fri Aug  5 21:25:42 2005//Ttekkotsu-2_4
+/VisionUpdatedListener.java/1.2/Thu Mar  3 22:53:54 2005//Ttekkotsu-2_4
+/WM2DMData.java/1.1/Fri Sep 26 04:36:22 2003//Ttekkotsu-2_4
+/WM2DMListener.java/1.4/Wed Jun  8 21:05:03 2005//Ttekkotsu-2_4
+/WM2FSData.java/1.1/Fri Sep 26 04:36:22 2003//Ttekkotsu-2_4
+/WM2FSListener.java/1.4/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+/WM2HMData.java/1.1/Fri Sep 26 04:36:22 2003//Ttekkotsu-2_4
+/WM2HMListener.java/1.4/Wed Jun  8 21:05:03 2005//Ttekkotsu-2_4
+/WMvar.java/1.1/Fri Sep 26 04:36:22 2003//Ttekkotsu-2_4
+/WalkGUI.java/1.4/Fri Jan 21 23:31:39 2005//Ttekkotsu-2_4
+/WatchableMemory.java/1.7/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+/WatchableMemoryListener.java/1.4/Fri Nov 12 22:07:40 2004//Ttekkotsu-2_4
+/WorldModel2Conf.java/1.1/Fri Sep 26 04:36:23 2003//Ttekkotsu-2_4
+/WorldStateJointsListener.java/1.5/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+/WorldStatePIDsListener.java/1.4/Wed Jun  8 21:05:01 2005//Ttekkotsu-2_4
+D/icons////
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Repository ./tools/mon/org/tekkotsu/mon/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/CVS/Repository	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/org/tekkotsu/mon
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Root ./tools/mon/org/tekkotsu/mon/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/CVS/Root	Wed Aug 10 11:03:29 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Tag ./tools/mon/org/tekkotsu/mon/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ControllerGUI.java ./tools/mon/org/tekkotsu/mon/ControllerGUI.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ControllerGUI.java	Fri Jan 21 17:50:40 2005
+++ ./tools/mon/org/tekkotsu/mon/ControllerGUI.java	Fri Aug  5 15:44:23 2005
@@ -12,17 +12,19 @@
 
 //Admittedly a little sloppy, but I don't want to spend forever on this...
 
-public class ControllerGUI extends JFrame implements ActionListener, KeyListener {
+public class ControllerGUI extends JFrame implements ActionListener, KeyListener, EStopListener.UpdatedListener {
 	JList menu;
 	JScrollPane menuScroll;
 	JComboBox title;
 	JLabel status;
 	JList scripts;
 	ControllerListener comm;
+	EStopListener estopComm;
 	JButton backBut;
 	JButton refreshBut;
 	JButton reconnectBut;
-	EStopButton estop;
+	EStopPanel estop;
+	JButton estopBut;
 	JTextField inputField;
 	boolean isUpdating=false;
 	DefaultListModel scriptsModel=new DefaultListModel();
@@ -36,6 +38,7 @@
 		comm = new ControllerListener(addr,port);
 		comm.listener=this;
 		init();
+		comm.needConnection();
 	}
 
 	// Disables the component if there's nothing selected to apply it to
@@ -88,7 +91,9 @@
 			title.setEnabled(list.isEnabled());
 			title.setFont(list.getFont());
 			title.setOpaque(true);
-			title.setPreferredSize(new Dimension(list.getSize().width,title.getPreferredSize().height));
+			//I would rather use title.getPreferredSize().height instead of the hard-coded 15
+			//but sometimes values around 16390 are returned, and sometimes 0 -- doesn't make sense
+			title.setPreferredSize(new Dimension(list.getSize().width,15));
 			//Vector tmp2=new Vector();
 			//for(int i=0;i<1000000;i++) {tmp2.add(new Integer(0));tmp2.remove(tmp2.size()-1);}
 			if(cellHasFocus)
@@ -161,8 +166,14 @@
 		}
 	}
  	
+	void gotConnection() {
+		updated();
+		repaint();
+	}
+
 	void lostConnection() {
 		updated();
+		repaint();
 	}
 
 	void updated() {
@@ -173,13 +184,17 @@
 		//scripts.setEnabled(comm._isConnected);
 		title.setEnabled(comm._isConnected);
 		backBut.setEnabled(comm._isConnected);
+		estopBut.setEnabled(comm._isConnected);
 		refreshBut.setEnabled(comm._isConnected);
 		inputField.setEnabled(comm._isConnected);
-		title.removeAllItems();//clearing the title popup menu, but we'll refresh the items if we're still connected
 		if(!comm._isConnected) {
-			title.addItem("-");
-			menu.setListData(new Vector());
-			status.setText("Reconnecting...");
+			synchronized(menuScroll) {
+				title.removeAllItems();
+				title.addItem("-");
+				menu.setListData(new Vector());
+				status.setText("Reconnecting...");
+				status.setToolTipText("");
+			}
 		} else {
 			if(comm._connectCount>0) {
 				if(comm._connectCount==1) {
@@ -198,19 +213,38 @@
 						comm.sendInput(((ScriptEntry)scriptsModel.get(i)).cmd);
 				comm._connectCount=-1; //so we don't get it again
 			}
+
+			Vector menuitems;
 			synchronized(comm._menus) {
-				int len=0;
-				for(Iterator it=comm._titles.iterator(); it.hasNext();) {
+				boolean titleDirty=false;
+				int index=comm._titles.size()-1;
+				for(Iterator it=comm._titles.iterator(); index>=0 && it.hasNext();index--) {
 					String entry=(String)it.next();
-					title.insertItemAt(entry,0);
-					if(entry.length()>len)
-						len=entry.length();
+					if(!entry.equals((String)title.getItemAt(index))) {
+						titleDirty=true;
+						break;
+					}
 				}
-				title.setMaximumSize(new Dimension((int)(len*8)+25,title.getHeight()));
-				title.setSelectedIndex(0);
-				Vector menuitems=(Vector)comm._menus.lastElement();
+				if(titleDirty) {
+					title.removeAllItems();//clearing the title popup menu, but we'll refresh the items if we're still connected
+					int len=0;
+					for(Iterator it=comm._titles.iterator(); it.hasNext();) {
+						String entry=(String)it.next();
+						title.insertItemAt(entry,0);
+						if(entry.length()>len)
+							len=entry.length();
+					}
+					title.setMaximumSize(new Dimension((int)(len*8)+25,title.getHeight()));
+					title.setSelectedIndex(0);
+				}
+				menuitems=(Vector)comm._menus.lastElement();
+				menuitems=(Vector)menuitems.clone();
+				updateStatusText();
+			}
+
+			//synchronized(this) {
 				menu.setValueIsAdjusting(true);
-				menu.setListData((Vector)menuitems.clone());
+				menu.setListData(menuitems);
 				Vector sels=new Vector();
 				for(int i=0; i<menuitems.size(); i++)
 					if(((ControllerListener.MenuEntry)menuitems.get(i)).selected)
@@ -220,24 +254,42 @@
 					selsArr[i]=((Integer)sels.get(i)).intValue();
 				menu.setSelectedIndices(selsArr);
 				menu.setValueIsAdjusting(false);
-			}
-			status.setText(comm._status.length()>0?comm._status:"Connected.");
+			//}
 		}
 		menuScroll.getViewport().setViewPosition(p);
 		isUpdating=false;
 		comm._updatedFlag=false;
 	}
 
-	public void paint(Graphics g) {
+	/*public void paint(Graphics g) {
 		if(comm!=null && comm._updatedFlag)
 			updated();
 		super.paint(g);
+		}*/
+
+	public void estopUpdated(EStopListener l) {
+		updateStatusText();
+		if(estopBut!=null)
+			estopBut.setText(estopComm.getEStop()?"Un-Stop":"Stop!");
+	}
+	
+	public void updateStatusText() {
+		if(comm._status.length()>0) {
+			status.setText(comm._status);
+		} else {
+			if(status!=null && estopComm!=null) //otherwise still doing initial connect, leave at default text
+				status.setText(estopComm.getEStop()?"Stopped":"Running");
+		}
+		if(status!=null)
+			status.setToolTipText(comm._status);
 	}
 	
 	public void actionPerformed(ActionEvent evt) {
 		if(evt.getSource()==backBut) {
 			//System.out.println("back button clicked");
 			comm.sendReturn();
+		} else if(evt.getSource()==estopBut) {
+			estopComm.toggleEStop();
 		} else if(evt.getSource()==refreshBut) {
 			//System.out.println("refresh button clicked");
 			comm.sendRefresh();
@@ -276,16 +328,21 @@
 			comm.dynObjs=dynObjs;
 			comm.dynObjSrcs=dynObjSrcs;
 			comm.dynObjPorts=dynObjPorts;
+			comm.needConnection();
 			estop.close();
 			estop.open();
-		} else if(evt.getActionCommand().equals("raw") || evt.getActionCommand().equals("rle")) {
+		} else if(evt.getActionCommand().equals("raw") || evt.getActionCommand().equals("rle") || evt.getActionCommand().equals("reg")) {
 			if(evt.getActionCommand().equals("raw")) {
 				comm.sendInput("!root \"TekkotsuMon\" \"Raw Cam Server\"");
 				comm.dynObjSrcs.put("RawVisionGUI","\"TekkotsuMon\" \"Raw Cam Server\"");
-			} else {
+			} else if(evt.getActionCommand().equals("rle")) {
 				comm.sendInput("!root \"TekkotsuMon\" \"Seg Cam Server\"");
 				comm.dynObjSrcs.put("SegVisionGUI","\"TekkotsuMon\" \"Seg Cam Server\"");
+			} else {
+				comm.sendInput("!root \"TekkotsuMon\" \"Region Cam Server\"");
+				comm.dynObjSrcs.put("RegionVisionGUI","\"TekkotsuMon\" \"Region Cam Server\"");
 			}
+ 
 		} else if(evt.getActionCommand().equals("addbookmark")) {
 			int sel=comm.firstSelected();
 			if(sel==-1 || !comm._isConnected) {
@@ -345,10 +402,20 @@
 		public Dimension getSize() { return dim; }
 	}
 
+	public class SynchPaint extends JScrollPane {
+		public Object lock=new Object();
+		
+		SynchPaint(JList l) { super(l); }
+		public void paint(Graphics g) {
+			synchronized(lock) {
+				super.paint(g);
+			}
+		}
+	}
+
 	protected void init() {
 		int spacer_size=10;
 	
-		
 		setTitle("TekkotsuMon: Controller Menus");
 		getContentPane().setLayout(new BorderLayout());
 		getContentPane().add(Box.createHorizontalStrut(spacer_size),BorderLayout.WEST);
@@ -375,6 +442,7 @@
 		
 		Box menuBox=Box.createVerticalBox();
 		menuScroll=new JScrollPane(menu);
+		//menuScroll.lock=this;
 		menuScroll.setAlignmentX(0.5f);
 		menuBox.add(menuScroll);
 		{
@@ -403,14 +471,27 @@
 		statusbox.add(Box.createVerticalStrut(spacer_size-2));
 		{
 			JPanel tmp=new JPanel(new BorderLayout());
+			{
+				Box tmp2=Box.createHorizontalBox();
+				estopComm=new EStopListener(comm._host,EStopListener.defPort);
+				estopComm.addUpdatedListener(this);
+				estop=new EStopPanel(estopComm,true);
+				estop.setMyDim(new Dimension(carrows.getIconWidth(),carrows.getIconHeight()));
+				//estop.setMargin(new Insets(0,0,0,0));
+				tmp2.add(estop);
+				tmp2.add(Box.createHorizontalStrut(spacer_size));
+				tmp.add(tmp2,BorderLayout.WEST);
+			}
 			status=new JLabel("Connecting...");
 			tmp.add(status,BorderLayout.CENTER);
 			{
 				Box tmp2=Box.createHorizontalBox();
-				estop=new EStopButton(new EStopListener(comm._host,EStopListener.defPort));
-				estop.setMyDim(new Dimension(65,27));
-				estop.setMargin(new Insets(0,0,0,0));
-				tmp2.add(estop);
+				estopBut=new JButton("Stop!");
+				estopBut.setText(estopComm.getEStop()?"Un-Stop":"Stop!");
+				estopBut.addActionListener(this);
+				estopBut.setToolTipText("Toggle the emergency stop status");
+				estopBut.setEnabled(false);
+				tmp2.add(estopBut);
 				tmp2.add(Box.createHorizontalStrut(spacer_size));
 				reconnectBut=new JButton(carrows);
 				reconnectBut.setPreferredSize(new Dimension(carrows.getIconWidth(),carrows.getIconHeight()));
@@ -425,14 +506,14 @@
 		
 		Box p=Box.createVerticalBox();
 		p.add(new JLabel("Send Input:"));
-    inputFieldHistory=new Vector();
+		inputFieldHistory=new Vector();
 		for(int i=0; i<MAX_STORE_INPUT_HIST; i++)
 			inputFieldHistory.add(prefs.get("inputFieldHistory"+i,""));
-    inputFieldLocation=inputFieldHistory.size();
+		inputFieldLocation=inputFieldHistory.size();
 		p.add(inputField=new JTextField());
 		inputField.setEnabled(false);
 		inputField.addActionListener(this);
-    inputField.addKeyListener(this);
+		inputField.addKeyListener(this);
 		inputField.setPreferredSize(new Dimension(30,inputField.getPreferredSize().height));
 		inputField.setToolTipText("Text from here is passed to selected controls, or the current control if no selection");
 
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ControllerListener.java ./tools/mon/org/tekkotsu/mon/ControllerListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ControllerListener.java	Fri Jan 21 18:31:39 2005
+++ ./tools/mon/org/tekkotsu/mon/ControllerListener.java	Fri Jun 10 15:15:25 2005
@@ -139,6 +139,10 @@
 			sin=socket.getInputStream();
 			_out=new PrintStream(socket.getOutputStream());
 			fireConnected();
+			if(listener!=null) {
+				listener.gotConnection();
+				//listener.repaint();
+			}
 			_out.println("!hello");
 			_out.println("!dump_stack");
 			_out.println("!refresh");
@@ -279,11 +283,13 @@
 						System.err.println("ControllerListener - Invalid message type:"+msgtype);
 					}
 					_updatedFlag=true;
-					if(listener!=null)
-						listener.repaint();
-					else
-						System.out.println("null listener");
-				}
+				} //end of synchronized update section
+				if(listener!=null) {
+					//System.out.println("Listener repaint");
+					//listener.repaint();
+					listener.updated();
+				} else
+					System.out.println("null listener");
 			}
 		} catch (SocketException e) {
 		} catch (Exception e) {
@@ -302,7 +308,7 @@
 		_status="Reconnecting.";
 		if(listener!=null) {
 			listener.lostConnection();
-			listener.repaint();
+			//listener.repaint();
 		}
 		//The sleep is to get around the socket still listening after being closed thing
 		//if(!destroy)
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EStopButton.java ./tools/mon/org/tekkotsu/mon/EStopButton.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EStopButton.java	Fri Jan 21 18:31:39 2005
+++ ./tools/mon/org/tekkotsu/mon/EStopButton.java	Tue Aug  2 17:33:36 2005
@@ -76,9 +76,9 @@
 	public void setMyDim(Dimension d) { dim=d; }
 	public Dimension getMyDim() { return dim; }
 
-	public Dimension getPreferredSize() { return dim; }
-	public Dimension getMinimumSize() { return dim; }
-	public Dimension getMaximumSize() { return dim; }
+	public Dimension getPreferredSize() { return (dim==null) ? super.getPreferredSize() : dim; }
+	public Dimension getMinimumSize() { return (dim==null) ? super.getPreferredSize() : dim; }
+	public Dimension getMaximumSize() { return (dim==null) ? super.getPreferredSize() : dim; }
 	
 	public void estopUpdated(EStopListener l) {
 		if(l.isConnected()) {
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EStopListener.java ./tools/mon/org/tekkotsu/mon/EStopListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EStopListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/EStopListener.java	Tue Aug  2 18:25:04 2005
@@ -9,19 +9,19 @@
 import java.net.SocketException;
 
 public class EStopListener extends TCPListener {
-  // The command output stream
+	// The command output stream
 	static int defPort=10053;
-  PrintStream out;
+	PrintStream out;
 	boolean stopped=true;
 	boolean data=false;
-  Socket mysock;
+	Socket mysock;
 	Vector listeners=new Vector();
 	
 	public interface UpdatedListener {
 		public void estopUpdated(EStopListener mc);
 	}
 
-	public void addUpdatedListener(UpdatedListener mcl) { listeners.add(mcl); }
+	public void addUpdatedListener(UpdatedListener mcl) { listeners.add(mcl); needConnection(); }
 	public	void removeUpdatedListener(UpdatedListener mcl) {
 		listeners.remove(mcl);
 		if(listeners.size()==0)
@@ -29,10 +29,14 @@
 	}
 	void fireUpdated() {
 		data=true;
+		if(listeners==null) {
+			System.out.println("wtf?");
+			listeners=new Vector();
+		}
 		for(int i=0;i<listeners.size();i++)
 			((UpdatedListener)listeners.get(i)).estopUpdated(this);
 	}
-
+	
   // Connect to control socket
   public void connected(Socket socket) {
     mysock = socket;
@@ -85,6 +89,8 @@
   }
 
 	public void setEStop(boolean b) {
+		if(!isConnected())
+			return;
 		if(b!=stopped) {
 			out.print(b?"stop\n":"start\n");
 		}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EStopPanel.java ./tools/mon/org/tekkotsu/mon/EStopPanel.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EStopPanel.java	Fri Jan 21 18:31:39 2005
+++ ./tools/mon/org/tekkotsu/mon/EStopPanel.java	Tue Aug  2 17:33:36 2005
@@ -52,28 +52,54 @@
 
 	public EStopPanel(EStopListener comm) {
 		super();
-		
+		init(comm,false);
+	}
+	
+	public EStopPanel(EStopListener comm, boolean isStatus) {
+		super();
+		init(comm,isStatus);
+	}
+	
+	protected void init(EStopListener comm, boolean isStatus) {
 		this.comm=comm;
 		mode=comm.isConnected()?(comm.getEStop()?STOPPED_MODE:NOTSTOPPED_MODE):DISABLED_MODE;
 		setEnabled(mode!=DISABLED_MODE);
 		comm.addUpdatedListener(this);
 		
-		shape[NOTSTOPPED_MODE]=makeStopSign();
-		stroke[NOTSTOPPED_MODE]=new BasicStroke(res/30);
-		fill[NOTSTOPPED_MODE]=Color.RED;
-		line[NOTSTOPPED_MODE]=Color.BLACK;
-		text[NOTSTOPPED_MODE]="STOP";
-		textFill[NOTSTOPPED_MODE]=Color.WHITE;
-		textSize[NOTSTOPPED_MODE]=3.125f;
-
-		shape[STOPPED_MODE]=new Ellipse2D.Float(0,0,res,res);
-		stroke[STOPPED_MODE]=new BasicStroke(res/30);
-		fill[STOPPED_MODE]=Color.GREEN;
-		line[STOPPED_MODE]=Color.BLACK;
-		text[STOPPED_MODE]="GO";
-		textFill[STOPPED_MODE]=Color.BLACK;
-		textSize[STOPPED_MODE]=2.5f;
+		if(!isStatus) {
+			shape[NOTSTOPPED_MODE]=makeStopSign();
+			stroke[NOTSTOPPED_MODE]=new BasicStroke(res/30);
+			fill[NOTSTOPPED_MODE]=Color.RED;
+			line[NOTSTOPPED_MODE]=Color.BLACK;
+			text[NOTSTOPPED_MODE]="STOP";
+			textFill[NOTSTOPPED_MODE]=Color.WHITE;
+			textSize[NOTSTOPPED_MODE]=3.125f;
 
+			shape[STOPPED_MODE]=new Ellipse2D.Float(0,0,res,res);
+			stroke[STOPPED_MODE]=new BasicStroke(res/30);
+			fill[STOPPED_MODE]=Color.GREEN;
+			line[STOPPED_MODE]=Color.BLACK;
+			text[STOPPED_MODE]="GO";
+			textFill[STOPPED_MODE]=Color.BLACK;
+			textSize[STOPPED_MODE]=2.5f;
+		} else {
+			shape[STOPPED_MODE]=makeStopSign();
+			stroke[STOPPED_MODE]=new BasicStroke(res/30);
+			fill[STOPPED_MODE]=Color.RED;
+			line[STOPPED_MODE]=Color.BLACK;
+			text[STOPPED_MODE]="STOPPED";
+			textFill[STOPPED_MODE]=Color.WHITE;
+			textSize[STOPPED_MODE]=5.5f;
+			
+			shape[NOTSTOPPED_MODE]=new Ellipse2D.Float(0,0,res,res);
+			stroke[NOTSTOPPED_MODE]=new BasicStroke(res/30);
+			fill[NOTSTOPPED_MODE]=Color.GREEN;
+			line[NOTSTOPPED_MODE]=Color.BLACK;
+			text[NOTSTOPPED_MODE]="RUNNING";
+			textFill[NOTSTOPPED_MODE]=Color.BLACK;
+			textSize[NOTSTOPPED_MODE]=5.5f;
+		}
+			
 		shape[DISABLED_MODE]=new Rectangle2D.Float(res/8,res/8,res*3/4,res*3/4);
 		stroke[DISABLED_MODE]=new BasicStroke(0);
 		fill[DISABLED_MODE]=null;
@@ -86,6 +112,14 @@
 		enableEvents(AWTEvent.MOUSE_EVENT_MASK);
 	}
 
+	protected Dimension dim;
+	public void setMyDim(Dimension d) { dim=d; }
+	public Dimension getMyDim() { return dim; }
+	
+	public Dimension getPreferredSize() { return (dim==null) ? super.getPreferredSize() : dim; }
+	public Dimension getMinimumSize() { return (dim==null) ? super.getPreferredSize() : dim; }
+	public Dimension getMaximumSize() { return (dim==null) ? super.getPreferredSize() : dim; }
+
 	protected Shape makeStopSign() {
 		int x[] = new int[10];
 		int y[] = new int[10];
@@ -163,7 +197,7 @@
 		int h=getHeight();
 		int cons=w>h?h:w;
 		int ex=(w>h?w:h)-cons;
-		double scale=cons/(double)(res+stroke[mode].getLineWidth());
+		double scale=(cons-1)/(double)(res+stroke[mode].getLineWidth());
 		if(w>h)
 			g.translate(ex/2.0,0);
 		else
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EllipseShapeInfo.java ./tools/mon/org/tekkotsu/mon/EllipseShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/EllipseShapeInfo.java	Thu Apr 22 18:46:02 2004
+++ ./tools/mon/org/tekkotsu/mon/EllipseShapeInfo.java	Wed Dec 31 19:00:00 1969
@@ -1,53 +0,0 @@
-package org.tekkotsu.mon;
-
-import java.awt.Graphics2D;
-import javax.swing.Icon;
-import javax.swing.ImageIcon;
-
-// stores info for a EllipseShape
-// note that ellipse center is same as centroid
-public class EllipseShapeInfo extends ShapeInfo {
-	static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/ellipse.png");
-	float semimajor, semiminor; // length of semimajor axes
-	float orientation; // orientation of principal axis
-
-	public EllipseShapeInfo(int _id, int _parentId, String _name, int _color,
-			float _centroidx, float _centroidy, float _centroidz,
-			float _semimajor, float _semiminor,
-			float _orientation) {
-		super(_id, _parentId, _name, _color, _centroidx, _centroidy, _centroidz);
-		semimajor = _semimajor;
-		semiminor = _semiminor;
-		orientation = _orientation;
-	}
-
-	// returns left-most coordinate of object
-	public float getLeft() { return centroidx-semimajor; }
-	// returns right-most coordinate of object
-	public float getRight() { return centroidx+semimajor; }
-	// returns top-most coordinate of object
-	public float getTop() { return centroidy-semiminor; }
-	// returns bottom-most coordinate of object
-	public float getBottom() { return centroidy+semiminor; }
-
-
-	public String toString() {
-		return (super.toString() + "(semimajor " + semimajor 
-			+ ", semiminor " + semiminor 
-			+ ", orientation " + orientation + ")");
-	}
-
-	public Icon getIcon() { return icon; }
-
-	// rough rendering which doesn't take orientation into account
-	public void renderTo(Graphics2D graphics) {
-		// maybe do a hack-ish check if abs(orientation) more than pi/4?
-		graphics.drawOval((int)(getCentroidX()-semimajor+1), 
-			(int)(getCentroidY()-semiminor+1),
-			(int)(semimajor*2), (int)(semiminor*2));
-	}
-
-	public float getSemiMajor() { return semimajor; }
-	public float getSemiMinor() { return semiminor; }
-	public float getOrientation() { return orientation; }
-}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/HeadPointListener.java ./tools/mon/org/tekkotsu/mon/HeadPointListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/HeadPointListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/HeadPointListener.java	Wed Jun 22 16:06:17 2005
@@ -28,7 +28,7 @@
 		public void headPointUpdated(HeadPointListener mc);
 	}
 
-	void addHeadPointUpdatedListener(HeadPointUpdatedListener mcl) { listeners.add(mcl); }
+	void addHeadPointUpdatedListener(HeadPointUpdatedListener mcl) { listeners.add(mcl); needConnection(); }
 	void removeHeadPointUpdatedListener(HeadPointUpdatedListener mcl) { listeners.remove(mcl); }
 	void fireHeadPointUpdated() {
 		for(int i=0;i<listeners.size();i++)
@@ -38,10 +38,12 @@
   // Connect to control socket
   public void connected(Socket socket) {
     mysock = socket;
-		fireHeadPointUpdated();
     try {
+			mysock.setTcpNoDelay(true);
+			mysock.setTrafficClass(0x10);
       out = mysock.getOutputStream();
 			InputStream sin=socket.getInputStream();
+			fireHeadPointUpdated();
 			fireConnected();
 			while (true) { //not that we expect input, but will block until the socket is closed
 				String msgtype=readLine(sin);
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/LineShapeInfo.java ./tools/mon/org/tekkotsu/mon/LineShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/LineShapeInfo.java	Thu Apr 22 18:46:02 2004
+++ ./tools/mon/org/tekkotsu/mon/LineShapeInfo.java	Wed Dec 31 19:00:00 1969
@@ -1,65 +0,0 @@
-package org.tekkotsu.mon;
-
-import java.awt.Graphics2D;
-import javax.swing.Icon;
-import javax.swing.ImageIcon;
-
-// stores info for a LineShape
-public class LineShapeInfo extends ShapeInfo {
-	static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/line.png");
-	// x/y coordinates of endpoints, with variances
-	float e1x, e1y, e1v;
-	float e2x, e2y, e2v;
-	float r, theta;
-
-	public LineShapeInfo(int _id, int _parentId, String _name, int _color,
-			float _centroidx, float _centroidy, float _centroidz,
-			float _e1x, float _e1y, float _e1v, 
-			float _e2x, float _e2y, float _e2v,
-			float _r, float _theta) {
-		
-		super(_id, _parentId, _name, _color, _centroidx, _centroidy, _centroidz);
-		e1x = _e1x;
-		e1y = _e1y;
-		e1v = _e1v;
-		e2x = _e2x;
-		e2y = _e2y;
-		e2v = _e2v;
-		r = _r;
-		theta = _theta;
-	}
-	
-	// returns left-most coordinate of object
-	public float getLeft() { return java.lang.Math.min(e1x,e2x); }
-	// returns right-most coordinate of object
-	public float getRight() { return java.lang.Math.max(e1x,e2x); }
-	// returns top-most coordinate of object
-	public float getTop() { return java.lang.Math.min(e1y,e2y); }
-	// returns bottom-most coordinate of object
-	public float getBottom() { return java.lang.Math.max(e1y,e2y); }
-
-	public String toString() {
-		return (super.toString() 
-				+ "(e1x " +e1x + ", e1y " + e1y + ", e1v " + e1v 
-				+ ", e2x " +e2x + ", e2y " + e2y + ", e2v " + e2v 
-				+ ", r " + r + ", theta " + theta + ")");
-	}
-
-	public Icon getIcon() { return icon; }
-
-	public void renderTo(Graphics2D graphics) {
-		graphics.drawLine((int)e1x,(int)e1y,(int)e2x,(int)e2y);
-		// draw circles for variance
-		graphics.drawOval((int)e1x,(int)e1y,(int)(e1v/2),(int)(e1v/2));
-		graphics.drawOval((int)e2x,(int)e2y,(int)(e2v/2),(int)(e2v/2));
-	}
-
-	public float getE1X() { return e1x; }
-	public float getE1Y() { return e1y; }
-	public float getE1V() { return e1v; }
-	public float getE2X() { return e2x; }
-	public float getE2Y() { return e2y; }
-	public float getE2V() { return e2v; }
-	public float getR() { return r; }
-	public float getTheta() { return theta; }
-}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/Listener.java ./tools/mon/org/tekkotsu/mon/Listener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/Listener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/Listener.java	Fri Aug  5 15:44:23 2005
@@ -47,6 +47,7 @@
 		listeners.add(listener);
 		cachedListeners = 
 			(ConnectionListener[]) listeners.toArray(EMPTY_LISTENER_ARRAY);
+		needConnection();
 	}
 	
 	/**
@@ -126,15 +127,19 @@
 		_isServer=false;
 		_host=host;
 		_port=port;
-		startThread();
+		//spawning threads in the constructor (or functions called from the constructor) is a bad idea:
+		//startThread(); // don't do it!
 	}
 
+	public void needConnection() {
+		if(_listenerThread==null)
+			startThread();
+	}
 	public void startThread() {
 		destroy=false;
 		_listenerThread=new Thread(this);
 		_listenerThread.start();
 	}
-
 	public void run() {
 		if (_port >= 0) {
 			if (_isServer)
@@ -152,6 +157,7 @@
 		if(_listenerThread!=null)
 			_listenerThread.interrupt();
 		close();
+		_listenerThread=null;
 	}
 
 	public void frameTimer() {
@@ -315,6 +321,13 @@
 	public int b2i(byte b) { return (b>=0)?(int)b:((int)b)+256; }
 	public long b2l(byte b) { return (b>=0)?(long)b:((long)b)+256; }
 
+    //Convert a 4 byte int, located in an array with a given offset to an integer.
+    public int byteToInt(byte[] buf, int offset) {
+    return (b2i(buf[offset+3])<<24) | (b2i(buf[offset+2])<<16) |
+           (b2i(buf[offset+1])<< 8) | b2i(buf[offset]);
+    }
+
+    
 	protected abstract void runServer();
 	protected abstract void runConnect();
 	public abstract void close();
@@ -345,3 +358,5 @@
   public static final int PACKET_WORLDSTATEBUTTONS=13;
   public static final int PACKET_WMCLASS=14;
 }
+
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/MechaController.java ./tools/mon/org/tekkotsu/mon/MechaController.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/MechaController.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/MechaController.java	Wed Jun  8 17:05:01 2005
@@ -29,7 +29,7 @@
 		public void mechaUpdated(MechaController mc);
 	}
 
-	void addMechaUpdatedListener(MechaUpdatedListener mcl) { listeners.add(mcl); }
+	void addMechaUpdatedListener(MechaUpdatedListener mcl) { listeners.add(mcl); needConnection(); }
 	void removeMechaUpdatedListener(MechaUpdatedListener mcl) { listeners.remove(mcl); }
 	void fireMechaUpdated() {
 		for(int i=0;i<listeners.size();i++)
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/MicrophoneClient.java ./tools/mon/org/tekkotsu/mon/MicrophoneClient.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/MicrophoneClient.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/MicrophoneClient.java	Wed Jun  8 17:05:01 2005
@@ -52,6 +52,7 @@
     audioListeners.add(listener);
     cachedAudioListeners =
       (AudioListener[]) audioListeners.toArray(EMPTY_AUDIO_LISTENER_ARRAY);
+	needConnection(); 
   }
   
   /**
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ParamListener.java ./tools/mon/org/tekkotsu/mon/ParamListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ParamListener.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/ParamListener.java	Wed Jun  8 17:05:01 2005
@@ -0,0 +1,227 @@
+package org.tekkotsu.mon;
+
+// Send/receive named parameters between TekkotsuMon to the AIBO.
+import java.lang.Integer;
+import java.lang.String;
+import java.lang.System;
+import java.io.PrintStream;
+import java.io.InputStream;
+import java.net.Socket;
+import javax.swing.Timer;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.Vector;
+import java.net.SocketException;
+import org.xml.sax.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.helpers.DefaultHandler;
+import org.xml.sax.helpers.XMLReaderFactory;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Set;
+import java.util.Iterator;
+
+// Does communication with the robot
+public class ParamListener extends TCPListener implements ActionListener {
+  // The command output stream
+  PrintStream out;
+  Socket mysock;
+	Vector listeners=new Vector();
+	static DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
+	static DocumentBuilder db;
+	static TransformerFactory transf = TransformerFactory.newInstance();
+	static Transformer trans;
+		
+	static int defPort=10055;
+	
+	public interface CommListener {
+		public void commUpdated(ParamListener mc);
+	}
+
+	void addCommListener(CommListener mcl) { listeners.add(mcl); needConnection(); }
+	void removeCommListener(CommListener mcl) { listeners.remove(mcl); }
+	void fireCommUpdated() {
+		for(int i=0;i<listeners.size();i++)
+			((CommListener)listeners.get(i)).commUpdated(this);
+	}
+	
+	public class IncomingParser extends DefaultHandler {
+		ParamListener parent;
+		HashMap params = new HashMap();
+		boolean updating=false;
+		IncomingParser(ParamListener p) {
+			super();
+			parent=p;
+		}
+		public void startElement(String namespace, String localname, String qName, Attributes attr) throws SAXException{
+			if(localname.equals("param")) {
+				String name=attr.getValue("","name");
+				String value=attr.getValue("","value");
+				if(name==null || value==null)
+					throw new SAXException("bad parameter update command - missing name or value");
+				synchronized(params) {
+					params.put(name,value);
+				}
+			} else if(localname.equals("refresh")) {
+				parent.actionPerformed(null);
+			} else if(localname.equals("update")) {
+				synchronized(params) {
+					updating=true;
+				}
+			} else if(localname.equals("connection")) {
+			} else {
+				System.out.println("Warning: unknown element "+localname);
+			}
+		}
+		public void endElement(String namespace, String localname, String qName) {
+			if(localname.equals("param")) {
+				if(!updating)
+					parent.fireCommUpdated();
+			} else if(localname.equals("update")) {
+				synchronized(params) {
+					updating=false;
+					params.notifyAll();
+				}
+				parent.fireCommUpdated();
+			}
+		}
+	}
+	IncomingParser parser=new IncomingParser(this);
+
+	public String getParam(String name) {
+		synchronized(parser.params) {
+			return (String)parser.params.get(name);
+		}
+	}
+
+	public Set getParams() {
+		synchronized(parser.params) {
+			return parser.params.keySet();
+		}
+	}
+
+  // Connect to control socket
+  public void connected(Socket socket) {
+    mysock = socket;
+		fireCommUpdated();
+    try {
+      out = new PrintStream(mysock.getOutputStream());
+			out.println("<connection>");
+			InputStream sin=socket.getInputStream();
+			fireConnected();
+			XMLReader myReader = XMLReaderFactory.createXMLReader();
+			myReader.setContentHandler(parser);
+			myReader.parse(new InputSource(sin));
+    } catch(SocketException e) {
+    } catch(Exception e) {
+      e.printStackTrace();
+    } finally {
+      fireDisconnected();
+    }
+
+		try { socket.close(); } catch (Exception ex) { }
+
+		_isConnected=false;
+		fireCommUpdated();
+		//The sleep is to get around the socket still listening after being closed thing
+		if(!destroy)
+			System.out.println("ParamListener - connection closed... reconnect after 5 seconds");
+		try { Thread.sleep(5000); } catch (Exception ex) {}
+  }
+
+  // Disconnect from control socket
+  public void close() {
+		if(out!=null)
+			out.println("</connection>");
+		//    try { mysock.close(); } catch(Exception e) {}
+    //_isConnected = false;
+    super.close();
+		//we'll fire an event to the listeners when the readLine in connected finally fails
+  }
+
+	public void actionPerformed(ActionEvent e) {
+		if(!_isConnected || out==null)
+			return;
+		try {
+			while(true) {
+				if(parser.updating)
+					parser.params.wait();
+				synchronized(parser.params) {
+					if(parser.updating)
+						continue;
+					Document doc=db.newDocument();
+					Element root=doc.createElement("update");
+					doc.appendChild(root);
+					Set entries=parser.params.entrySet();
+					for(Iterator it=entries.iterator();it.hasNext();) {
+						Map.Entry ent=(Map.Entry)it.next();
+						Element elm=doc.createElement("param");
+						elm.setAttribute("name",(String)ent.getKey());
+						elm.setAttribute("value",(String)ent.getValue());
+						root.appendChild(elm);
+					}
+					trans.transform(new DOMSource(doc),new StreamResult(out));
+					out.print("\n");
+					break;
+				}
+			}
+		} catch(Exception ex) {
+			System.err.println("Dropped action event");
+			ex.printStackTrace();
+		}
+	}
+
+  // Send a headPoint command
+  public void setParam(String command, String value) {
+		synchronized(parser.params) {
+			parser.params.put(command,value);
+		}
+    if (out == null)
+      return;
+    try {
+			Document doc=db.newDocument();
+			Element elm=doc.createElement("param");
+			elm.setAttribute("name",command);
+			elm.setAttribute("value",value);
+			doc.appendChild(elm);
+			trans.transform(new DOMSource(doc),new StreamResult(out));
+			out.print("\n");
+    } catch(Exception e) { close(); return; }
+  }
+
+  // Some state inquiry functions
+  public boolean hasData() { return false; }
+  public boolean isConnected() { return _isConnected; }
+
+  // Constructors
+  public ParamListener() { super(); init(); }
+  public ParamListener(int port) { super(port); init(); }
+  public ParamListener(String host, int port) { super(host, port); init(); }
+	void init() {
+		try {
+			db = dbf.newDocumentBuilder();
+			trans = transf.newTransformer();
+			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
+    } catch(Exception e) { e.printStackTrace(); }
+	}
+
+	static public void main(String s[]) {
+		int port=defPort;
+		if(s.length<1)
+			usage();
+		if(s.length>1)
+			port=Integer.parseInt(s[1]);
+		ParamListener l=new ParamListener(s[0],port);
+	}
+	
+	public static void usage() {
+		System.out.println("Usage: java ParamListener host [port]");
+		System.out.println("       if port is not specified, it defaults to: "+defPort);
+		System.exit(2);
+	}
+}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ShapeInfo.java ./tools/mon/org/tekkotsu/mon/ShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/ShapeInfo.java	Thu Apr 15 20:39:28 2004
+++ ./tools/mon/org/tekkotsu/mon/ShapeInfo.java	Wed Dec 31 19:00:00 1969
@@ -1,35 +0,0 @@
-package org.tekkotsu.mon;
-
-import java.awt.Graphics2D;
-
-// stores info for a Shape, to use as UserObject for DefaultMutableTreeNode
-public class ShapeInfo extends VisualObjectInfo {
-	float centroidx, centroidy, centroidz;
-	int color; // the color index of this object
-
-	public ShapeInfo(int _id, int _parentId, String _name, int _color,
-			float _centroidx, float _centroidy, float _centroidz) {
-		super(_id, _parentId, _name);
-		centroidx = _centroidx;
-		centroidy = _centroidy;
-		centroidz = _centroidz;
-		color = _color;
-	}
-
-	public String toString() {
-		return (super.toString() + "(color " + color + ",cx " + centroidx + ", cy " + centroidy
-			+ ", cz " + centroidz + ")");
-	}
-
-	// if no specific renderer defined, just plot a point at centroid
-	public void renderTo(Graphics2D graphics) {
-//		graphics.setColor()
-		graphics.drawOval((int)centroidx,(int)centroidy,5,5);
-	}
-
-	public float getCentroidX() { return centroidx; }
-	public float getCentroidY() { return centroidy; }
-	public float getCentroidZ() { return centroidz; }
-	public int getColor() { return color; }
-}
-
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/SketchGUI.java ./tools/mon/org/tekkotsu/mon/SketchGUI.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/SketchGUI.java	Fri Jan 21 18:31:39 2005
+++ ./tools/mon/org/tekkotsu/mon/SketchGUI.java	Wed Dec 31 19:00:00 1969
@@ -1,731 +0,0 @@
-package org.tekkotsu.mon;
-
-import java.awt.event.*;
-import javax.swing.*;
-import javax.swing.tree.*;
-import javax.swing.event.*;
-import java.lang.String;
-//import java.util.LinkedList;
-import java.awt.*;
-import javax.imageio.ImageIO;
-import java.awt.geom.AffineTransform;
-import java.awt.image.BufferedImage;
-import java.awt.image.IndexColorModel;
-import java.util.Date;
-import java.util.Vector;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.Comparator;
-import java.io.PrintWriter;
-import java.io.FileOutputStream;
-import java.util.prefs.Preferences;
-import java.io.File;
-import java.net.*;
-import java.io.*;
-import java.util.StringTokenizer;
-
-public class SketchGUI extends JFrame implements ActionListener,TreeSelectionListener,VisionUpdatedListener {
-	boolean isCam; // true if this GUI is displaying a camera space (not world)
-
-	JFrame sketchFrame;
-    SketchPanel sketchPanel;
-//    JButton spawnBut;
-    JButton refreshBut;
-    JButton saveImageBut;
-	JButton refreshListBut;
-    JTree sketchTree;
-	DefaultMutableTreeNode root; //= new DefaultMutableTreeNode("camspace");
-    JLabel status;
-    float mspf=0;
-    float mspfGamma=.9f;
-    String state="";
-    String host;
-    int listingPort;
-	int sketchPort;
-//    static int defListPort = 5800; // Default Port
- //   static int defSketchPort = 5801; // Default Port
-    static Preferences prefs = Preferences.userNodeForPackage(SketchGUI.class);
-	// the socket over which listings are retrieved and Sketch commands are sent
-	Socket listingSocket=null;
-	PrintWriter netout = null; // network output
-	BufferedReader netin = null; // network input
-
-    public static void main(String args[]) {
-	if(args.length<4)
-	     usage();
-
-    //listingPort=Integer.parseInt(args[2]);
-	int _listingPort = Integer.parseInt(args[2]);
-	int _sketchPort = Integer.parseInt(args[3]);
- //   sketchPort=Integer.parseInt(args[3]);
-
-	boolean _isCam = args[1].equals("cam");
-	SketchGUI gui = new SketchGUI(args[0], _listingPort, _sketchPort, _isCam);
-//	gui.listingPort = _listingPort;
-//	gui.sketchPort = Integer.parseInt(args[3]);
-	gui.addWindowListener(new WindowAdapter() {
-		 public void windowClosing(WindowEvent e) {System.exit(0);}});
-	gui.setVisible(true);
-    }
-		
-    public static void usage() {
-	System.out.println("Usage: java org/tekkotsu/mon/SketchGUI host [cam/world] listport sketchport");
-//	System.out.println("       if port is not specified, it defaults to: [12345]"); // Default port
-	System.exit(2);
-    }
-			
-    public void actionPerformed(ActionEvent e) {
-//	if(e.getActionCommand().compareTo("spawn")==0) {
-//	    SketchGUI gui = new SketchGUI(host,port);
-//	    gui.addWindowListener(new WindowAdapter() {
-//		     public void windowClosing(WindowEvent e) {
-//		     }});
-//	    gui.setVisible(true);
-	if(e.getActionCommand().compareTo("refresh")==0) {
-		// reset bounds
-		sketchPanel.leftBound = 0;
-		sketchPanel.rightBound = 176;
-		sketchPanel.topBound = 0;
-		sketchPanel.bottomBound = 144;
-/*		Enumeration nodes = root.breadthFirstEnumeration();
-		nodes.nextElement(); //skip the root
-		while (nodes.hasMoreElements()) {
-			VisualObjectInfo oinfo = (VisualObjectInfo)(((DefaultMutableTreeNode)(nodes.nextElement())).getUserObject());
-			sketchPanel.scaleToVisualObject(oinfo);
-		}*/
-
-		TreePath[] paths = sketchTree.getSelectionPaths();
-		if(paths!=null) {
-			for (int path_i = 0; path_i < paths.length; path_i++) {
-				DefaultMutableTreeNode node 
-					=(DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
-				
-				if (node == root) continue;
-				if(!(node.getUserObject() instanceof VisualObjectInfo)) {
-					System.out.println("placeholder text can't be selected");
-					continue;
-				}
-				
-				VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
-				sketchPanel.scaleToVisualObject(vinfo);
-			}
-		}
-
-		//Graphics2D g = sketchPanel._image.createGraphics();
-		//g.setBackground(Color.GRAY);
-		//g..clearRect(0,0,sketchPanel._image.getWidth(),sketchPanel._image.getHeight());
-		//sketchPanel.repaint();
-		//valueChanged(null); // redraw
-		//sketchPanel.repaint();
-		valueChanged(null); // redraw
-	} else if(e.getActionCommand().compareTo("saveimg")==0) {
-	    File cursavepath = new File(prefs.get("cursavepath",""));
-	    JFileChooser dia=new JFileChooser(cursavepath);
-	    dia.setDialogTitle("Save Image...");
-	    Component cur=this;
-	    while(cur.getParent()!=null)
-		 cur=cur.getParent();
-	    if(dia.showSaveDialog(cur)==JFileChooser.APPROVE_OPTION) {
-		prefs.put("cursavepath",dia.getCurrentDirectory().getPath());
-		String base=dia.getSelectedFile().getName();
-		String format;
-		if(base.lastIndexOf('.')==-1) {
-		    format="png";
-		} else {
-		    int i=base.lastIndexOf(".");
-		    format=base.substring(i+1);
-		    base=base.substring(0,i);
-		}
-		try {
-			FileOutputStream fileout=new FileOutputStream(dia.getSelectedFile().getParent()+File.separator+base+"."+format);
-			ImageIO.write(sketchPanel.getListener().getImage(),format,fileout);
-		} catch(Exception ex) {}
-	    }
-	} else if(e.getActionCommand().compareTo("refreshlist")==0) {
-		// send command to refresh the sketch tree list
-		if(netout==null)
-			reconnect();
-		if(netout==null)
-			return;
-
-		netout.println("list");
-//		DefaultMutableTreeNode root = new DefaultMutableTreeNode("camspace");
-		root.removeAllChildren();
-		// read in new sketch listing
-		try {
-			// reset bounds
-			sketchPanel.leftBound = 0;
-			sketchPanel.rightBound = 176;
-			sketchPanel.topBound = 0;
-			sketchPanel.bottomBound = 144;
-
-			String inputLine;
-			System.out.println(inputLine = readLine());
-			while((inputLine=readLine()).compareTo("list end") != 0) {
-				// parse type (sketch or shape)	
-				StringTokenizer st = new StringTokenizer(inputLine,": ");
-				String type = st.nextToken();
-
-				// parse id
-				inputLine = readLine();
-				st = new StringTokenizer(inputLine,": ");
-				st.nextToken();
-				int id = Integer.parseInt(st.nextToken());
-				
-				//parse parentId
-				inputLine = readLine();
-				st = new StringTokenizer(inputLine,": ");
-				st.nextToken();
-				int parentId = Integer.parseInt(st.nextToken());
-			
-				// parse name
-				inputLine = readLine();
-				st = new StringTokenizer(inputLine,":\r\n");
-				st.nextToken();
-				String name = st.nextToken();
-
-				// create node
-				System.out.println(type + " id:"+id+"parentId:"+parentId+"name:"+name);
-				VisualObjectInfo oinfo;
-				if(type.equals("sketch")) {
-					oinfo = new SketchInfo(id, parentId, name);
-				} else if (type.equals("shape")) {
-					inputLine = readLine();
-					st = new StringTokenizer(inputLine,": ");
-					st.nextToken();
-					int shapetype = Integer.parseInt(st.nextToken());
-					System.out.println("shapetype:" + shapetype);
-
-					// parse shape color
-					inputLine = readLine();
-					st = new StringTokenizer(inputLine,": ");
-					st.nextToken();
-					int color = Integer.parseInt(st.nextToken());
-					System.out.println("color:" + color);
-
-					inputLine = readLine();
-					st = new StringTokenizer(inputLine,": ");
-					st.nextToken();
-					float cx = Float.parseFloat(st.nextToken());
-					float cy = Float.parseFloat(st.nextToken());
-					float cz = Float.parseFloat(st.nextToken());
-					System.out.println("cxyz:" +cx+" "+cy+" "+cz);
-
-					if(shapetype == 1) { // lineshape
-						inputLine = readLine();
-						st = new StringTokenizer(inputLine,": ");
-						st.nextToken();
-						float e1x = Float.parseFloat(st.nextToken());
-						float e1y = Float.parseFloat(st.nextToken());
-						float e1v = Float.parseFloat(st.nextToken());
-						System.out.println("e1xyv:"+e1x+" "+e1y +" "+e1v);
-
-						inputLine = readLine();
-						st = new StringTokenizer(inputLine,": ");
-						st.nextToken();
-						float e2x = Float.parseFloat(st.nextToken());
-						float e2y = Float.parseFloat(st.nextToken());
-						float e2v = Float.parseFloat(st.nextToken());
-						System.out.println("e1xyv:"+e1x+" "+e1y +" "+e1v);
-
-						inputLine = readLine();
-						st = new StringTokenizer(inputLine,": ");
-						st.nextToken();
-						float r = Float.parseFloat(st.nextToken());
-						System.out.println("r:"+r);
-
-						inputLine = readLine();
-						st = new StringTokenizer(inputLine,": ");
-						st.nextToken();
-						float theta = Float.parseFloat(st.nextToken());
-						System.out.println("theta:"+theta);
-
-						oinfo = new LineShapeInfo(id, parentId, name, color,
-							cx,cy,cz, e1x, e1y, e1v, e2x, e2y, e2v, r, theta);
-
-					} else if(shapetype == 2) { // ellipseshape
-						inputLine = readLine();
-						st = new StringTokenizer(inputLine,": ");
-						st.nextToken();
-						float semimajor = Float.parseFloat(st.nextToken());
-						float semiminor = Float.parseFloat(st.nextToken());
-						System.out.println("axes:"+semimajor+" "+semiminor);
-
-						inputLine = readLine();
-						st = new StringTokenizer(inputLine,": ");
-						st.nextToken();
-						float orientation = Float.parseFloat(st.nextToken());
-						System.out.println("orientation:"+orientation);
-
-						oinfo = new EllipseShapeInfo(id,parentId,name,color,
-								cx,cy,cz, semimajor, semiminor, orientation);
-
-					} else if (shapetype == 4) { // agentshape
-						inputLine = readLine();
-						st = new StringTokenizer(inputLine,": ");
-						st.nextToken();
-						float orientation = Float.parseFloat(st.nextToken());
-						System.out.println("orientation:"+orientation);
-
-						oinfo = new AgentShapeInfo(id,parentId, name, color,
-								cx,cy,cz, orientation);
-					} else {
-						System.out.println("Invalid shape!");
-						oinfo = new ShapeInfo(id, parentId, name, color,
-								cx,cy,cz);
-					}
-				} else {
-					System.out.println("Invalid type!");
-					oinfo = new VisualObjectInfo(id, parentId, name);
-				}
-	
-				if(!isCam)
-					sketchPanel.scaleToVisualObject(oinfo);
-
-				DefaultMutableTreeNode newnode = new DefaultMutableTreeNode(oinfo);
-				root.add(newnode);
-
-
-				sketchTree.updateUI();
-				
-			}
-			// pair up nodes with parents, quite inefficiently (?)
-//			Enumeration nodes = root.preorderEnumeration();
-//			while(nodes.hasMoreElements()) {
-//				SketchInfo cur = (SketchInfo)(nodes.nextElement());
-//				while(nodes.hasMoreElements()) {
-//					
-//				}
-//			}
-			// pair children with parents
-			DefaultMutableTreeNode curNode = root;
-			while((curNode = curNode.getNextNode()) != null) {
-				DefaultMutableTreeNode potentialParent = root;
-				while((potentialParent = potentialParent.getNextNode()) != null) {
-					if(((VisualObjectInfo)(curNode.getUserObject())).parentId == ((VisualObjectInfo)(potentialParent.getUserObject())).id && !potentialParent.isNodeAncestor(curNode)) {
-						potentialParent.add(curNode);
-					}
-				}
-
-			}
-			sortTree(root);		
-
-			// display the first sketch
-			SketchInfo firstinfo = (SketchInfo)(((DefaultMutableTreeNode)(root.getFirstChild())).getUserObject());
-			netout.println("get "+firstinfo.getId());
-			while((inputLine=readLine()).compareTo("get end") != 0) {
-				System.out.println(inputLine);
-			}	
-			//netout.println("get "+firstinfo.getId()); // why a 2nd time?
-			//while((inputLine=readLine()).compareTo("get end") != 0) {
-			//System.out.println(inputLine);
-			//}
-
-
-			System.out.println(inputLine);
-			//sketchTree = new JTree(root); // is this right?
-			//JScrollPane treeView = new JScrollPane(sketchTree);
-//			sketchTree.removeAll();
-//			sketchTree.add(root);
-			// expand all the rows
-			for (int i = 0; i < sketchTree.getRowCount(); i++) {
-				sketchTree.expandRow(i);
-//			sketchTree.updateUI();
-			}
-			sketchTree.clearSelection();
-			sketchTree.updateUI();
-		} catch(IOException ioe) {
-			System.err.println("Transfer error");
-			reconnect();
-			actionPerformed(e);
-		}
-	}
-    }
-
-	public SketchGUI(String host, int _listingPort, int _sketchPort, 
-									 boolean _isCam) {
-		super();
-		this.host = host;
-		this.listingPort = _listingPort;
-		this.sketchPort = _sketchPort;
-		this.isCam = _isCam;
-		//this.port = port;
-		
-		if(isCam)
-			root = new DefaultMutableTreeNode("camspace");
-		else root = new DefaultMutableTreeNode("worldspace");
-
-		init();
-
-		// network setup
-		reconnect();
-		/*
-			try {
-			System.out.println("Trying to open socket...");
-			listingSocket = new Socket(host,listingPort);
-			netout = new PrintWriter(listingSocket.getOutputStream(), true);
-			netin = new BufferedReader(new InputStreamReader(listingSocket.getInputStream()));
-			} catch (UnknownHostException e) {
-			System.err.println("Don't know about host:"+host);
-			System.exit(1);
-			} catch (IOException e) {
-			System.err.println("Couldn't get I/O for "
-			+ "the connection to:" + host + ".");
-			//System.exit(1);
-			}*/
-	}
-	
-	
-
-    public void init() {
-			//enableEvents(AWTEvent.FOCUS_EVENT_MASK);// want to receive FocusEvents
-
-	int strutsize=10;
-	int sepsize=5;
-	getContentPane().setLayout(new BorderLayout());
-	getContentPane().add(Box.createVerticalStrut(strutsize),BorderLayout.NORTH);
-	getContentPane().add(Box.createHorizontalStrut(strutsize),BorderLayout.WEST);
-	getContentPane().add(Box.createHorizontalStrut(strutsize),BorderLayout.EAST);
-		
-	setTitle("TekkotsuMon: Sketch/Shape Listing");
-	sketchPanel=new SketchPanel(this, new TCPVisionListener(host, sketchPort), 
-			isCam);
-	sketchPanel.setMinimumSize(new Dimension(VisionListener.DEFAULT_WIDTH/2, VisionListener.DEFAULT_HEIGHT/2));
-	sketchPanel.setPreferredSize(new Dimension(VisionListener.DEFAULT_WIDTH*2, VisionListener.DEFAULT_HEIGHT*2));
-	sketchPanel.setLockAspectRatio(true);
-
-	//getContentPane().add(sketch,BorderLayout.NORTH);
-
-	// stuff specific to putting SketchPanel in new frame
-	if (isCam)
-		sketchFrame = new JFrame("Cam Sketch/Shape Frame");
-	else sketchFrame = new JFrame("World Sketch/Shape Frame");
-	sketchFrame.getContentPane().add(sketchPanel);
-	sketchFrame.pack();
-	sketchFrame.setLocation(prefs.getInt("SketchPanel.location.x",50),prefs.getInt("SketchPanel.location.y",50));
-
-	sketchFrame.setVisible(true);
-
-	{
-
-	    Box tmp1 = Box.createHorizontalBox();
-	    tmp1.add(Box.createHorizontalStrut(strutsize));
-	    {
-		Box tmp2 = Box.createVerticalBox();
-
-		tmp2.add(Box.createVerticalStrut(strutsize));
-
-		{
-		    Box tmp3 = Box.createHorizontalBox();
-		    tmp3.add(status=new JLabel(state));
-		    tmp3.add(Box.createHorizontalGlue());
-
-		    tmp3.add(Box.createHorizontalStrut(strutsize));
-		
-		    refreshBut = new JButton("Refresh/Scale to Image");
-		    refreshBut.setAlignmentX(0.5f);
-		    refreshBut.addActionListener(this);
-		    refreshBut.setActionCommand("refresh");
-		    refreshBut.setEnabled(true);
-		    refreshBut.setToolTipText("Refreshes the displayed sketch;");
-		    tmp3.add(refreshBut);
-
-		    tmp3.add(Box.createHorizontalStrut(strutsize));
-		    
-		    saveImageBut = new JButton("Save Image");
-		    saveImageBut.setAlignmentX(0.5f);
-		    saveImageBut.addActionListener(this);
-		    saveImageBut.setActionCommand("saveimg");
-		    saveImageBut.setEnabled(true);
-		    saveImageBut.setToolTipText("Saves sketch to a file - use .jpg or .png extension to choose format;");
-		    tmp3.add(saveImageBut);
-			tmp3.add(Box.createHorizontalStrut(strutsize));
-
-
-			refreshListBut = new JButton("Refresh Listing");
-			refreshListBut.setAlignmentX(0.5f);
-			refreshListBut.addActionListener(this);
-			refreshListBut.setActionCommand("refreshlist");
-			refreshListBut.setEnabled(true);
-			refreshListBut.setToolTipText("Refreshes the sketch listing;");
-			tmp3.add(refreshListBut);
-		    tmp2.add(tmp3, BorderLayout.CENTER);
-		}
-
-		tmp2.add(Box.createVerticalStrut(strutsize));
-		// Sketch Tree:
-		sketchTree = new JTree(new DefaultTreeModel(initSketchTree(host, listingPort)));
-		tmp2.add(new JScrollPane(sketchTree));
-		// set up sketch node selection
-		sketchTree.getSelectionModel().setSelectionMode
-		            (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
-		//Listen for when the selection changes.
-	    sketchTree.addTreeSelectionListener(this);
-		sketchTree.setCellRenderer(new SketchTreeRenderer());
-
-//		JFrame sketchFrame = new JFrame("Sketches");
-//		sketchFrame.setSize(200,400);
-//		sketchFrame.getContentPane().add(new JScrollPane(sketchTree));
-//		JScrollPane sketchPane = new JScrollPane(sketchTree);
-//		sketchPane.setSize(200,100);
-//		tmp2.add(sketchPane);
-		tmp2.add(Box.createVerticalStrut(strutsize));
-		tmp2.add(new JSeparator());
-		tmp2.add(Box.createVerticalStrut(strutsize-sepsize));
-		{
-		    Box tmp4 = Box.createHorizontalBox();
-		    tmp4.add(status=new JLabel(state));
-		    tmp4.add(Box.createHorizontalGlue());
-		    tmp2.add(tmp4);
-		}
-		tmp2.add(Box.createVerticalStrut(strutsize));
-		tmp1.add(tmp2);
-	    }
-	    tmp1.add(Box.createHorizontalStrut(strutsize));
-	    getContentPane().add(tmp1,BorderLayout.CENTER);
-	}
-	pack();
-	
-	String name="SketchGUI"+".location";
-	setLocation(prefs.getInt(name+".x",50),prefs.getInt(name+".y",50));
-	addWindowListener(new CloseSketchGUIAdapter(this));
-
-	sketchPanel.getListener().addListener(this);
-	
-	// trigger some beginning events
-//	actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "refreshlist"));
-    }
-
-	class CloseSketchGUIAdapter extends WindowAdapter {
-		SketchGUI gui;
-		CloseSketchGUIAdapter(SketchGUI gui) {this.gui=gui;}
-		public void windowClosing(WindowEvent e) {
-			gui.close();
-		}
-	}
-	
-	public void close() {
-		try {
-			if(listingSocket!=null && !listingSocket.isClosed())
-				listingSocket.close();
-		} catch (IOException ioe) {
-			System.err.println("close failed:");
-			ioe.printStackTrace();
-		}
-		prefs.putInt("SketchGUI.location.x",getLocation().x);
-		prefs.putInt("SketchGUI.location.y",getLocation().y);
-		sketchPanel.getListener().removeListener(this);
-		Component p=sketchPanel;
-		while(p.getParent()!=null)
-			p=p.getParent();
-		if(p instanceof Window) {
-			Window w=(Window)p;
-			prefs.putInt("SketchPanel.location.x",w.getLocation().x);
-			prefs.putInt("SketchPanel.location.y",w.getLocation().y);
-			w.dispose();
-		} else
-			System.out.println("That's weird - root container isn't window");
-		dispose();
-	}
-
-    public TreeNode initSketchTree(String host, int port) {
-
-	// Just for demonstration:
-	DefaultMutableTreeNode cam = new DefaultMutableTreeNode("hit refresh");
-	root.insert(cam,0);
-
-	return root;
-    }
-
-	public void sortTree(DefaultMutableTreeNode curNode) {
-		// set up comparator
-		Comparator comp =
-			new Comparator() {
-				public int compare(Object o1, Object o2) {
-					return compare((DefaultMutableTreeNode) o1, (DefaultMutableTreeNode) o2);    
-				}
-				public int compare(DefaultMutableTreeNode n1, DefaultMutableTreeNode n2) {
-					Integer i1 = new Integer(((VisualObjectInfo)n1.getUserObject()).id);
-					Integer i2 = new Integer(((VisualObjectInfo)n2.getUserObject()).id);
-					return i1.compareTo(i2);
-				}
-			};
-
-		// sort the roots children
-		Object[] objs = new Object[curNode.getChildCount()];
-		Enumeration children = curNode.children();
-		for (int i=0;children.hasMoreElements();i++) {
-			DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
-			objs[i] = child;
-		}
-
-		Arrays.sort(objs, comp);
-		curNode.removeAllChildren();
-
-		// insert newly ordered children
-		for (int i=0;i<objs.length;i++) {
-			DefaultMutableTreeNode orderedNode = (DefaultMutableTreeNode) objs[i];
-			curNode.add(orderedNode);
-			if (!orderedNode.isLeaf()) {
-				sortTree(orderedNode);
-			}
-		}
-	}
-
-	// gets called when a Sketch selection is clicked
-	public void valueChanged(TreeSelectionEvent e) {
-		TreePath[] paths = sketchTree.getSelectionPaths();
-		if (paths == null) {
-			renderSelectedInTree(null);
-			return;
-		}
-		int sketches=0;
-		for (int path_i = 0; path_i < paths.length; path_i++) {
-			DefaultMutableTreeNode node 
-				=(DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
-
-			if (node == root) continue;	
-			if (node == null) {System.err.println("node is null???"); return; }
-	
-			if(!(node.getUserObject() instanceof VisualObjectInfo)) {
-				System.out.println("placeholder text can't be displayed");
-				continue;
-			}
-			
-			VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
-			if(vinfo instanceof SketchInfo)
-				sketches++;
-			if (!node.isRoot()) {
-				System.out.println("id clicked:"+vinfo.id);
-				netout.println("get "+vinfo.id);
-				try {
-					String inputLine;
-					while((inputLine=readLine()).compareTo("get end") != 0) {
-						System.out.println(inputLine);
-					}
-				} catch (IOException ioe) {
-					System.err.println("Transfer error");
-					reconnect();
-					valueChanged(null);
-				}
-				System.out.println("done with id:"+vinfo.id);
-			} else {
-				//displayURL(helpURL); 
-			}
-		}
-		if(sketches==0)
-			renderSelectedInTree(null);
-	}
-	
-	protected String readLine() throws java.io.IOException {
-		if(netin==null)
-			reconnect();
-		if(netin==null)
-			throw new java.io.IOException("no connection");
-		String ans=netin.readLine();
-		if(ans==null)
-			throw new java.io.IOException("lost connection");
-		return ans;
-	}
-	
-	public void reconnect() {
-		System.out.print(host+":"+listingPort+" reconnecting...");
-		try {
-			if(listingSocket!=null && !listingSocket.isClosed())
-				listingSocket.close();
-			netin=null;
-			netout=null;
-			listingSocket = new Socket(host,listingPort);
-			netout = new PrintWriter(listingSocket.getOutputStream(), true);
-			netin = new BufferedReader(new InputStreamReader(listingSocket.getInputStream()));
-		} catch (UnknownHostException e) {
-			System.err.println("Don't know about host:"+host);
-			System.exit(1);
-		} catch (IOException ioe) {
-			System.err.println("reconnection failed:");
-			//ioe.printStackTrace();
-			return;
-		}
-		System.out.println("done");
-		refreshListBut.doClick(); //auto refresh on reconnect
-	}
-
-	public void visionUpdated(VisionListener l) {
-		renderSelectedInTree(l.getImage().createGraphics());
-		l.removeListener(this);
-		l.fireVisionUpdate();
-		l.addListener(this);
-	}
-	
-	// called when the window receives focus
-	/*public void processFocusEvent(FocusEvent e) {
-		repaint(); // keeps window from getting overwritten; bit of a hack
-		}*/
-
-	// renders all the currently selected elements in the tree
-	public void renderSelectedInTree(Graphics2D g) {
-		if(g==null) {
-			g = sketchPanel._image.createGraphics();
-			g.setBackground(Color.GRAY);
-			g.clearRect(0,0,sketchPanel._image.getWidth(),sketchPanel._image.getHeight());
-		}
-		TreePath[] paths = sketchTree.getSelectionPaths();
-		if (paths == null) {
-			sketchPanel.repaint();
-			return;
-		}
-		for (int path_i = 0; path_i < paths.length; path_i++) {
-			DefaultMutableTreeNode node 
-				=(DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
-
-			if (node == root) continue;
-			if (node == null) return;
-			
-			if(!(node.getUserObject() instanceof VisualObjectInfo)) {
-				System.out.println("placeholder text can't be displayed");
-				continue;
-			}
-			
-			VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
-			int cval = vinfo.getColor();
-			IndexColorModel cmodel = sketchPanel._listener.getColorModel();
-			int rgb = cmodel.getRGB(cval);
-			Color color = new Color(cmodel.getRGB(cval));
-			g.setColor(new Color(cmodel.getRGB(vinfo.getColor())));
-
-			g.setTransform(sketchPanel.resultAtrans);
-			vinfo.renderTo(g);
-		}
-		sketchPanel.repaint();
-		//repaint(); // repaints this frame
-		//paintAll(); // repaints everything in this frame
-	}
-
-	private class SketchTreeRenderer extends DefaultTreeCellRenderer {
-		public SketchTreeRenderer(/*Icon icon*/) {
-//			tutorialIcon = icon;
-		}
-
-		public Component getTreeCellRendererComponent(
-				JTree tree,
-				Object value,
-				boolean sel,
-				boolean expanded,
-				boolean leaf,
-				int row,
-				boolean hasFocus) {
-			super.getTreeCellRendererComponent(
-					tree, value, sel,
-					expanded, leaf, row,
-					hasFocus);
-			try {
-			VisualObjectInfo vinfo = (VisualObjectInfo)(((DefaultMutableTreeNode)value).getUserObject());
-			
-			setIcon(vinfo.getIcon());
-			setToolTipText(vinfo.toString());
-			} catch (ClassCastException e) {}
-
-			return this;
-		}
-	}
-}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/SketchInfo.java ./tools/mon/org/tekkotsu/mon/SketchInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/SketchInfo.java	Thu Apr 22 18:46:02 2004
+++ ./tools/mon/org/tekkotsu/mon/SketchInfo.java	Wed Dec 31 19:00:00 1969
@@ -1,16 +0,0 @@
-package org.tekkotsu.mon;
-
-import javax.swing.Icon;
-import javax.swing.ImageIcon;
-
-// stores info for a Sketch, to use as UserObject for DefaultMutableTreeNode
-public class SketchInfo extends VisualObjectInfo {
-	static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/sketch.png");
-
-	public SketchInfo(int _id, int _parentId, String _name) {
-		super(_id, _parentId, _name);
-	}
-
-	public Icon getIcon() { return icon; }
-}
-
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/SketchPanel.java ./tools/mon/org/tekkotsu/mon/SketchPanel.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/SketchPanel.java	Wed Dec  1 18:18:30 2004
+++ ./tools/mon/org/tekkotsu/mon/SketchPanel.java	Wed Dec 31 19:00:00 1969
@@ -1,112 +0,0 @@
-package org.tekkotsu.mon;
-
-import javax.swing.SwingConstants;
-import javax.swing.JLabel;
-import java.awt.Color;
-import java.awt.image.BufferedImage;
-import java.awt.BorderLayout;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.FontMetrics;
-import java.awt.geom.AffineTransform;
-
-public class SketchPanel extends VisionPanel {
-	SketchGUI gui; // reference back to owning SketchGUI
-	AffineTransform atrans;
-	AffineTransform resultAtrans;
-	boolean isCam;
-
-	// coordinate bounds for the view of the SketchPanel
-	float leftBound=0, rightBound=176, topBound=0, bottomBound=144;
-
-	protected SketchPanel(SketchGUI _gui, VisionListener listener, 
-			boolean _isCam) {
-		super(listener);
-		gui = _gui;
-		isCam = _isCam;
-		//listener.run();
-	}	
-	
-	public void visionUpdated(VisionListener l) {
-		super.visionUpdated(l);
-	}
-	
-	protected void drawImage(Graphics _g, BufferedImage img, int x, int y, 
-			int w, int h) {
-		Graphics2D g2d = (Graphics2D)_g;
-		float scaling =java.lang.Math.min(img.getWidth()/(rightBound-leftBound),
-				img.getHeight()/(bottomBound-topBound));
-		if(isCam) {
-			atrans = new AffineTransform(1*scaling,0,0,1*scaling,
-					-leftBound*scaling,-topBound*scaling);
-		} else {
-			atrans = new AffineTransform(1*scaling,0,0,-1*scaling,
-					-leftBound*scaling,bottomBound*scaling);
-
-		}
-		AffineTransform origtrans = g2d.getTransform();
-		g2d.transform(atrans);
-		resultAtrans = g2d.getTransform();
-		//g2d.scale(scale,scale);
-		//g2d.translate(leftBound, topBound);
-//		System.out.println(g2d.getTransform().toString());
-		
-		//buf = new BufferedImage(500,500,BufferedImage.TYPE_BYTE_INDEXED);
-		//buf.setData(img.getRaster());
-
-		if(img!=null) {
-			g2d.setTransform(origtrans);
-			g2d.drawImage(img,x,y,w,h,null);
-	//		g2d.drawImage(img,x,y,(int)(w*scaling),(int)(h*scaling),null);
-			//g2d.drawImage(img,x,y,null);
-			//g2d.drawImage(img, atrans,null);
-		} else {
-			g2d.setColor(getBackground());
-			g2d.fillRect(x,y,w,h);
-			FontMetrics tmp=g2d.getFontMetrics();
-			String msg="No image";
-			int strw=tmp.stringWidth(msg);
-			int strh=tmp.getHeight();
-			g2d.setColor(getForeground());
-			g2d.drawString(msg,(getSize().width-strw)/2,(getSize().height-strh)/2+tmp.getAscent());
-		}
-	
-		// redraw shapes if necessary
-		//gui.renderSelectedInTree(g2d);
-
-		// draw coordinates
-		if (isCam) {
-			g2d.setColor(getForeground());
-			FontMetrics tmp=g2d.getFontMetrics();
-			String msg="("+String.valueOf((int)leftBound)+","+String.valueOf((int)topBound)+")";
-			int strw=tmp.stringWidth(msg);
-			g2d.drawString(msg,x,y+tmp.getAscent());
-			msg="("+String.valueOf((int)rightBound)+","+String.valueOf((int)bottomBound)+")";
-			strw=tmp.stringWidth(msg);
-			g2d.drawString(msg,x+w-strw,y+h-tmp.getDescent());
-		} else {
-			g2d.setColor(getForeground());
-			FontMetrics tmp=g2d.getFontMetrics();
-			int strh=tmp.getHeight();
-			String msg="("+String.valueOf((int)leftBound)+","+String.valueOf((int)bottomBound)+")";
-			int strw=tmp.stringWidth(msg);
-			g2d.drawString(msg,x,y+tmp.getAscent());
-			msg="("+String.valueOf((int)rightBound)+","+String.valueOf((int)topBound)+")";
-			strw=tmp.stringWidth(msg);
-			g2d.drawString(msg,x+w-strw,y+h-tmp.getDescent());
-		}
-
-	}
-
-	// stretches the view of the SketchPanel to accomodate the specified object 
-	public void scaleToVisualObject(VisualObjectInfo oinfo) {
-		if(oinfo.getLeft() < leftBound)
-			leftBound = oinfo.getLeft();
-		if(oinfo.getRight() > rightBound)
-			rightBound = oinfo.getRight();
-		if(oinfo.getTop() < topBound)
-			topBound = oinfo.getTop();
-		if(oinfo.getBottom() > bottomBound)
-			bottomBound = oinfo.getBottom();
-	}
-}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/TCPListener.java ./tools/mon/org/tekkotsu/mon/TCPListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/TCPListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/TCPListener.java	Wed Jun  8 17:05:01 2005
@@ -38,8 +38,7 @@
 			if(_isConnected) {
 				connected(_socket);
 				if(!destroy)
-					System.out.println("["+_port+"] disconnected");
-          System.out.println("["+_port+"] attempting to reestablish ..");
+					System.out.println("["+_port+"] disconnected, attempting to reestablish ..");
 			}
 			attempts++;
 			if(destroy) {
@@ -67,3 +66,4 @@
 	Socket _socket;
 	ServerSocket _serverSocket;
 }
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/TCPVisionListener.java ./tools/mon/org/tekkotsu/mon/TCPVisionListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/TCPVisionListener.java	Mon Nov 29 20:15:52 2004
+++ ./tools/mon/org/tekkotsu/mon/TCPVisionListener.java	Fri Aug  5 15:44:23 2005
@@ -15,6 +15,8 @@
 import javax.imageio.stream.ImageInputStream;
 import javax.imageio.stream.MemoryCacheImageInputStream;
 
+import java.awt.Color;
+
 public class TCPVisionListener extends TCPListener implements VisionListener {
 	boolean updatedFlag;
 	Date timestamp;
@@ -23,7 +25,7 @@
 	protected Vector listeners = new Vector();
 	protected boolean updating;
 
-	public void addListener(VisionUpdatedListener l) { listeners.add(l); }
+	public void addListener(VisionUpdatedListener l) { listeners.add(l); needConnection(); }
 	public void removeListener(VisionUpdatedListener l) { listeners.remove(l); }
 	public void fireVisionUpdate() {
 		updating=true;
@@ -71,6 +73,19 @@
 
 	Object packetFormatChangeLock=new Object();
 
+
+    boolean readingImage;
+
+    public void setReadingImage()
+    {
+	readingImage = true;
+    }
+
+    public boolean isReadingImage()
+    {
+	return readingImage;
+    }
+
 	public boolean hasRawJPEG() { return isJPEG; }
 	public byte[] getJPEG() { return _jpeg; }
 	public int getJPEGLen() { return jpegLen; }
@@ -340,11 +355,69 @@
 		isIndex=true;
 		return true;
 	}
+    
+    public boolean readRegions(InputStream in, int chanW, int chanH) throws java.io.IOException {
+        //clear the _data array
+        for(int h=0; h<chanH; h++) {
+            for(int w =0; w<chanW; w++) {
+                _data[chanW*h+w]=0;
+            }
+        }
+
+        int numColors=readInt(in);
+        if(!_isConnected) return false;
+        for(int curColor = 0; curColor < numColors; curColor++) {
+            int numRegions = readInt(in);
+            if(!_isConnected) return false;
+            
+        	readBytes(_tmp,in,36*numRegions);
+			if(!_isConnected) return false;
+            	
+			int dpos=0;
+			for (int i = 0; i<numRegions; i++) {
+				byte color= _tmp[dpos];
+	            dpos +=4;
+	            int x1 = byteToInt(_tmp,dpos);
+	            dpos +=4;
+	            int y1 = byteToInt(_tmp,dpos);
+	            dpos +=4;
+	            int x2 = byteToInt(_tmp,dpos);
+	            dpos +=4;
+	            int y2 = byteToInt(_tmp,dpos);
+                //The  data of the centroid, area and run_start are ignored
+	            dpos +=20; //isn't nessescary, but now it nicely adds up to 36
+                if (  x1 > chanW || y1 > chanH || x2 > chanW || y2 > chanH
+                   || x1 > x2 || y1 > y2
+                   || x1 < 0 || x2 < 0 || y1 < 0 || y2 < 0
+                   )
+					return false;
+				
+                //Fill the data array with the bounding boxes..
+                //..the top and bottom lines
+				for (int tb = x1; tb <= x2; tb++) {
+	                _data[y1*width+tb]=color;
+	                _data[y2*width+tb]=color;
+	            }
+	            //..the left and right lines
+				for (int lr = y1; lr <= y2; lr++) {
+	                _data[lr*width+x1]=color;
+	                _data[lr*width+x2]=color;
+	            }
+			}
+            readBytes(_tmp,in,12); //read out the min_area, total_area and merge_threshhold and ignore them:)
+        }
+        if(!readColorModel(in)) return false;
+		if(!_isConnected) return false;
+		isIndex=true;
+		return true;
+	}
 
 	public void connected(Socket socket) {
 		_isConnected=true;
-		while(listeners==null) //fixes a race condition, since Listener constructor spawns thread, subclass constructors may not be finished
+		while(listeners==null) {
+			System.out.println("Assert: Bad race condition -- shouldn't be happening");
 			Thread.yield();
+		}
 		fireVisionUpdate();
 		try {
 			InputStream in=socket.getInputStream();
@@ -353,7 +426,8 @@
 				String type = readLoadSaveString(in);
 				if(!_isConnected) break; //System.out.println("Got type="+type);
 				if(!type.equals("TekkotsuImage")) {
-					System.err.println("Unrecognized type: "+type);
+					if(!type.equals("CloseConnection"))
+						System.err.println("Unrecognized type: "+type);
 					break;
 				}
 				fireConnected();
@@ -457,17 +531,27 @@
 						} else if(fmt.equals("SegColorImage")) {
 							isJPEG=false;
 							isIndex=true;
-							if(!readIndexedColor(in,chanwidth,chanheight)) { failed=true; System.err.println("TCPVisionListener SegColor read failed"); break; }
+							if(!readIndexedColor(in,chanwidth,chanheight)) { 
+							    failed=true; 
+							    System.err.println("TCPVisionListener SegColor read failed"); 
+							    break; 
+							}
 						} else if(fmt.equals("RLEImage")) {
 							isJPEG=false;
 							isIndex=true;
 							if(!readRLE(in,chanwidth,chanheight)) { failed=true; System.err.println("TCPVisionListener RLEImage read failed"); break; }
+						} else if(fmt.equals("RegionImage")) {
+							isJPEG=false;
+							isIndex=true;
+							if(!readRegions(in,chanwidth,chanheight)) { failed=true; System.err.println("TCPVisionListener RegionImage read failed"); break; }
 						} else {
 							isJPEG=false;
 							isIndex=false;
 							System.err.println("Unrecognized format: "+fmt);
 							failed=true; break;
 						}
+						//System.out.println("Done reading");
+						readingImage = false;
 					}
 				}
 				if(failed || !_isConnected) {
@@ -503,8 +587,8 @@
 	}
 	
 	public byte[] getData() {
-//		frameTimer();
-		synchronized (_outd) {
+//		frameTimer();		
+	    synchronized (_outd) {
 			updatedFlag=false;
 			return _outd;
 		}
@@ -621,3 +705,4 @@
 	public TCPVisionListener(int port) { super(port); }
 	public TCPVisionListener(String host, int port) { super(host,port); }
 }
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/TwoParamPanel.java ./tools/mon/org/tekkotsu/mon/TwoParamPanel.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/TwoParamPanel.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/TwoParamPanel.java	Wed Jun  1 01:48:09 2005
@@ -0,0 +1,223 @@
+package org.tekkotsu.mon;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.geom.*;
+import java.awt.event.*;
+import javax.swing.event.*;
+import java.util.prefs.Preferences;
+import java.util.Iterator;
+
+public class TwoParamPanel extends JPanel implements PointPick.PointPickedListener, ChangeListener, ActionListener, MouseListener, ParamListener.CommListener {
+	PointPick pp;
+	JPanel sliderPane;
+	JPanel draggerPane;
+	JButton stopBut;
+	JComboBox xsel;
+	JComboBox ysel;
+	JCheckBox resetOnRelease;
+	ParamListener comm;
+	final static ImageIcon carrows = new ImageIcon("images/chasingarrows.png");
+	static Preferences prefs = Preferences.userNodeForPackage(TwoParamPanel.class);
+	static final int strutsize=10;
+	static final int sepsize=5;
+
+	static public void main(String s[]) {
+		int port=ParamListener.defPort;
+		if(s.length<1)
+			usage();
+		if(s.length>1)
+			port=Integer.parseInt(s[1]);
+		String[] args=null;
+		if(s.length>2) {
+			args=new String[s.length-2];
+			for(int i=2; i<s.length; i++)
+				args[i-2]=s[i];
+		}
+		JFrame frame=new JFrame("TekkotsuMon: TwoParamPanel");
+		frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
+		TwoParamPanel tpp=new TwoParamPanel(new ParamListener(s[0],port),args);
+		frame.getContentPane().add(tpp);
+		{
+			Box tmp=Box.createHorizontalBox();
+			tmp.add(Box.createHorizontalStrut(strutsize));
+			{
+				Box tmp2=Box.createVerticalBox();
+				tmp2.add(Box.createVerticalStrut(strutsize));
+				JSeparator jsep=new JSeparator();
+				jsep.setMaximumSize(new Dimension(jsep.getMaximumSize().width,jsep.getPreferredSize().height));
+				tmp2.add(jsep);
+				tmp2.add(Box.createVerticalStrut(sepsize));
+				{
+					Box tmp3=Box.createHorizontalBox();
+					tmp3.add(Box.createHorizontalGlue());
+					JButton reconnectBut=new JButton(carrows);
+					reconnectBut.setPreferredSize(new Dimension(carrows.getIconWidth(),carrows.getIconHeight()));
+					reconnectBut.setMaximumSize(new Dimension(carrows.getIconWidth(),carrows.getIconHeight()));
+					reconnectBut.setActionCommand("reconnect");
+					reconnectBut.addActionListener(tpp);
+					reconnectBut.setToolTipText("Drop current connection and try again.");
+					tmp3.add(reconnectBut);
+					tmp2.add(tmp3);
+				}					
+				tmp2.add(Box.createVerticalStrut(strutsize));
+				tmp.add(tmp2);
+			}
+			tmp.add(Box.createHorizontalStrut(strutsize));
+			frame.getContentPane().add(tmp);
+		}
+		
+		frame.addWindowListener(new WindowAdapter() {
+				public void windowClosing(WindowEvent e) { System.exit(0); }
+			});
+		
+		frame.pack();
+		frame.setVisible(true);
+	}
+	
+	public static void usage() {
+		System.out.println("Usage: java TwoParamPanel host [port]");
+		System.out.println("       if port is not specified, it defaults to: "+ParamListener.defPort);
+		System.exit(2);
+	}
+		
+	public TwoParamPanel(ParamListener pl, String args[]) {
+		super();
+		comm=pl;
+		if(args!=null)
+			for(int i=0; i<args.length; i++)
+				if(comm.getParam(args[i])==null)
+					comm.setParam(args[i],"0");
+		setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
+		{
+			Box tmp=Box.createHorizontalBox();
+			{
+				Box tmp2=Box.createVerticalBox();
+				JLabel label=new JLabel("Y axis:");
+				tmp2.add(label);
+				ysel=new JComboBox(comm.getParams().toArray());
+				ysel.setMaximumSize(ysel.getMinimumSize());
+				ysel.setAlignmentX(0);
+				if(args!=null && args.length>1)
+					ysel.setSelectedItem(args[1]);
+				else if(comm.getParams().size()>1)
+					ysel.setSelectedIndex(1);
+				tmp2.add(ysel);
+				tmp.add(tmp2);
+			}
+			pp=new PointPick(false);
+			pp.addPointPickedListener(this);
+			pp.addMouseListener(this);
+			pp.setMinimumSize(new Dimension(100,100));
+			pp.setPreferredSize(new Dimension(300,300));
+			tmp.add(pp);
+			add(tmp);
+		}
+		{
+			Box tmp=Box.createVerticalBox();
+			tmp.add(Box.createVerticalStrut(sepsize));
+			{
+				Box tmp2=Box.createHorizontalBox();
+				tmp2.add(Box.createHorizontalGlue());
+				tmp2.add(new JLabel("X axis:  "));
+				xsel=new JComboBox(comm.getParams().toArray());
+				xsel.setMaximumSize(xsel.getMinimumSize());
+				if(args!=null && args.length>0)
+					xsel.setSelectedItem(args[0]);
+				else if(comm.getParams().size()>0)
+					xsel.setSelectedIndex(0);
+				tmp2.add(xsel);
+				tmp2.add(Box.createHorizontalGlue());
+				tmp.add(tmp2);
+			}
+			tmp.add(Box.createVerticalStrut(sepsize));
+			{
+				Box tmp2=Box.createHorizontalBox();
+				tmp2.add(Box.createHorizontalGlue());
+				stopBut=new JButton("Center");
+				stopBut.addActionListener(this);
+				tmp2.add(stopBut);
+				tmp2.add(Box.createHorizontalGlue());
+				tmp.add(tmp2);
+			}
+			tmp.add(Box.createVerticalStrut(sepsize));
+			{
+				Box tmp2=Box.createHorizontalBox();
+				tmp2.add(Box.createHorizontalGlue());
+				tmp2.add(resetOnRelease=new JCheckBox("Center on release"));
+				tmp2.add(Box.createHorizontalGlue());
+				tmp.add(tmp2);
+			}
+			add(tmp);
+		}
+		pp.setEnabled(comm._isConnected);
+		stopBut.setEnabled(comm._isConnected);
+		comm.addCommListener(this);
+	}
+
+	public void pointPicked(Point2D.Float p, MouseEvent e, PointPick pp) {
+		comm.setParam((String)xsel.getSelectedItem(),String.valueOf(p.x));
+		comm.setParam((String)ysel.getSelectedItem(),String.valueOf(p.y));
+	}
+
+	public void commUpdated(ParamListener comm) {
+		if(pp.isEnabled()!=comm._isConnected || comm.getParams().size()!=xsel.getItemCount()) {
+			Object x=xsel.getSelectedItem();
+			xsel.removeAllItems();
+			for(Iterator it=comm.getParams().iterator(); it.hasNext(); xsel.addItem(it.next())) {}
+			xsel.setMaximumSize(xsel.getMinimumSize());
+			xsel.setSelectedItem(x);
+
+			Object y=ysel.getSelectedItem();
+			ysel.removeAllItems();
+			for(Iterator it=comm.getParams().iterator(); it.hasNext(); ysel.addItem(it.next())) {}
+			ysel.setMaximumSize(ysel.getMinimumSize());
+			ysel.setSelectedItem(y);
+
+			pp.setEnabled(comm._isConnected);
+			stopBut.setEnabled(comm._isConnected);
+		}
+	}
+
+	public void mouseClicked(MouseEvent e) {}
+	public void mouseEntered(MouseEvent e) {}
+	public void mouseExited(MouseEvent e) {}
+	public void mousePressed(MouseEvent e) {}
+	public void mouseReleased(MouseEvent e) {
+		if(resetOnRelease.isSelected())
+			stopBut.doClick();
+	}
+
+	public void stateChanged(ChangeEvent e) {
+		/*
+		if(e.getSource()==tslide) {
+			comm.sendCommand("t",tslide.getValue()/(float)slidermax);
+			pp.doSetPoint(pp.getXValue(),tslide.getValue()/(float)slidermax);
+		} else if(e.getSource()==pslide) {
+			comm.sendCommand("p",-pslide.getValue()/(float)slidermax);
+			if(horizPanBut.isSelected())
+				pp.doSetPoint(pslide.getValue()/(float)slidermax,pp.getYValue());
+		} else if(e.getSource()==rslide) {
+			// Rotation is both fast and sensitive, so we'll exponentiate it to
+			// drag out the low end without sacrificing the high end
+			comm.sendCommand("r",rslide.getValue()/(float)slidermax);
+			float tmp=pp.getYValue();
+			if(horizRollBut.isSelected())
+				pp.doSetPoint(rslide.getValue()/(float)slidermax,pp.getYValue());
+		}
+		*/
+	}
+
+	public void actionPerformed(ActionEvent e) {
+		if(e.getSource()==stopBut) {
+			pp.doSetPoint(0,0);
+			comm.setParam((String)xsel.getSelectedItem(),"0");
+			comm.setParam((String)ysel.getSelectedItem(),"0");
+		} else if(e.getActionCommand().equals("reconnect")) {
+			int port=comm._port;
+			String addr=comm._host;
+			comm.close();
+			comm.startThread();
+		}
+	}
+}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/UDPListener.java ./tools/mon/org/tekkotsu/mon/UDPListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/UDPListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/UDPListener.java	Fri Jul 29 19:08:03 2005
@@ -1,67 +1 @@
-package org.tekkotsu.mon;
-
-import java.net.DatagramSocket;
-import java.net.*;
-
-
-public abstract class UDPListener extends Listener {
-  protected abstract void connected(DatagramSocket socket);
-
-  String message = new String("connection request");
-  byte[] buf = message.getBytes();
-
-  protected void runServer() {
-    try {
-      _socket=new DatagramSocket(_port);
-
-      try {
-        _socket.connect(InetAddress.getByName(_host), _port);
-        _socket.setSoTimeout(2000); // block for 2 seconds at most
-      } catch (Exception ex) { }
-
-      // send a dummy message so that the AIBO can see what
-      // address to connect it's UDP socket to
-      DatagramPacket message = new DatagramPacket(buf, buf.length,
-                                                  InetAddress.getByName(_host),
-                                                  _port);
-      _socket.send(message);
-
-      connected(_socket);
-    } catch (Exception ex) {
-      System.out.println("port "+_port+": "+ex);
-    }
-  }
-
-  protected void runConnect() {
-    try {
-      _socket=new DatagramSocket(_port);
-
-      try {
-        _socket.connect(InetAddress.getByName(_host), _port);
-        _socket.setSoTimeout(2000); // block for 2 seconds at most
-      } catch (Exception ex) { }
-
-      // send a dummy message so that the AIBO can see what
-      // address to connect it's UDP socket to
-      DatagramPacket message = new DatagramPacket(buf, buf.length,
-                                                  InetAddress.getByName(_host),
-                                                  _port);
-      _socket.send(message);
-
-      connected(_socket);
-    } catch (Exception ex) { }
-  }
-
-  public void close() {
-
-	try{_socket.close();}
-	catch(Exception e){}
-
-  }
-
-  public UDPListener() { super(); }
-  public UDPListener(int port) { super(port); }
-  public UDPListener(String host, int port) { super(host, port); }
-
-  DatagramSocket _socket;
-}
+package org.tekkotsu.mon;import java.net.DatagramSocket;import java.net.*;public abstract class UDPListener extends Listener {  protected abstract void connected(DatagramSocket socket, DatagramPacket firstPacket);  byte[] incomingbuf = new byte[1<<16];  DatagramPacket incoming = new DatagramPacket(incomingbuf, incomingbuf.length);  byte[] buf = (new String("connection request")).getBytes();	int _lastPort=-1; // keep track of previously used port number so we can resume connections  protected void runServer() {		System.out.println("ERROR: UDP server listener is not implemented");    try {      //_socket=new DatagramSocket(_port);      try {        //_socket.connect(InetAddress.getByName(_host), _port);        //_socket.setSoTimeout(10000); // block for 10 seconds at most (if infinite, we can't automatically detect a closed connection & then reconnect      } catch (Exception ex) { }      // send a dummy message so that the AIBO can see what      // address to connect it's UDP socket to			/*      DatagramPacket message = new DatagramPacket(buf, buf.length,                                                  InetAddress.getByName(_host),                                                  _port);      _socket.send(message);			*/      //connected(_socket);    } catch (Exception ex) {      System.out.println("port "+_port+": "+ex);    }  }  protected void runConnect() {		int attempts=0;		Thread me = Thread.currentThread();		while (me==_listenerThread && !destroy) {			if(attempts==0) {				System.out.println("["+_port+"] connecting ...");			}			try {				if(_lastPort==-1)					_socket=new DatagramSocket();				else					_socket=new DatagramSocket(_lastPort);				_lastPort=_socket.getLocalPort();				_socket.connect(InetAddress.getByName(_host), _port);				// send a dummy message so that the AIBO can see what				// address to connect it's UDP socket to				DatagramPacket message = new DatagramPacket(buf, buf.length);				_socket.send(message);				_socket.setSoTimeout(500);				_socket.receive(incoming);				_socket.setSoTimeout(0); //set to be blocking				System.out.println("["+_port+"] connected ...");				attempts=0;				_isConnected=true;			} catch (Exception ex) {}			if(_isConnected) {				connected(_socket,incoming);				if(!destroy)					System.out.println("["+_port+"] disconnected, attempting to reestablish ..");			}			attempts++;			if(destroy) {				System.out.println("["+_port+"] connection closed");				break;			}			try {				Thread.sleep(500);			} catch (Exception ex) {}		}  }  public void close() {	_listenerThread=null;	_isConnected=false;		try{_socket.close();}	catch(Exception e){}  }  public UDPListener() { super(); }  public UDPListener(int port) { super(port); }  public UDPListener(String host, int port) { super(host, port); }  DatagramSocket _socket;}
\ No newline at end of file
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/UDPVisionListener.java ./tools/mon/org/tekkotsu/mon/UDPVisionListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/UDPVisionListener.java	Mon Nov 29 20:15:52 2004
+++ ./tools/mon/org/tekkotsu/mon/UDPVisionListener.java	Fri Aug  5 15:44:23 2005
@@ -1,628 +1 @@
-package org.tekkotsu.mon;
-
-import java.awt.image.BufferedImage;
-import java.util.Vector;
-import java.util.Date;
-
-import java.io.*;
-import java.net.*;
-import java.awt.image.BufferedImage;
-import java.awt.image.Raster;
-import java.awt.image.IndexColorModel;
-import java.util.Date;
-import javax.imageio.ImageIO;
-import javax.imageio.ImageReader;
-import javax.imageio.stream.ImageInputStream;
-import javax.imageio.stream.MemoryCacheImageInputStream;
-
-public class UDPVisionListener extends UDPListener implements VisionListener {
-  DatagramSocket mysock;
-	
-  byte[] buf = new byte[200000];
-  DatagramPacket incoming = new DatagramPacket(buf, buf.length);
-	
-  InputStream in;
-
-	boolean updatedFlag;
-	Date timestamp;
-	long frameNum=0;
-
-	protected Vector listeners = new Vector();
-	protected boolean updating;
-	
-	public void addListener(VisionUpdatedListener l) { listeners.add(l); }
-	public void removeListener(VisionUpdatedListener l) { listeners.remove(l); }
-	public void fireVisionUpdate() {
-		updating=true;
-		for(int i=0; i<listeners.size() && updating; i++)
-			((VisionUpdatedListener)listeners.get(i)).visionUpdated(this);
-		updating=false;
-	}
-
-	public Date getTimeStamp() { return timestamp; }
-	public long getFrameNum() { return frameNum; }
-	public IndexColorModel getColorModel() { return cmodel; }
-
-	public boolean hasData() {
-		return updatedFlag;
-	}
- 
-	public boolean isConnected() {
-		return _isConnected;
-	}
-
-	int channels=3;
-	int width=DEFAULT_WIDTH;
-	int height=DEFAULT_HEIGHT;
-	int pktSize=width*height*channels;
-	int oldformat=PACKET_VISIONRAW_FULL;
-	int format;
-	int compression;
-	int chan_id;
-
-	byte[] _data=new byte[pktSize];
-	byte[] _outd=new byte[pktSize];
-	byte[] _tmp=new byte[pktSize*2];
-	byte[] _jpeg=new byte[pktSize*2];
-	byte[] _newjpeg=new byte[pktSize*2];
-	boolean isJPEG=false;
-	int jpegLen=0;
-	int newjpegLen=0;
-	boolean isIndex=false;
-	boolean badCompressWarn=false;
-	int[] _pixels=new int[width*height];
-	BufferedImage img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
-	int bytesRead;
-	boolean convertRGB=true;
-	IndexColorModel cmodel;
-
-	public boolean hasRawJPEG() { return isJPEG; }
-	public byte[] getJPEG() { return _jpeg; }
-	public int getJPEGLen() { return jpegLen; }
-	
-	public String readLoadSaveString(InputStream in) throws java.io.IOException {
-		int creatorLen=readInt(in);
-		if(!_isConnected) return ""; 
-		String creator=new String(readBytes(in,creatorLen));
-		if(!_isConnected) return "";
-		if(readChar(in)!='\0')
-			System.err.println("Misread LoadSave string? "+creator);
-		return creator;
-	}
-
-	public boolean readChannel(InputStream in, int c, int chanW, int chanH) throws java.io.IOException {
-		readBytes(_tmp,in,chanW*chanH);
-		if(!_isConnected) return false;
-		return upsampleData(c,chanW,chanH);
-	}
-	public boolean upsampleData(int c, int chanW, int chanH) {
-		if(chanW==width && chanH==height) {
-			//special case: straight copy if image and channel are same size
-			for(int y=0;y<height;y++) {
-				int datarowstart=y*width*channels+c;
-				int tmprowstart=y*chanW;
-				for(int x=0;x<width;x++)
-					_data[datarowstart+x*channels]=_tmp[tmprowstart+x];
-			}
-			return true;
-		}
-		//otherwise this channel is subsampled, need to blow it up
-		//we'll linearly interpolate between pixels
-		//METHOD A:
-		//hold edges, interpolate through middle:
-		//  if we have 2 samples, scaling up to 4
-		//   index: 0   1    2   3
-		// maps to: 0  1/3  2/3  1
-		/*
-		float xsc=(chanW-1)/(float)(width-1);
-		float ysc=(chanH-1)/(float)(height-1);
-		for(int y=0;y<height-1;y++) {
-			int datarowstart=y*width*channels+c;
-			float ty=y*ysc;
-			int ly=(int)ty; //lower pixel index
-			float fy=ty-ly; //upper pixel weight
-			int tmprowstart=ly*chanW;
-			for(int x=0;x<width-1;x++) {
-				float tx=x*xsc;
-				int lx=(int)tx; //lower pixel index
-				float fx=tx-lx; //upper pixel weight
-
-				float lv=((int)_tmp[tmprowstart+lx]&0xFF)*(1-fx)+((int)_tmp[tmprowstart+lx+1]&0xFF)*fx;
-				float uv=((int)_tmp[tmprowstart+lx+chanW]&0xFF)*(1-fx)+((int)_tmp[tmprowstart+lx+1+chanW]&0xFF)*fx;
-				_data[datarowstart+x*channels]=(byte)(lv*(1-fy)+uv*fy);
-			}
-			_data[datarowstart+(width-1)*channels]=_tmp[tmprowstart+chanW-1];
-		}
-		int datarowstart=width*(height-1)*channels+c;
-		int tmprowstart=chanW*(chanH-1);
-		for(int x=0;x<width-1;x++) {
-			float tx=x*xsc;
-			int lx=(int)tx; //lower pixel index
-			float fx=tx-lx; //upper pixel weight
-			_data[datarowstart+x*channels]=(byte)(((int)_tmp[tmprowstart+lx]&0xFF)*(1-fx)+((int)_tmp[tmprowstart+lx+1]&0xFF)*fx);
-		}
-		_data[datarowstart+(width-1)*channels]=_tmp[tmprowstart+chanW-1];
-		*/
-		
-		//Unfortunately, pixels are simply interleaved, starting at the
-		//top right.  So, Method A will stretch things to the bottom-right
-		//a bit.  This method holds left edge and spacing, so it lines up
-		//better with what's being transmitted (but the bottom right edges
-		//wind up smeared)
-		//METHOD B:
-		//  if we have 2 samples, scaling up to 4
-		//   index: 0   1    2   3
-		// maps to: 0  1/2   1   1  <-- this last one would be 3/2, so we have to replicate 1
-		float xsc=(chanW)/(float)(width);
-		float ysc=(chanH)/(float)(height);
-		int xgap=Math.round(1.0f/xsc);
-		int ygap=Math.round(1.0f/ysc);
-		for(int y=0;y<height-ygap;y++) {
-			int datarowstart=y*width*channels+c;
-			float ty=y*ysc;
-			int ly=(int)ty; //lower pixel index
-			float fy=ty-ly; //upper pixel weight
-			int tmprowstart=ly*chanW;
-			for(int x=0;x<width-xgap;x++) {
-				float tx=x*xsc;
-				int lx=(int)tx; //lower pixel index
-				float fx=tx-lx; //upper pixel weight
-
-				float lv=(_tmp[tmprowstart+lx]&0xFF)*(1-fx)+(_tmp[tmprowstart+lx+1]&0xFF)*fx;
-				float uv=(_tmp[tmprowstart+lx+chanW]&0xFF)*(1-fx)+(_tmp[tmprowstart+lx+1+chanW]&0xFF)*fx;
-				_data[datarowstart+x*channels]=(byte)(lv*(1-fy)+uv*fy);
-			}
-			for(int x=width-xgap;x<width;x++) {
-				float lv=(_tmp[tmprowstart+chanW-1]&0xFF);
-				float uv=(_tmp[tmprowstart+chanW-1+chanW]&0xFF);
-				_data[datarowstart+x*channels]=(byte)(lv*(1-fy)+uv*fy);
-			}
-		}
-		for(int y=height-ygap;y<height;y++) {
-			int datarowstart=y*width*channels+c;
-			int tmprowstart=chanW*(chanH-1);
-			for(int x=0;x<width-xgap;x++) {
-				float tx=x*xsc;
-				int lx=(int)tx; //lower pixel index
-				float fx=tx-lx; //upper pixel weight
-
-				float lv=(_tmp[tmprowstart+lx]&0xFF)*(1-fx)+(_tmp[tmprowstart+lx+1]&0xFF)*fx;
-				_data[datarowstart+x*channels]=(byte)(lv);
-			}
-			for(int x=width-xgap;x<width;x++)
-				_data[datarowstart+x*channels]=_tmp[tmprowstart+chanW-1];
-		}
-		
-		return true;
-	}
-
-	public boolean readJPEGChannel(InputStream in, int c, int chanW, int chanH) throws java.io.IOException {
-		int len=readInt(in);
-		newjpegLen=len;
-		//System.out.println("len="+len);
-		if(!_isConnected) return false;
-		if(len>=_newjpeg.length) {
-			System.out.println("Not enough tmp room");
-			return false;
-		}
-		readBytes(_newjpeg,in,len);
-		if(!_isConnected) return false;
-		if(len>chanW*chanH*channels) {
-			if(!badCompressWarn) {
-				badCompressWarn=true;
-				System.out.println("Compressed image is larger than raw would be... :(");
-			}
-		} else {
-			if(badCompressWarn) {
-				badCompressWarn=false;
-				System.out.println("...ok, compressed image is smaller than raw now... :)");
-			}
-		}
-
-		try {
-			ImageInputStream jpegStream=new MemoryCacheImageInputStream(new ByteArrayInputStream(_newjpeg));
-			jpegReader.setInput(jpegStream); 
-			Raster decoded=jpegReader.readRaster(0,null);
-			int off=c;
-			for(int y=0; y<chanH; y++)
-				for(int x=0; x<chanW; x++) {
-					_data[off]=(byte)decoded.getSample(x,y,0);
-					off+=channels;
-				}
-		} catch(Exception ex) { ex.printStackTrace(); }
-		return true;
-	}
-
-	public boolean readJPEG(InputStream in, int chanW, int chanH) throws java.io.IOException {
-		int len=readInt(in);
-		newjpegLen=len;
-		//System.out.println("len="+len);
-		if(!_isConnected) return false;
-		if(len>=_newjpeg.length) {
-			System.out.println("Not enough tmp room");
-			return false;
-		}
-		readBytes(_newjpeg,in,len);
-		if(!_isConnected) return false;
-		if(len>chanW*chanH*channels) {
-			if(!badCompressWarn) {
-				badCompressWarn=true;
-				System.out.println("Compressed image is larger than raw would be... :(");
-			}
-		} else {
-			if(badCompressWarn) {
-				badCompressWarn=false;
-				System.out.println("...ok, compressed image is smaller than raw now... :)");
-			}
-		}
-
-		try {
-			ImageInputStream jpegStream=new MemoryCacheImageInputStream(new ByteArrayInputStream(_newjpeg));
-			jpegReader.setInput(jpegStream); 
-			Raster decoded=jpegReader.readRaster(0,null);
-			int off=0;
-			for(int y=0; y<chanH; y++)
-				for(int x=0; x<chanW; x++) {
-					_data[off++]=(byte)decoded.getSample(x,y,0);
-					_data[off++]=(byte)decoded.getSample(x,y,2);
-					_data[off++]=(byte)decoded.getSample(x,y,1);
-				}
-		} catch(Exception ex) { ex.printStackTrace(); }
-		return true;
-	}
-
-	byte[] colormap = new byte[256*3];
-	public boolean readColorModel(InputStream in) throws java.io.IOException {
-		int len=readInt(in);
-		//System.out.println("len="+len);
-		if(!_isConnected) return false;
-		readBytes(colormap,in,len*3);
-		if(!_isConnected) return false;
-		//we'll do this stupid thing because we can't change an existing color model, and we don't want to make a new one for each frame
-		// (btw, java is stupid)
-		boolean makeNew=false;
-		if(cmodel==null || len!=cmodel.getMapSize()) {
-			makeNew=true;
-		} else {
-			int off=0;
-			for(int i=0; i<len; i++) {
-				if((byte)cmodel.getRed(i)!=colormap[off++] || (byte)cmodel.getGreen(i)!=colormap[off++] || (byte)cmodel.getBlue(i)!=colormap[off++]) {
-					makeNew=true;
-					break;
-				}
-			}
-		}
-		if(makeNew) {
-			//System.out.println("new color model");
-			cmodel=new IndexColorModel(7,len,colormap,0,false);
-		}
-		return true;
-	}
-	
-	public boolean readIndexedColor(InputStream in, int chanW, int chanH) throws java.io.IOException {
-		readBytes(_data,in,chanW*chanH);
-		if(!_isConnected) return false;
-		if(!readColorModel(in)) return false;
-		if(!_isConnected) return false;
-		isIndex=true;
-		return true;
-	}
-
-	public boolean readRLE(InputStream in, int chanW, int chanH) throws java.io.IOException {
-		int len=readInt(in);
-		if(!_isConnected) return false;
-		readBytes(_tmp,in,len*5);
-		if(!_isConnected) return false;
-
-		int dpos=0;
-		int curx=0, cury=0;
-		for (; len>0 && cury<chanH;) {
-			byte color=_tmp[dpos++];
-			int x=((int)_tmp[dpos++]&0xFF);
-			x|=((int)_tmp[dpos++]&0xFF)<<8;
-			int rlen=((int)_tmp[dpos++]&0xFF);
-			rlen|=((int)_tmp[dpos++]&0xFF)<<8;
-			//System.out.println(color + " "+x + " "+rlen);
-			len--;
-			if (x < curx)
-				return false;
-			
-			for (; curx < x; curx++)
-				_data[cury*width+curx]=0;
-			
-			if (curx+rlen>width)
-				return false;
-			
-			for (; rlen>0; rlen--, curx++)
-				_data[cury*width+curx]=color;
-			if (curx==width) {
-				cury++;
-				curx=0;
-			}
-		}
-		if(!readColorModel(in)) return false;
-		if(!_isConnected) return false;
-		isIndex=true;
-		return true;
-	}
-
-	public void connected(DatagramSocket UDPsocket) {
-		_isConnected=true;
-		mysock = UDPsocket;
-		while(listeners==null) //fixes a race condition, since Listener constructor spawns thread, subclass constructors may not be finished
-			Thread.yield();
-		fireVisionUpdate();
-		try {
-			while(!mysock.isClosed()) {
-				mysock.receive(incoming);
-				in = new ByteArrayInputStream(incoming.getData());
-				String type = readLoadSaveString(in);
-				if(!_isConnected) break; //System.out.println("Got type="+type);
-				if(!type.equals("TekkotsuImage")) {
-					System.err.println("Unrecognized type: "+type);
-					break;
-				}
-        fireConnected();
-				format=readInt(in);
-				if(!_isConnected) break; //System.out.println("Got format="+format);
-				compression=readInt(in);
-				if(!_isConnected) break; //System.out.println("Got compression="+compression);
-				int newWidth=readInt(in);
-				if(!_isConnected) break; //System.out.println("Got newWidth="+newWidth);
-				int newHeight=readInt(in);
-				if(!_isConnected) break; //System.out.println("Got newHeight="+newHeight);
-				long timest=readInt(in);
-				if(timest<0)
-					timest+=(1L<<32);
-				if(!_isConnected) break; //System.out.println("Got timest="+timest);
-				frameNum=readInt(in);
-				if(frameNum<0)
-					frameNum+=(1L<<32);
-				if(!_isConnected) break; //System.out.println("Got frameNum="+frameNum);
-				
-				if (format!=oldformat || newWidth!=width || newHeight!=height) {
-					width=newWidth;
-					height=newHeight;
-					synchronized (_outd) {
-						switch (format) {
-						case ENCODE_COLOR:
-							channels=3;
-							pktSize=width*height*channels;
-							break;
-						case ENCODE_SINGLE_CHANNEL:
-							channels=1;
-							pktSize=width*height*channels;
-							break;
-						default:
-							System.err.println("VisionRawListener: unknown packet type "+format);
-							throw new java.lang.NoSuchFieldException("fake exception");
-						}
-						_data=new byte[pktSize];
-						_outd=new byte[pktSize];
-						_tmp=new byte[pktSize];
-						_jpeg=new byte[pktSize*2<2000?2000:pktSize*2];
-						_newjpeg=new byte[pktSize*2<2000?2000:pktSize*2];
-						_pixels=new int[width*height];;
-						img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
-						oldformat=format;
-					}
-				}
-				
-				boolean failed=false;
-				for(int i=0; i<channels; i++) {
-					String creator = readLoadSaveString(in);
-					if(!_isConnected) break; //System.out.println("Got creator="+creator);
-					if(!creator.equals("FbkImage")) {
-						System.err.println("Unrecognized creator: "+creator);
-						failed=true; break;
-					} else {
-						int chanwidth=readInt(in);
-						if(!_isConnected) break; //System.out.println("Got chanwidth="+chanwidth);
-						int chanheight=readInt(in);
-						if(!_isConnected) break; //System.out.println("Got chanheight="+chanheight);
-						
-						if(chanwidth>width || chanheight>height) {
-							System.err.println("channel dimensions exceed image dimensions");
-							failed=true; break;
-						}
-						
-						int layer=readInt(in);
-						if(!_isConnected) break; //System.out.println("Got layer="+layer);
-						chan_id=readInt(in);
-						if(!_isConnected) break; //System.out.println("Got chan_id="+chan_id);
-				
-						String fmt=readLoadSaveString(in);
-						if(!_isConnected) break; //System.out.println("Got fmt="+fmt);
-						if(fmt.equals("blank")) {
-							isJPEG=false;
-							isIndex=false;
-							int useChan=(channels==1)?i:chan_id;
-							int off=useChan;
-							for(int y=0; y<height; y++)
-								for(int x=0; x<width; x++) {
-									_data[off]=(byte)(convertRGB?0x80:0);
-									off+=channels;
-								}
-						} else if(fmt.equals("RawImage")) {
-							isJPEG=false;
-							isIndex=false;
-							int useChan=(channels==1)?i:chan_id;
-							if(!readChannel(in,useChan,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener channel read failed"); break; }
-						} else if(fmt.equals("JPEGGrayscale")) {
-							isIndex=false;
-							int useChan=(channels==1)?i:chan_id;
-							if(!readJPEGChannel(in,useChan,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener JPEGGreyscale channel read failed"); break; }
-							isJPEG=(channels==1);
-						} else if(fmt.equals("JPEGColor")) {
-							isIndex=false;
-							if(format==ENCODE_SINGLE_CHANNEL)
-								System.err.println("WTF? ");
-							if(!readJPEG(in,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener JPEGColor channel read failed"); break; }
-							i=channels;
-							isJPEG=true;
-						} else if(fmt.equals("SegColorImage")) {
-							isJPEG=false;
-							isIndex=true;
-							if(!readIndexedColor(in,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener SegColor read failed"); break; }
-						} else if(fmt.equals("RLEImage")) {
-							isJPEG=false;
-							isIndex=true;
-							if(!readRLE(in,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener RLEImage read failed"); break; }
-						} else {
-							isJPEG=false;
-							isIndex=false;
-							System.err.println("Unrecognized format: "+fmt);
-							failed=true; break;
-						}
-					}
-				}
-				if(failed || !_isConnected) {
-					System.err.println("UDPVisionListener connection lost");
-					break;
-				}
-				
-				synchronized(_outd) {
-					byte[] temp=_data;
-					_data=_outd;
-					_outd=temp;
-					if(isJPEG) {
-						temp=_newjpeg;
-						_newjpeg=_jpeg;
-						_jpeg=temp;
-						int tempi=newjpegLen;
-						newjpegLen=jpegLen;
-						jpegLen=tempi;
-					}
-					timestamp=new Date(timest);
-				}
-				updatedFlag=true;
-				fireVisionUpdate();
-			}
-		} catch (Exception ex) {
-    } finally {
-      fireDisconnected();
-    }
-		
-		try { mysock.close(); } catch (Exception ex) { }
-		_isConnected=false;
-		fireVisionUpdate();
-	}
-	
-	public byte[] getData() {
-		synchronized (_outd) {
-			updatedFlag=false;
-			return _outd;
-		}
-	}
-
-	public void setConvertRGB(boolean b) { 
-		if(b!=convertRGB) {
-			convertRGB=b;
-			updatedFlag=true;
-		}
-	}
-	public boolean getConvertRGB() { return convertRGB; }
-
-	public int[] getYUVPixels() {
-		synchronized(_outd) {
-			byte[] data=getData();
-			int offset=0;
-			for (int i=0; i<width*height; i++) {
-				int y=(int)data[offset++]&0xFF;
-				int u=(int)data[offset++]&0xFF;
-				int v=(int)data[offset++]&0xFF;
-				_pixels[i]=(255<<24) | (y<<16) | (u<<8) | v;
-			}
-		}
-		return _pixels;
-	}
-
-	//This still uses RGB pixels just in case you want to display the
-	//intensity value into hues instead of black/white
-	public int[] getIntensityPixels() {
-		synchronized(_outd) {
-			byte[] data=getData();
-			int offset=0;
-			if(!getConvertRGB()) {
-				for (int i=0; i<width*height; i++) {
-					int z=(int)data[offset++]&0xFF;
-					_pixels[i]=(255<<24) | (z<<16) | (z<<8) | z;
-				}
-			} else if(chan_id==CHAN_Y || chan_id==CHAN_Y_DY || chan_id==CHAN_Y_DX || chan_id==CHAN_Y_DXDY ) {
-				for (int i=0; i<width*height; i++) {
-					int z=(int)data[offset++]&0xFF;
-					_pixels[i]=pixelYUV2RGB(z,0x80,0x80);
-				}
-			} else if(chan_id==CHAN_U) {
-				for (int i=0; i<width*height; i++) {
-					int z=(int)data[offset++]&0xFF;
-					_pixels[i]=pixelYUV2RGB(0x80,z,0x80);
-				}
-			} else if(chan_id==CHAN_V) {
-				for (int i=0; i<width*height; i++) {
-					int z=(int)data[offset++]&0xFF;
-					_pixels[i]=pixelYUV2RGB(0x80,0x80,z);
-				}
-			}
-		}		
-		return _pixels;
-	}
-
-	public int[] getRGBPixels() {
-		synchronized(_outd) {
-			byte[] data=getData();
-			int offset=0;
-			for (int i=0; i<width*height; i++) {
-				int y=(int)data[offset++]&0xFF;
-				int u=(int)data[offset++]&0xFF;
-				int v=(int)data[offset++]&0xFF;
-				_pixels[i]=pixelYUV2RGB(y, u, v);
-			}
-		}
-		return _pixels;
-	}
-
-	static final int pixelYUV2RGB(int y, int u, int v) {
-		u=u*2-255;
-		v=v*2-255;
-		int r=y+u;
-		int b=y+v;
-		u=u>>1;
-		v=(v>>2)-(v>>4);
-		int g=y-u-v;
-		if (r<0) r=0; if (g<0) g=0; if (b<0) b=0;
-		if (r>255) r=255; if (g>255) g=255; if (b>255) b=255;
-
-		return (255<<24) | (r<<16) | (g<<8) | b;
-	}
-
-	public BufferedImage getImage() {
-		if(!updatedFlag)
-			return img;
-		if(isIndex) {
-			byte[] data=getData();
-			if(cmodel==null)
-				return img;
-			if(img.getWidth()!=width || img.getHeight()!=height || img.getType()!=BufferedImage.TYPE_BYTE_INDEXED)
-				img=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_INDEXED,cmodel);
-			img.getRaster().setDataElements(0,0,width,height,data);
-		} else {
-			updatedFlag=false;
-			int[] pix;
-			if(img.getWidth()!=width || img.getHeight()!=height || img.getType()!=BufferedImage.TYPE_BYTE_INDEXED)
-				img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
-			if(format==ENCODE_COLOR)
-				pix=getConvertRGB()?getRGBPixels():getYUVPixels();
-			else
-				pix=getIntensityPixels();
-			img.setRGB(0,0,width,height,pix,0,width);
-		}
-		return img;
-	}
-
-
-
-	public UDPVisionListener() { super(); }
-	public UDPVisionListener(int port) { super(port); }
-	public UDPVisionListener(String host, int port) { super(host,port); }
-}
+package org.tekkotsu.mon;import java.awt.image.BufferedImage;import java.util.Vector;import java.util.Date;import java.io.*;import java.net.*;import java.awt.image.BufferedImage;import java.awt.image.Raster;import java.awt.image.IndexColorModel;import java.util.Date;import javax.imageio.ImageIO;import javax.imageio.ImageReader;import javax.imageio.stream.ImageInputStream;import javax.imageio.stream.MemoryCacheImageInputStream;public class UDPVisionListener extends UDPListener implements VisionListener {  DatagramSocket mysock;	  InputStream in;	boolean updatedFlag;	Date timestamp;	long frameNum=0;	protected Vector listeners = new Vector();	protected boolean updating;		public void addListener(VisionUpdatedListener l) { listeners.add(l); needConnection(); }	public void removeListener(VisionUpdatedListener l) { listeners.remove(l); }	public void fireVisionUpdate() {		updating=true;		for(int i=0; i<listeners.size() && updating; i++)			((VisionUpdatedListener)listeners.get(i)).visionUpdated(this);		updating=false;	}	public Date getTimeStamp() { return timestamp; }	public long getFrameNum() { return frameNum; }	public IndexColorModel getColorModel() { return cmodel; }	public boolean hasData() {		return updatedFlag;	} 	public boolean isConnected() {		return _isConnected;	}	int channels=3;	int width=DEFAULT_WIDTH;	int height=DEFAULT_HEIGHT;	int pktSize=width*height*channels;	int oldformat=PACKET_VISIONRAW_FULL;	int format;	int compression;	int chan_id;	byte[] _data=new byte[pktSize];	byte[] _outd=new byte[pktSize];	byte[] _tmp=new byte[pktSize*2];	byte[] _jpeg=new byte[pktSize*2];	byte[] _newjpeg=new byte[pktSize*2];	boolean isJPEG=false;	int jpegLen=0;	int newjpegLen=0;	boolean isIndex=false;	boolean badCompressWarn=false;	int[] _pixels=new int[width*height];	BufferedImage img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);	int bytesRead;	boolean convertRGB=true;	IndexColorModel cmodel;	public boolean hasRawJPEG() { return isJPEG; }	public byte[] getJPEG() { return _jpeg; }	public int getJPEGLen() { return jpegLen; }		public String readLoadSaveString(InputStream in) throws java.io.IOException {		int creatorLen=readInt(in);		if(!_isConnected) return ""; //System.out.println("creatorLen=="+creatorLen);		String creator=new String(readBytes(in,creatorLen));		if(!_isConnected) return "";		if(readChar(in)!='\0')			System.err.println("Misread LoadSave string? "+creator);		return creator;	}	public boolean readChannel(InputStream in, int c, int chanW, int chanH) throws java.io.IOException {		readBytes(_tmp,in,chanW*chanH);		if(!_isConnected) return false;		return upsampleData(c,chanW,chanH);	}	public boolean upsampleData(int c, int chanW, int chanH) {		if(chanW==width && chanH==height) {			//special case: straight copy if image and channel are same size			for(int y=0;y<height;y++) {				int datarowstart=y*width*channels+c;				int tmprowstart=y*chanW;				for(int x=0;x<width;x++)					_data[datarowstart+x*channels]=_tmp[tmprowstart+x];			}			return true;		}		//otherwise this channel is subsampled, need to blow it up		//we'll linearly interpolate between pixels		//METHOD A:		//hold edges, interpolate through middle:		//  if we have 2 samples, scaling up to 4		//   index: 0   1    2   3		// maps to: 0  1/3  2/3  1		/*		float xsc=(chanW-1)/(float)(width-1);		float ysc=(chanH-1)/(float)(height-1);		for(int y=0;y<height-1;y++) {			int datarowstart=y*width*channels+c;			float ty=y*ysc;			int ly=(int)ty; //lower pixel index			float fy=ty-ly; //upper pixel weight			int tmprowstart=ly*chanW;			for(int x=0;x<width-1;x++) {				float tx=x*xsc;				int lx=(int)tx; //lower pixel index				float fx=tx-lx; //upper pixel weight				float lv=((int)_tmp[tmprowstart+lx]&0xFF)*(1-fx)+((int)_tmp[tmprowstart+lx+1]&0xFF)*fx;				float uv=((int)_tmp[tmprowstart+lx+chanW]&0xFF)*(1-fx)+((int)_tmp[tmprowstart+lx+1+chanW]&0xFF)*fx;				_data[datarowstart+x*channels]=(byte)(lv*(1-fy)+uv*fy);			}			_data[datarowstart+(width-1)*channels]=_tmp[tmprowstart+chanW-1];		}		int datarowstart=width*(height-1)*channels+c;		int tmprowstart=chanW*(chanH-1);		for(int x=0;x<width-1;x++) {			float tx=x*xsc;			int lx=(int)tx; //lower pixel index			float fx=tx-lx; //upper pixel weight			_data[datarowstart+x*channels]=(byte)(((int)_tmp[tmprowstart+lx]&0xFF)*(1-fx)+((int)_tmp[tmprowstart+lx+1]&0xFF)*fx);		}		_data[datarowstart+(width-1)*channels]=_tmp[tmprowstart+chanW-1];		*/				//Unfortunately, pixels are simply interleaved, starting at the		//top right.  So, Method A will stretch things to the bottom-right		//a bit.  This method holds left edge and spacing, so it lines up		//better with what's being transmitted (but the bottom right edges		//wind up smeared)		//METHOD B:		//  if we have 2 samples, scaling up to 4		//   index: 0   1    2   3		// maps to: 0  1/2   1   1  <-- this last one would be 3/2, so we have to replicate 1		float xsc=(chanW)/(float)(width);		float ysc=(chanH)/(float)(height);		int xgap=Math.round(1.0f/xsc);		int ygap=Math.round(1.0f/ysc);		for(int y=0;y<height-ygap;y++) {			int datarowstart=y*width*channels+c;			float ty=y*ysc;			int ly=(int)ty; //lower pixel index			float fy=ty-ly; //upper pixel weight			int tmprowstart=ly*chanW;			for(int x=0;x<width-xgap;x++) {				float tx=x*xsc;				int lx=(int)tx; //lower pixel index				float fx=tx-lx; //upper pixel weight				float lv=(_tmp[tmprowstart+lx]&0xFF)*(1-fx)+(_tmp[tmprowstart+lx+1]&0xFF)*fx;				float uv=(_tmp[tmprowstart+lx+chanW]&0xFF)*(1-fx)+(_tmp[tmprowstart+lx+1+chanW]&0xFF)*fx;				_data[datarowstart+x*channels]=(byte)(lv*(1-fy)+uv*fy);			}			for(int x=width-xgap;x<width;x++) {				float lv=(_tmp[tmprowstart+chanW-1]&0xFF);				float uv=(_tmp[tmprowstart+chanW-1+chanW]&0xFF);				_data[datarowstart+x*channels]=(byte)(lv*(1-fy)+uv*fy);			}		}		for(int y=height-ygap;y<height;y++) {			int datarowstart=y*width*channels+c;			int tmprowstart=chanW*(chanH-1);			for(int x=0;x<width-xgap;x++) {				float tx=x*xsc;				int lx=(int)tx; //lower pixel index				float fx=tx-lx; //upper pixel weight				float lv=(_tmp[tmprowstart+lx]&0xFF)*(1-fx)+(_tmp[tmprowstart+lx+1]&0xFF)*fx;				_data[datarowstart+x*channels]=(byte)(lv);			}			for(int x=width-xgap;x<width;x++)				_data[datarowstart+x*channels]=_tmp[tmprowstart+chanW-1];		}				return true;	}	public boolean readJPEGChannel(InputStream in, int c, int chanW, int chanH) throws java.io.IOException {		int len=readInt(in);		newjpegLen=len;		//System.out.println("len="+len);		if(!_isConnected) return false;		if(len>=_newjpeg.length) {			System.out.println("Not enough tmp room");			return false;		}		readBytes(_newjpeg,in,len);		if(!_isConnected) return false;		if(len>chanW*chanH*channels) {			if(!badCompressWarn) {				badCompressWarn=true;				System.out.println("Compressed image is larger than raw would be... :(");			}		} else {			if(badCompressWarn) {				badCompressWarn=false;				System.out.println("...ok, compressed image is smaller than raw now... :)");			}		}		try {			ImageInputStream jpegStream=new MemoryCacheImageInputStream(new ByteArrayInputStream(_newjpeg));			jpegReader.setInput(jpegStream); 			Raster decoded=jpegReader.readRaster(0,null);			int off=c;			for(int y=0; y<chanH; y++)				for(int x=0; x<chanW; x++) {					_data[off]=(byte)decoded.getSample(x,y,0);					off+=channels;				}		} catch(Exception ex) { ex.printStackTrace(); }		return true;	}	public boolean readJPEG(InputStream in, int chanW, int chanH) throws java.io.IOException {		int len=readInt(in);		newjpegLen=len;		//System.out.println("len="+len);		if(!_isConnected) return false;		if(len>=_newjpeg.length) {			System.out.println("Not enough tmp room");			return false;		}		readBytes(_newjpeg,in,len);		if(!_isConnected) return false;		if(len>chanW*chanH*channels) {			if(!badCompressWarn) {				badCompressWarn=true;				System.out.println("Compressed image is larger than raw would be... :(");			}		} else {			if(badCompressWarn) {				badCompressWarn=false;				System.out.println("...ok, compressed image is smaller than raw now... :)");			}		}		try {			ImageInputStream jpegStream=new MemoryCacheImageInputStream(new ByteArrayInputStream(_newjpeg));			jpegReader.setInput(jpegStream); 			Raster decoded=jpegReader.readRaster(0,null);			int off=0;			for(int y=0; y<chanH; y++)				for(int x=0; x<chanW; x++) {					_data[off++]=(byte)decoded.getSample(x,y,0);					_data[off++]=(byte)decoded.getSample(x,y,2);					_data[off++]=(byte)decoded.getSample(x,y,1);				}		} catch(Exception ex) { ex.printStackTrace(); }		return true;	}	byte[] colormap = new byte[256*3];	public boolean readColorModel(InputStream in) throws java.io.IOException {		int len=readInt(in);		//System.out.println("len="+len);		if(!_isConnected) return false;		readBytes(colormap,in,len*3);		if(!_isConnected) return false;		//we'll do this stupid thing because we can't change an existing color model, and we don't want to make a new one for each frame		// (btw, java is stupid)		boolean makeNew=false;		if(cmodel==null || len!=cmodel.getMapSize()) {			makeNew=true;		} else {			int off=0;			for(int i=0; i<len; i++) {				if((byte)cmodel.getRed(i)!=colormap[off++] || (byte)cmodel.getGreen(i)!=colormap[off++] || (byte)cmodel.getBlue(i)!=colormap[off++]) {					makeNew=true;					break;				}			}		}		if(makeNew) {			//System.out.println("new color model");			cmodel=new IndexColorModel(7,len,colormap,0,false);		}		return true;	}		public boolean readIndexedColor(InputStream in, int chanW, int chanH) throws java.io.IOException {		readBytes(_data,in,chanW*chanH);		if(!_isConnected) return false;		if(!readColorModel(in)) return false;		if(!_isConnected) return false;		isIndex=true;		return true;	}	public boolean readRLE(InputStream in, int chanW, int chanH) throws java.io.IOException {		int len=readInt(in);		if(!_isConnected) return false;		readBytes(_tmp,in,len*5);		if(!_isConnected) return false;		int dpos=0;		int curx=0, cury=0;		for (; len>0 && cury<chanH;) {			byte color=_tmp[dpos++];			int x=((int)_tmp[dpos++]&0xFF);			x|=((int)_tmp[dpos++]&0xFF)<<8;			int rlen=((int)_tmp[dpos++]&0xFF);			rlen|=((int)_tmp[dpos++]&0xFF)<<8;			//System.out.println(color + " "+x + " "+rlen);			len--;			if (x < curx)				return false;						for (; curx < x; curx++)				_data[cury*width+curx]=0;						if (curx+rlen>width)				return false;						for (; rlen>0; rlen--, curx++)				_data[cury*width+curx]=color;			if (curx==width) {				cury++;				curx=0;			}		}		if(!readColorModel(in)) return false;		if(!_isConnected) return false;		isIndex=true;		return true;	}		public boolean readRegions(InputStream in, int chanW, int chanH) throws java.io.IOException {		//clear the _data array		for(int h=0; h<chanH; h++) {			for(int w =0; w<chanW; w++) {				_data[chanW*h+w]=0;			}		}  		int numColors=readInt(in);		if(!_isConnected) return false;		for(int curColor = 0; curColor < numColors; curColor++) {			int numRegions = readInt(in);			if(!_isConnected) return false;            			readBytes(_tmp,in,36*numRegions);			if(!_isConnected) return false;            				int dpos=0;			for (int i = 0; i<numRegions; i++) {				byte color= _tmp[dpos];				dpos +=4;				int x1 = byteToInt(_tmp,dpos);				dpos +=4;				int y1 = byteToInt(_tmp,dpos);				dpos +=4;				int x2 = byteToInt(_tmp,dpos);				dpos +=4;				int y2 = byteToInt(_tmp,dpos);				//The  data of the centroid, area and run_start are ignored				dpos +=20; //isn't nessescary, but now it nicely adds up to 36				if (  x1 > chanW || y1 > chanH || x2 > chanW || y2 > chanH							|| x1 > x2 || y1 > y2							|| x1 < 0 || x2 < 0 || y1 < 0 || y2 < 0							)					return false;								//Fill the data array with the bounding boxes..				//..the top and bottom lines				for (int tb = x1; tb <= x2; tb++) {					_data[y1*width+tb]=color;					_data[y2*width+tb]=color;				}				//..the left and right lines				for (int lr = y1; lr <= y2; lr++) {					_data[lr*width+x1]=color;					_data[lr*width+x2]=color;				}			}			readBytes(_tmp,in,12); //read out the min_area, total_area and merge_threshhold and ignore them:)		}		if(!readColorModel(in)) return false;		if(!_isConnected) return false;		isIndex=true;		return true;	}	public void connected(DatagramSocket UDPsocket, DatagramPacket incoming) {		_isConnected=true;		mysock = UDPsocket;		while(listeners==null) {			System.out.println("Assert: Bad race condition -- shouldn't be happening");			Thread.yield();		}		fireVisionUpdate();		try {			while(!mysock.isClosed()) {				in = new ByteArrayInputStream(incoming.getData());				String type = readLoadSaveString(in);				if(!_isConnected) break; //System.out.println("Got type="+type);				if(!type.equals("TekkotsuImage")) {					if(!type.equals("CloseConnection"))						System.err.println("Unrecognized type: "+type);					else {						System.out.println("Got Close connection packet");						_isConnected=false;					}					break;				}        fireConnected();				format=readInt(in);				if(!_isConnected) break; //System.out.println("Got format="+format);				compression=readInt(in);				if(!_isConnected) break; //System.out.println("Got compression="+compression);				int newWidth=readInt(in);				if(!_isConnected) break; //System.out.println("Got newWidth="+newWidth);				int newHeight=readInt(in);				if(!_isConnected) break; //System.out.println("Got newHeight="+newHeight);				long timest=readInt(in);				if(timest<0)					timest+=(1L<<32);				if(!_isConnected) break; //System.out.println("Got timest="+timest);				frameNum=readInt(in);				if(frameNum<0)					frameNum+=(1L<<32);				if(!_isConnected) break; //System.out.println("Got frameNum="+frameNum);								if (format!=oldformat || newWidth!=width || newHeight!=height) {					width=newWidth;					height=newHeight;					synchronized (_outd) {						switch (format) {						case ENCODE_COLOR:							channels=3;							pktSize=width*height*channels;							break;						case ENCODE_SINGLE_CHANNEL:							channels=1;							pktSize=width*height*channels;							break;						default:							System.err.println("VisionRawListener: unknown packet type "+format);							throw new java.lang.NoSuchFieldException("fake exception");						}						_data=new byte[pktSize];						_outd=new byte[pktSize];						_tmp=new byte[pktSize];						_jpeg=new byte[pktSize*2<2000?2000:pktSize*2];						_newjpeg=new byte[pktSize*2<2000?2000:pktSize*2];						_pixels=new int[width*height];;						img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);						oldformat=format;					}				}								boolean failed=false;				for(int i=0; i<channels; i++) {					String creator = readLoadSaveString(in);					if(!_isConnected) break; //System.out.println("Got creator="+creator);					if(!creator.equals("FbkImage")) {						System.err.println("Unrecognized creator: "+creator);						failed=true; break;					} else {						int chanwidth=readInt(in);						if(!_isConnected) break; //System.out.println("Got chanwidth="+chanwidth);						int chanheight=readInt(in);						if(!_isConnected) break; //System.out.println("Got chanheight="+chanheight);												if(chanwidth>width || chanheight>height) {							System.err.println("channel dimensions exceed image dimensions");							failed=true; break;						}												int layer=readInt(in);						if(!_isConnected) break; //System.out.println("Got layer="+layer);						chan_id=readInt(in);						if(!_isConnected) break; //System.out.println("Got chan_id="+chan_id);										String fmt=readLoadSaveString(in);						if(!_isConnected) break; //System.out.println("Got fmt="+fmt);						if(fmt.equals("blank")) {							isJPEG=false;							isIndex=false;							int useChan=(channels==1)?i:chan_id;							int off=useChan;							for(int y=0; y<height; y++)								for(int x=0; x<width; x++) {									_data[off]=(byte)(convertRGB?0x80:0);									off+=channels;								}						} else if(fmt.equals("RawImage")) {							isJPEG=false;							isIndex=false;							int useChan=(channels==1)?i:chan_id;							if(!readChannel(in,useChan,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener channel read failed"); break; }						} else if(fmt.equals("JPEGGrayscale")) {							isIndex=false;							int useChan=(channels==1)?i:chan_id;							if(!readJPEGChannel(in,useChan,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener JPEGGreyscale channel read failed"); break; }							isJPEG=(channels==1);						} else if(fmt.equals("JPEGColor")) {							isIndex=false;							if(format==ENCODE_SINGLE_CHANNEL)								System.err.println("WTF? ");							if(!readJPEG(in,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener JPEGColor channel read failed"); break; }							i=channels;							isJPEG=true;						} else if(fmt.equals("SegColorImage")) {							isJPEG=false;							isIndex=true;							if(!readIndexedColor(in,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener SegColor read failed"); break; }						} else if(fmt.equals("RLEImage")) {							isJPEG=false;							isIndex=true;							if(!readRLE(in,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener RLEImage read failed"); break; }						} else if(fmt.equals("RegionImage")) {							isJPEG=false;							isIndex=true;							if(!readRegions(in,chanwidth,chanheight)) { failed=true; System.err.println("UDPVisionListener RegionImage read failed"); break; }						} else {							isJPEG=false;							isIndex=false;							System.err.println("Unrecognized format: "+fmt);							failed=true; break;						}					}				}				if(failed || !_isConnected) {					System.err.println("UDPVisionListener connection lost");					break;				}								synchronized(_outd) {					byte[] temp=_data;					_data=_outd;					_outd=temp;					if(isJPEG) {						temp=_newjpeg;						_newjpeg=_jpeg;						_jpeg=temp;						int tempi=newjpegLen;						newjpegLen=jpegLen;						jpegLen=tempi;					}					timestamp=new Date(timest);				}				updatedFlag=true;				fireVisionUpdate();				mysock.receive(incoming);			}		} catch (Exception ex) {    } finally {      fireDisconnected();    }				try { mysock.close(); } catch (Exception ex) { }		if(!_isConnected) {			if(!destroy)				System.out.println("Waiting 5 seconds to reconnect");			try { Thread.sleep(5000); } catch (Exception ex) {}		}		_isConnected=false;		fireVisionUpdate();	}		public byte[] getData() {		synchronized (_outd) {			updatedFlag=false;			return _outd;		}	}	public void setConvertRGB(boolean b) { 		if(b!=convertRGB) {			convertRGB=b;			updatedFlag=true;		}	}	public boolean getConvertRGB() { return convertRGB; }	public int[] getYUVPixels() {		synchronized(_outd) {			byte[] data=getData();			int offset=0;			for (int i=0; i<width*height; i++) {				int y=(int)data[offset++]&0xFF;				int u=(int)data[offset++]&0xFF;				int v=(int)data[offset++]&0xFF;				_pixels[i]=(255<<24) | (y<<16) | (u<<8) | v;			}		}		return _pixels;	}	//This still uses RGB pixels just in case you want to display the	//intensity value into hues instead of black/white	public int[] getIntensityPixels() {		synchronized(_outd) {			byte[] data=getData();			int offset=0;			if(!getConvertRGB()) {				for (int i=0; i<width*height; i++) {					int z=(int)data[offset++]&0xFF;					_pixels[i]=(255<<24) | (z<<16) | (z<<8) | z;				}			} else if(chan_id==CHAN_Y || chan_id==CHAN_Y_DY || chan_id==CHAN_Y_DX || chan_id==CHAN_Y_DXDY ) {				for (int i=0; i<width*height; i++) {					int z=(int)data[offset++]&0xFF;					_pixels[i]=pixelYUV2RGB(z,0x80,0x80);				}			} else if(chan_id==CHAN_U) {				for (int i=0; i<width*height; i++) {					int z=(int)data[offset++]&0xFF;					_pixels[i]=pixelYUV2RGB(0x80,z,0x80);				}			} else if(chan_id==CHAN_V) {				for (int i=0; i<width*height; i++) {					int z=(int)data[offset++]&0xFF;					_pixels[i]=pixelYUV2RGB(0x80,0x80,z);				}			}		}				return _pixels;	}	public int[] getRGBPixels() {		synchronized(_outd) {			byte[] data=getData();			int offset=0;			for (int i=0; i<width*height; i++) {				int y=(int)data[offset++]&0xFF;				int u=(int)data[offset++]&0xFF;				int v=(int)data[offset++]&0xFF;				_pixels[i]=pixelYUV2RGB(y, u, v);			}		}		return _pixels;	}	static final int pixelYUV2RGB(int y, int u, int v) {		u=u*2-255;		v=v*2-255;		int r=y+u;		int b=y+v;		u=u>>1;		v=(v>>2)-(v>>4);		int g=y-u-v;		if (r<0) r=0; if (g<0) g=0; if (b<0) b=0;		if (r>255) r=255; if (g>255) g=255; if (b>255) b=255;		return (255<<24) | (r<<16) | (g<<8) | b;	}	public BufferedImage getImage() {		if(!updatedFlag)			return img;		if(isIndex) {			byte[] data=getData();			if(cmodel==null)				return img;			if(img.getWidth()!=width || img.getHeight()!=height || img.getType()!=BufferedImage.TYPE_BYTE_INDEXED)				img=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_INDEXED,cmodel);			img.getRaster().setDataElements(0,0,width,height,data);		} else {			updatedFlag=false;			int[] pix;			if(img.getWidth()!=width || img.getHeight()!=height || img.getType()!=BufferedImage.TYPE_BYTE_INDEXED)				img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);			if(format==ENCODE_COLOR)				pix=getConvertRGB()?getRGBPixels():getYUVPixels();			else				pix=getIntensityPixels();			img.setRGB(0,0,width,height,pix,0,width);		}		return img;	}	public UDPVisionListener() { super(); }	public UDPVisionListener(int port) { super(port); }	public UDPVisionListener(String host, int port) { super(host,port); }}
\ No newline at end of file
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionGUI.java ./tools/mon/org/tekkotsu/mon/VisionGUI.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionGUI.java	Fri Jan 21 18:31:39 2005
+++ ./tools/mon/org/tekkotsu/mon/VisionGUI.java	Fri Aug  5 15:44:23 2005
@@ -284,7 +284,11 @@
 				setTitle("TekkotsuMon: Vision Raw");
 				isRaw=true;
 				isRLE=false;
-			}
+			} else if(args[i].toUpperCase().compareTo("REG")==0 || args[i]==String.valueOf(VisionListener.defRegionPort)) {
+				setTitle("TekkotsuMon: Vision Regions");
+				isRaw=false;
+				isRLE=true; //It's not really an RLE window, but the options are the same, so whatever
+			} 
 		}
 		vision.setMinimumSize(new Dimension(VisionListener.DEFAULT_WIDTH/2, VisionListener.DEFAULT_HEIGHT/2));
 		vision.setPreferredSize(new Dimension(VisionListener.DEFAULT_WIDTH*2, VisionListener.DEFAULT_HEIGHT*2));
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionListener.java ./tools/mon/org/tekkotsu/mon/VisionListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/VisionListener.java	Fri Aug  5 15:44:23 2005
@@ -33,6 +33,8 @@
 	final static int DEFAULT_HEIGHT=144;
 	static int defRawPort=10011;
 	static int defRLEPort=10012;
+    //added this hardcoded region port, why is it variable in tekkotsu.cfg?
+    static int defRegionPort=10013;
 
 	public void addListener(VisionUpdatedListener l);
 	public void removeListener(VisionUpdatedListener l);
@@ -51,7 +53,7 @@
 	public byte[] getJPEG();
 	public int getJPEGLen();
 	
-	public byte[] getData();
+    public byte[] getData();
 	public void setConvertRGB(boolean b);
 	public boolean getConvertRGB();
 
@@ -65,6 +67,7 @@
 
 	public BufferedImage getImage();
 
+	public void needConnection();
 	public void startThread();
 	public void kill();
 	public void run();
@@ -74,3 +77,4 @@
 
 	public long getBytesRead(); 
 }
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionPanel.java ./tools/mon/org/tekkotsu/mon/VisionPanel.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionPanel.java	Fri Jan 21 18:31:39 2005
+++ ./tools/mon/org/tekkotsu/mon/VisionPanel.java	Fri Aug  5 17:25:42 2005
@@ -1,5 +1,7 @@
 package org.tekkotsu.mon;
 
+import org.tekkotsu.sketch.*;
+
 import javax.swing.JPanel;
 import java.awt.image.BufferedImage;
 import java.awt.Graphics;
@@ -10,11 +12,38 @@
 import java.awt.event.WindowAdapter;
 import java.awt.event.WindowEvent;
 
-public class VisionPanel extends JPanel implements VisionUpdatedListener {
-	BufferedImage _image;
-	VisionListener _listener;
-	boolean lockAspect=false;
-	float tgtAspect=-1;
+import java.awt.Rectangle;
+import java.awt.geom.*;
+import java.util.Vector;
+import java.awt.event.*;
+import javax.swing.Box;
+import javax.swing.JButton;
+import java.awt.image.IndexColorModel;
+import java.awt.BasicStroke;
+import java.awt.Graphics2D;
+
+public class VisionPanel extends JPanel implements VisionUpdatedListener, 
+                                                   MouseListener,
+						   MouseMotionListener
+{
+    boolean usingSketchGUI;
+
+    protected boolean windowHasFocus;
+    protected boolean crosshairsEnabled=false;
+    protected boolean idEnabled=false;
+    
+    protected BufferedImage _image;
+    protected VisionListener _listener;
+    boolean lockAspect=false;
+    float tgtAspect=-1;
+
+    SketchGUI gui;
+    //    boolean isCam;
+    int space;
+
+    int drawX, drawY, drawHeight, drawWidth;
+
+    protected int mouseX=-1, mouseY=-1;
 
 	public static void usage() {
 		System.out.println("Usage: java VisionPanel host [port|raw|rle] [udp|tcp]");
@@ -41,15 +70,22 @@
 		frame.getContentPane().add(vision);
 		frame.addWindowListener(new WindowAdapter() {
 				public void windowClosing(WindowEvent e) { System.exit(0); } });
+		//frame.show();
 		frame.setVisible(true);
 	}
 
 	public void setConvertRGB(boolean b) { _listener.setConvertRGB(b); }
 	public boolean getConvertRGB() { return _listener.getConvertRGB(); }
 
-	public VisionPanel(VisionListener listener) {
+    //	public VisionPanel(VisionListener listener, SketchGUI _gui, boolean _isCam) {
+	public VisionPanel(VisionListener listener, SketchGUI _gui, int _space) {
 		super();
 		init(listener);
+		gui = _gui;
+		//isCam = _isCam;
+		space = _space;
+		usingSketchGUI = true;
+		_listener.removeListener(this);
 	}
 	
 	public VisionPanel(String host, String[] args) {
@@ -61,6 +97,8 @@
 				port=VisionListener.defRLEPort;
 			} else if(args[i].toUpperCase().compareTo("RAW")==0) {
 				port=VisionListener.defRawPort;
+			} else if(args[i].toUpperCase().compareTo("REG")==0) {
+				port=VisionListener.defRegionPort;
 			} else if(args[i].toUpperCase().compareTo("UDP")==0) {
 				useUDP=true;
 			} else if(args[i].toUpperCase().compareTo("TCP")==0) {
@@ -98,26 +136,23 @@
 	}
 	
 	public void init(VisionListener listener) {
-		_listener=listener;
-		_listener.addListener(this);
-		setBackground(Color.BLACK);
-		setForeground(Color.WHITE);
-		setOpaque(!lockAspect);
-	}
-	
-	public VisionListener getListener() { return _listener; }
-	
-	public void close() {
-		_listener.kill();
-	}
-	
-	public void open() {
-		_listener.startThread();
+	    usingSketchGUI = false;
+	    setBackground(Color.BLACK);
+	    setForeground(Color.WHITE);
+	    setOpaque(!lockAspect);
+	    addMouseMotionListener(this);
+	    addMouseListener(this);
+	    windowHasFocus = true;
+	    crosshairsEnabled = false;
+	    _listener=listener;
+	    _listener.addListener(this);
 	}
 
-	public void visionUpdated(VisionListener l) {
-		repaint();
-	}
+   
+	public VisionListener getListener() { return _listener; }
+	public void close() { _listener.kill();	}
+	public void open() { _listener.needConnection(); }
+	public void visionUpdated(VisionListener l) { repaint(); }
 	
 	public void setLockAspectRatio(boolean b) {
 		if(b!=lockAspect) {
@@ -145,40 +180,88 @@
 		setAspectRatio(asp);
 	}
 	
-	public void paint(Graphics graphics) {
-		_image=_listener.getImage();
-		super.paint(graphics);
-		Dimension sz=getSize();
-		if(getLockAspectRatio()) {
-			float curasp=sz.width/(float)sz.height;
-			float tgtasp=getAspectRatio();
-			if(tgtasp<0)
-				tgtasp=_image.getWidth()/(float)_image.getHeight();
-			if(curasp>tgtasp) {
-				int width=(int)(sz.height*tgtasp);
-				drawImage(graphics,_image, (sz.width-width)/2, 0, width, sz.height);
-			} else if(curasp<tgtasp) {
-				int height=(int)(sz.width/tgtasp);
-				drawImage(graphics,_image, 0, (sz.height-height)/2, sz.width, height);
-			} else {
-				drawImage(graphics,_image, 0, 0, sz.width, sz.height);
-			}
-		} else
-			drawImage(graphics,_image, 0, 0, sz.width, sz.height);
-	}
-	
-	protected void drawImage(Graphics g, BufferedImage img, int x, int y, int w, int h) {
-		if(img!=null)
-			g.drawImage(img,x,y,w,h,null);
-		else {
-			g.setColor(getBackground());
-			g.fillRect(x,y,w,h);
-			FontMetrics tmp=g.getFontMetrics();
-			String msg="No image";
-			int strw=tmp.stringWidth(msg);
-			int strh=tmp.getHeight();
-			g.setColor(getForeground());
-			g.drawString(msg,(getSize().width-strw)/2,(getSize().height-strh)/2+tmp.getAscent());
-		}
+  public void paint(Graphics graphics) {
+      if (!usingSketchGUI) { _image=_listener.getImage(); }
+      super.paint(graphics);
+      Dimension sz=getSize();
+      drawX = 0;
+      drawY = 0;
+      drawWidth = sz.width;
+      drawHeight = sz.height;
+      // Scale image to fit the window size while maintaining aspect ratio.
+      // Center the image in the unused space if window width or height too large.
+      // Note: this only makes sense for cam space.
+      //      if (_image != null && getLockAspectRatio() && (!usingSketchGUI || isCam)) {
+      if (_image != null && getLockAspectRatio() && (!usingSketchGUI || space==1)) {
+	  float curasp=sz.width/(float)sz.height;
+	  float tgtasp=getAspectRatio();
+	  if(tgtasp<0)
+	      tgtasp=_image.getWidth()/(float)_image.getHeight();
+	  if(curasp>tgtasp) {
+	      drawWidth = (int)(sz.height*tgtasp);
+	      drawX = (sz.width-drawWidth)/2;
+	  } else if(curasp<tgtasp) {
+	      drawHeight = (int)(sz.width/tgtasp);
+	      drawY = (sz.height-drawHeight)/2;
+	  } else {
+	  }
+      }
+      drawImage(graphics, _image, drawX, drawY, drawWidth, drawHeight);
+      
+      // If requested, draw crosshairs for RawCam, SegCam, or cam sketchspace.
+      // Crosshairs for world sketchspace are handled in SketchPanel.java.
+      //      if (crosshairsEnabled && (!usingSketchGUI || isCam))
+      if (crosshairsEnabled && (!usingSketchGUI || space==1))
+	  {
+	      graphics.setXORMode(Color.GRAY);
+	      graphics.setColor(Color.WHITE);
+	      ((Graphics2D)graphics).setStroke(new BasicStroke(1.0f));
+	      graphics.drawLine(drawX+drawWidth/2,drawY, drawX+drawWidth/2, drawY+drawHeight);
+	      graphics.drawLine(drawX, drawY+drawHeight/2, drawX+drawWidth, drawY+drawHeight/2);
+	      graphics.setPaintMode();
+	  }
+  }
+
+    protected void drawImage(Graphics g, BufferedImage img, int x, int y, int w, int h) {
+	if(img!=null)
+	    g.drawImage(img,x,y,w,h,null);
+	else {
+	    g.setColor(getBackground());
+	    g.fillRect(x,y,w,h);
+	    FontMetrics tmp=g.getFontMetrics();
+	    String msg="No image";
+	    int strw=tmp.stringWidth(msg);
+	    int strh=tmp.getHeight();
+	    g.setColor(getForeground());
+	    g.drawString(msg,(getSize().width-strw)/2,(getSize().height-strh)/2+tmp.getAscent());
 	}
+    }
+
+    public void mouseDragged(MouseEvent e){}
+
+    public void mouseMoved(MouseEvent e)
+    {
+	// Update the mouse position in the corner
+	mouseX = e.getX() - drawX;
+	// mouseX *= _listener.DEFAULT_WIDTH*1.0/drawWidth;
+	mouseY = e.getY()-drawY;
+	// mouseY *= _listener.DEFAULT_HEIGHT*1.0/drawHeight;
+	repaint();
+    }
+    
+    public void mousePressed(MouseEvent e){}
+
+    public void mouseClicked(MouseEvent e){}
+
+    public void mouseReleased(MouseEvent e){}
+
+    public void mouseEntered(MouseEvent e){}
+
+    public void mouseExited(MouseEvent e)
+    {
+	mouseX = -1;
+	mouseY = -1;
+	repaint();
+    }
+
 }
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionUpdatedListener.java ./tools/mon/org/tekkotsu/mon/VisionUpdatedListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisionUpdatedListener.java	Fri Sep 26 00:36:21 2003
+++ ./tools/mon/org/tekkotsu/mon/VisionUpdatedListener.java	Thu Mar  3 17:53:54 2005
@@ -1,6 +1,7 @@
 package org.tekkotsu.mon;
-
-public interface VisionUpdatedListener {
-	public void visionUpdated(VisionListener comm);
-}
-
+
+public interface VisionUpdatedListener {
+	public void visionUpdated(VisionListener comm);
+}
+
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisualObjectInfo.java ./tools/mon/org/tekkotsu/mon/VisualObjectInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/VisualObjectInfo.java	Thu Apr 22 18:46:02 2004
+++ ./tools/mon/org/tekkotsu/mon/VisualObjectInfo.java	Wed Dec 31 19:00:00 1969
@@ -1,46 +0,0 @@
-package org.tekkotsu.mon;
-
-import java.awt.Graphics2D;
-import javax.swing.Icon;
-import javax.swing.ImageIcon;
-
-// stores info for a VisualObject
-public class VisualObjectInfo {
-	static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/unknown.png");
-//	int portnum; //! the port number this object will be serialized over
-	int id;
-	int parentId;
-	String name;
-
-	public VisualObjectInfo(int _id, int _parentId, String _name){
-//		portnum = _portnum;
-		id = _id;
-		parentId = _parentId;
-		name = _name;
-	}
-
-//	public int getPortNum() { return portnum; }
-	public int getId() { return id; }
-	public int getParentId() { return parentId; }
-	public String getName() { return name; }
-
-	// returns left-most coordinate of object
-	public float getLeft() { return 0; }
-	// returns right-most coordinate of object
-	public float getRight() { return 176; }
-	// returns top-most coordinate of object
-	public float getTop() { return 0; }
-	// returns bottom-most coordinate of object
-	public float getBottom() { return 144; }
-
-	public int getColor() { return 0; } // returning 0 by default
-
-	public String toString() {
-		return (name + "(id " + id + ", parentId " + parentId + ")");
-	}
-
-	public Icon getIcon() { return icon; }
-
-	public void renderTo(Graphics2D graphics) { }
-}
-
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WM2DMListener.java ./tools/mon/org/tekkotsu/mon/WM2DMListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WM2DMListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/WM2DMListener.java	Wed Jun  8 17:05:03 2005
@@ -65,7 +65,7 @@
   }
 
   // Constructors
-  public WM2DMListener() { super(); }
-  public WM2DMListener(int port) { super(port); }
-  public WM2DMListener(String host, int port) { super(host, port); }
+  public WM2DMListener() { super(); needConnection(); }
+  public WM2DMListener(int port) { super(port); needConnection(); }
+  public WM2DMListener(String host, int port) { super(host, port); needConnection(); }
 }
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WM2FSListener.java ./tools/mon/org/tekkotsu/mon/WM2FSListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WM2FSListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/WM2FSListener.java	Wed Jun  8 17:05:01 2005
@@ -80,7 +80,7 @@
   }
 
   // Constructors
-  public WM2FSListener() { super(); }
-  public WM2FSListener(int port) { super(port); }
-  public WM2FSListener(String host, int port) { super(host, port); }
+  public WM2FSListener() { super(); needConnection(); }
+  public WM2FSListener(int port) { super(port); needConnection(); }
+  public WM2FSListener(String host, int port) { super(host, port); needConnection(); }
 }
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WM2HMListener.java ./tools/mon/org/tekkotsu/mon/WM2HMListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WM2HMListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/WM2HMListener.java	Wed Jun  8 17:05:03 2005
@@ -66,7 +66,7 @@
   }
 
   // Constructors
-  public WM2HMListener() { super(); }
-  public WM2HMListener(int port) { super(port); }
-  public WM2HMListener(String host, int port) { super(host, port); }
+  public WM2HMListener() { super(); needConnection(); }
+  public WM2HMListener(int port) { super(port); needConnection(); }
+  public WM2HMListener(String host, int port) { super(host, port); needConnection(); }
 }
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WatchableMemory.java ./tools/mon/org/tekkotsu/mon/WatchableMemory.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WatchableMemory.java	Fri Jan 21 18:31:39 2005
+++ ./tools/mon/org/tekkotsu/mon/WatchableMemory.java	Wed Jun  8 17:05:01 2005
@@ -57,6 +57,7 @@
 		WatchableMemoryListener listener;
 		listenThread(WatchableMemory gui,WatchableMemoryListener listener) { this.gui=gui; this.listener=listener;}
 		public void run() { 
+			listener.needConnection();
 			try {
 				while (true) {
 					if (listener.isConnected()) {
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WorldStateJointsListener.java ./tools/mon/org/tekkotsu/mon/WorldStateJointsListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WorldStateJointsListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/WorldStateJointsListener.java	Wed Jun  8 17:05:01 2005
@@ -68,7 +68,7 @@
     return _isConnected;
   }
 
-  public WorldStateJointsListener() { super(); }
-  public WorldStateJointsListener(int port) { super(port); }
-  public WorldStateJointsListener(String host, int port) { super(host,port); }
+  public WorldStateJointsListener() { super(); needConnection(); }
+  public WorldStateJointsListener(int port) { super(port); needConnection(); }
+  public WorldStateJointsListener(String host, int port) { super(host,port); needConnection(); }
 }
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WorldStatePIDsListener.java ./tools/mon/org/tekkotsu/mon/WorldStatePIDsListener.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/WorldStatePIDsListener.java	Fri Nov 12 17:07:40 2004
+++ ./tools/mon/org/tekkotsu/mon/WorldStatePIDsListener.java	Wed Jun  8 17:05:01 2005
@@ -55,7 +55,7 @@
     return _isConnected;
   }
 
-  public WorldStatePIDsListener() { super(); }
-  public WorldStatePIDsListener(int port) { super(port); }
-  public WorldStatePIDsListener(String host, int port) { super(host,port); }
+  public WorldStatePIDsListener() { super(); needConnection(); }
+  public WorldStatePIDsListener(int port) { super(port); needConnection(); }
+  public WorldStatePIDsListener(String host, int port) { super(host,port); needConnection(); }
 }
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Entries ./tools/mon/org/tekkotsu/mon/icons/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/icons/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,11 @@
+/agent.png/1.1/Thu Apr 22 22:46:08 2004//Ttekkotsu-2_4
+/ellipse.png/1.1/Thu Apr 22 22:46:08 2004//Ttekkotsu-2_4
+/ellipseinv.png/1.2/Thu Apr  7 20:44:50 2005/-kb/Ttekkotsu-2_4
+/line.png/1.1/Thu Apr 22 22:46:08 2004//Ttekkotsu-2_4
+/lineinv.png/1.1/Thu Mar 31 21:57:00 2005/-kb/Ttekkotsu-2_4
+/sketch.png/1.3/Thu Apr  7 20:44:50 2005//Ttekkotsu-2_4
+/sketchint.png/1.2/Thu Apr  7 20:44:50 2005/-kb/Ttekkotsu-2_4
+/sketchintinv.png/1.2/Thu Apr  7 20:44:50 2005/-kb/Ttekkotsu-2_4
+/sketchinv.png/1.2/Thu Apr  7 20:44:50 2005/-kb/Ttekkotsu-2_4
+/unknown.png/1.1/Thu Apr 22 22:46:08 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Repository ./tools/mon/org/tekkotsu/mon/icons/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/icons/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/org/tekkotsu/mon/icons
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Root ./tools/mon/org/tekkotsu/mon/icons/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/icons/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Tag ./tools/mon/org/tekkotsu/mon/icons/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/mon/icons/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
Binary files ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/ellipseinv.png and ./tools/mon/org/tekkotsu/mon/icons/ellipseinv.png differ
Binary files ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/lineinv.png and ./tools/mon/org/tekkotsu/mon/icons/lineinv.png differ
Binary files ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/sketch.png and ./tools/mon/org/tekkotsu/mon/icons/sketch.png differ
Binary files ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/sketchint.png and ./tools/mon/org/tekkotsu/mon/icons/sketchint.png differ
Binary files ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/sketchintinv.png and ./tools/mon/org/tekkotsu/mon/icons/sketchintinv.png differ
Binary files ../Tekkotsu_2.3/tools/mon/org/tekkotsu/mon/icons/sketchinv.png and ./tools/mon/org/tekkotsu/mon/icons/sketchinv.png differ
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/AgentShapeInfo.java ./tools/mon/org/tekkotsu/sketch/AgentShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/AgentShapeInfo.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/AgentShapeInfo.java	Tue Jun 21 05:16:10 2005
@@ -0,0 +1,41 @@
+package org.tekkotsu.sketch;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+
+public class AgentShapeInfo extends ShapeInfo {
+	static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/agent.png");
+	float orientation; // orientation of agent
+
+	public AgentShapeInfo(int _id, int _parentId, String _name, Color _color,
+			float _centroidx, float _centroidy, float _centroidz,
+			float _orientation) {
+		super(_id, _parentId, _name, _color, _centroidx,_centroidy, _centroidz);
+		orientation = _orientation;
+	}
+
+	// returns left-most coordinate of object (want some buffer)
+	public float getLeft() { return centroidx-2; }
+	// returns right-most coordinate of object
+	public float getRight() { return centroidx+2; }
+	// returns top-most coordinate of object
+	public float getTop() { return centroidy-2; }
+	// returns bottom-most coordinate of object
+	public float getBottom() { return centroidy+2; }
+
+	public String toString() {
+		return (super.toString() + "(orientation " + orientation + ")");
+	}	
+	
+	public Icon getIcon() { return icon; }
+
+	public void renderTo(Graphics2D graphics) {
+		graphics.drawOval((int)(getCentroidX()+1),
+			(int)(getCentroidY()+1), 5, 5);
+	}
+
+	public float getOrientation() { return orientation; }
+}
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Entries ./tools/mon/org/tekkotsu/sketch/CVS/Entries
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,10 @@
+/AgentShapeInfo.java/1.2/Tue Jun 21 09:16:10 2005//Ttekkotsu-2_4
+/EllipseShapeInfo.java/1.8/Sat Aug  6 01:07:38 2005//Ttekkotsu-2_4
+/LineShapeInfo.java/1.6/Sat Aug  6 01:07:38 2005//Ttekkotsu-2_4
+/ShapeInfo.java/1.3/Sat Jun 18 08:48:20 2005//Ttekkotsu-2_4
+/SketchGUI.java/1.10/Fri Aug  5 21:26:57 2005//Ttekkotsu-2_4
+/SketchInfo.java/1.5/Sun Jun 19 12:56:21 2005//Ttekkotsu-2_4
+/SketchPanel.java/1.17/Fri Aug  5 21:26:57 2005//Ttekkotsu-2_4
+/SphereShapeInfo.java/1.1/Sat Aug  6 01:04:58 2005//Ttekkotsu-2_4
+/VisualObjectInfo.java/1.3/Mon May 23 06:27:18 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Repository ./tools/mon/org/tekkotsu/sketch/CVS/Repository
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/mon/org/tekkotsu/sketch
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Root ./tools/mon/org/tekkotsu/sketch/CVS/Root
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Tag ./tools/mon/org/tekkotsu/sketch/CVS/Tag
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/EllipseShapeInfo.java ./tools/mon/org/tekkotsu/sketch/EllipseShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/EllipseShapeInfo.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/EllipseShapeInfo.java	Fri Aug  5 21:07:38 2005
@@ -0,0 +1,75 @@
+package org.tekkotsu.sketch;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics2D;
+import java.awt.Graphics;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import java.awt.Rectangle;
+import java.awt.geom.*;
+import java.awt.BasicStroke;
+
+// stores info for a EllipseShape
+// note that ellipse center is same as centroid
+public class EllipseShapeInfo extends ShapeInfo {
+    static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/ellipse.png");
+    static Icon inv_icon = new ImageIcon("org/tekkotsu/mon/icons/ellipseinv.png");
+    float semimajor, semiminor; // length of semimajor axes
+    float orientation; // orientation of principal axis
+    int id;
+
+	public EllipseShapeInfo(int _id, int _parentId, String _name, Color _color,
+			float _centroidx, float _centroidy, float _centroidz,
+			float _semimajor, float _semiminor,
+			float _orientation) {
+		super(_id, _parentId, _name, _color, _centroidx, _centroidy, _centroidz);
+		semimajor = _semimajor;
+		semiminor = _semiminor;
+		orientation = _orientation;
+		id = _id;
+	}
+
+	// returns left-most coordinate of object
+	public float getLeft() { return centroidx-semimajor; }
+	// returns right-most coordinate of object
+	public float getRight() { return centroidx+semimajor; }
+	// returns top-most coordinate of object
+	public float getTop() { return centroidy-semiminor; }
+	// returns bottom-most coordinate of object
+	public float getBottom() { return centroidy+semiminor; }
+
+
+	public String toString() {
+		return (super.toString() + " center=(" + centroidx + "," + centroidy + "," + centroidz + ")"
+			+ " smaj=" + semimajor 
+			+ ", smin=" + semiminor 
+			+ ", orient=" + orientation);
+	}
+
+	public Icon getIcon() { 
+	    if (inverted)
+		return inv_icon;
+	    return icon; 
+	}
+
+	// rough rendering which doesn't take ellipse orientation into account
+        // maybe do a hack-ish check if abs(orientation) more than pi/4?
+    public void renderTo(Graphics2D graphics) {
+	// System.out.println("Drawing ellipse");
+
+	graphics.setStroke(new BasicStroke(1.0f));
+
+	// for proper orientation, rotate the coordinate because we cannot rotate the oval itself
+	graphics.transform(AffineTransform.getRotateInstance(getOrientation(), getCentroidX(), getCentroidY())); // forward rotation
+	graphics.drawOval((int)(getCentroidX()-semimajor+1), 
+			  (int)(getCentroidY()-semiminor+1),
+			  (int)(semimajor*2), (int)(semiminor*2));
+	graphics.transform(AffineTransform.getRotateInstance(-getOrientation(), getCentroidX(), getCentroidY())); // backward rotation
+    }
+
+	public float getSemiMajor() { return semimajor; }
+	public float getSemiMinor() { return semiminor; }
+	public float getOrientation() { return orientation; }
+}
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/LineShapeInfo.java ./tools/mon/org/tekkotsu/sketch/LineShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/LineShapeInfo.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/LineShapeInfo.java	Fri Aug  5 21:07:38 2005
@@ -0,0 +1,78 @@
+package org.tekkotsu.sketch;
+
+import java.awt.Graphics2D;
+import java.awt.Graphics;
+import java.awt.Color;
+import java.awt.Font;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import java.awt.Rectangle;
+import java.awt.geom.*;
+import java.awt.BasicStroke;
+
+// stores info for a LineShape
+public class LineShapeInfo extends ShapeInfo {
+	static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/line.png");
+	static Icon inv_icon = new ImageIcon("org/tekkotsu/mon/icons/lineinv.png");
+	// x/y coordinates of endpoints, with variances
+	float e1x, e1y, e1v;
+	float e2x, e2y, e2v;
+	float r, theta;
+
+	public LineShapeInfo(int _id, int _parentId, String _name, Color _color,
+			float _centroidx, float _centroidy, float _centroidz,
+			float _e1x, float _e1y, float _e1v, 
+			float _e2x, float _e2y, float _e2v,
+			float _r, float _theta) {
+		
+		super(_id, _parentId, _name, _color, _centroidx, _centroidy, _centroidz);
+		e1x = _e1x;
+		e1y = _e1y;
+		e1v = _e1v;
+		e2x = _e2x;
+		e2y = _e2y;
+		e2v = _e2v;
+		r = _r;
+		theta = _theta;
+	}
+	
+	// returns left-most coordinate of object
+	public float getLeft() { return java.lang.Math.min(e1x,e2x); }
+	// returns right-most coordinate of object
+	public float getRight() { return java.lang.Math.max(e1x,e2x); }
+	// returns top-most coordinate of object
+	public float getTop() { return java.lang.Math.min(e1y,e2y); }
+	// returns bottom-most coordinate of object
+	public float getBottom() { return java.lang.Math.max(e1y,e2y); }
+
+	public String toString() {
+		return (super.toString()
+			+ " (" + e1x + "," + e1y + "," + e1v + ")---(" + e2x + "," + e2y + "," + e2v + ")  "
+			+ "r=" + r + " theta=" + theta); }
+			//				+ "(e1x " +e1x + ", e1y " + e1y + ", e1v " + e1v 
+			//+ ", e2x " +e2x + ", e2y " + e2y + ", e2v " + e2v 
+			//+ ", r " + r + ", theta " + theta + ")");	}
+
+	public Icon getIcon() { 
+	    if (inverted)
+		return inv_icon;
+	    return icon; 
+	}
+
+	public void renderTo(Graphics2D graphics) {
+		graphics.drawLine((int)e1x,(int)e1y,(int)e2x,(int)e2y);
+		// draw circles for variance
+		graphics.drawOval((int)e1x,(int)e1y,(int)(e1v/2),(int)(e1v/2));
+		graphics.drawOval((int)e2x,(int)e2y,(int)(e2v/2),(int)(e2v/2));
+	}
+
+	public float getE1X() { return e1x; }
+	public float getE1Y() { return e1y; }
+	public float getE1V() { return e1v; }
+	public float getE2X() { return e2x; }
+	public float getE2Y() { return e2y; }
+	public float getE2V() { return e2v; }
+	public float getR() { return r; }
+	public float getTheta() { return theta; }
+}
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/ShapeInfo.java ./tools/mon/org/tekkotsu/sketch/ShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/ShapeInfo.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/ShapeInfo.java	Sat Jun 18 04:48:20 2005
@@ -0,0 +1,47 @@
+package org.tekkotsu.sketch;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.Graphics;
+import java.awt.Rectangle;
+import java.awt.geom.*;
+
+// stores info for a Shape, to use as UserObject for DefaultMutableTreeNode
+
+public class ShapeInfo extends VisualObjectInfo {
+	float centroidx, centroidy, centroidz;
+
+    public ShapeInfo(int _id, int _parentId, String _name, Color _color,
+			float _centroidx, float _centroidy, float _centroidz) {
+		super(_id, _parentId, _name, _color);
+		centroidx = _centroidx;
+		centroidy = _centroidy;
+		centroidz = _centroidz;
+	}
+
+	public String toString() {
+	    //		return (super.toString() + "(color " + color + ",cx " + centroidx + ", cy " + centroidy
+	    //			+ ", cz " + centroidz + ")");
+	    return (super.toString() + "[" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + "]");
+	}
+
+	// if no specific renderer defined, just plot a point at centroid
+	public void renderTo(Graphics2D graphics) {
+    		graphics.setColor(color);
+		graphics.drawOval((int)centroidx,(int)centroidy,5,5);
+	}
+
+    public void renderTo(Graphics graphics, Rectangle2D.Double r)
+    {
+	double xscale = r.width;
+	double yscale = r.height;
+	graphics.setColor(color);
+	graphics.drawOval((int)(centroidx*xscale+r.x),(int)(centroidy*yscale+r.y),(int)(5*xscale),(int)(5*yscale));	
+    }
+
+	public float getCentroidX() { return centroidx; }
+	public float getCentroidY() { return centroidy; }
+	public float getCentroidZ() { return centroidz; }
+}
+
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SketchGUI.java ./tools/mon/org/tekkotsu/sketch/SketchGUI.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SketchGUI.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/SketchGUI.java	Fri Aug  5 17:26:57 2005
@@ -0,0 +1,882 @@
+package org.tekkotsu.sketch;
+
+import org.tekkotsu.mon.*;
+
+import java.awt.event.*;
+import javax.swing.*;
+import javax.swing.tree.*;
+import javax.swing.event.*;
+import java.lang.String;
+import java.awt.*;
+import javax.imageio.ImageIO;
+import java.awt.geom.AffineTransform;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.util.Date;
+import java.util.Vector;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.Comparator;
+import java.io.PrintWriter;
+import java.io.FileOutputStream;
+import java.util.prefs.Preferences;
+import java.io.File;
+import java.net.*;
+import java.io.*;
+import java.util.StringTokenizer;
+import java.awt.geom.*;
+
+
+
+public class SketchGUI extends JFrame implements ActionListener,
+						 TreeSelectionListener,
+						 VisionUpdatedListener,
+						 MouseListener
+{
+    //    boolean isCam; // true if this GUI is displaying a camera space (not world)
+    int space;
+
+    JFrame sketchFrame;
+    SketchPanel sketchPanel;
+    JButton rescaleBut;
+    JButton refreshListBut;
+
+    JTree sketchTree = null;
+    DefaultMutableTreeNode root;
+    JLabel status;
+    float mspf=0;
+    float mspfGamma = 0.9f;
+    String state="";
+    String host;
+    int listingPort;
+    int sketchPort;
+    static Preferences prefs = Preferences.userNodeForPackage(SketchGUI.class);
+
+    // the socket over which listings are retrieved and Sketch commands are sent
+    Socket listingSocket=null;
+    PrintWriter netout = null; // network output
+    BufferedReader netin = null; // network input
+
+    VisionListener listener;
+
+    PopupMenu popMenu;
+    VisualObjectInfo currentMenuObject;
+
+    Vector sketchStack;
+    BufferedImage img;
+    boolean imageNeedsUpdate;
+    TreeSelectionEvent lastEvent = null;
+
+    SketchPanel curSketchPanel;
+
+    public static void main(String args[]) {
+	if(args.length<4)
+	     usage();
+
+	int _listingPort = Integer.parseInt(args[2]);
+	int _sketchPort = Integer.parseInt(args[3]);
+	
+	//	boolean _isCam = args[1].equals("cam");
+	int _space = args[1].equals("cam") ? 1 : (args[1].equals("local") ? 2 : 3);
+	//	SketchGUI gui = new SketchGUI(args[0], _listingPort, _sketchPort, _isCam);
+	SketchGUI gui = new SketchGUI(args[0], _listingPort, _sketchPort, _space);
+	gui.addWindowListener(new WindowAdapter() {
+		 public void windowClosing(WindowEvent e) {System.exit(0);}});
+	gui.setVisible(true);
+    }
+
+    public static void usage() {
+	System.out.println("Usage: java org/tekkotsu/mon/SketchGUI host [cam/world] listport sketchport");
+	System.exit(2);
+    }
+
+    public void actionPerformed(ActionEvent e) {
+	try {
+	    if(e.getActionCommand().compareTo("rescale")==0)
+		rescaleAction();
+	    else if(e.getActionCommand().compareTo("refreshlist")==0)
+		refreshlistAction();
+	}
+	catch(IOException ioe) {
+	    System.err.println("Transfer error");
+	    reconnect();
+	    actionPerformed(e);
+	}
+    }
+
+    public void rescaleAction() {
+	// reset bounds **** THIS CODE ASSUMES ERS-2XX CAMERA DIMENSIONS; SHOULD FIX
+	sketchPanel.leftBound = 0;
+	sketchPanel.rightBound = 176;
+	sketchPanel.topBound = 0;
+	sketchPanel.bottomBound = 144;
+	TreePath[] paths = sketchTree.getSelectionPaths();
+	if(paths!=null) {
+	    for (int path_i = 0; path_i < paths.length; path_i++) {
+		DefaultMutableTreeNode node 
+		    =(DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
+		
+		if (node == root) continue;
+		if(!(node.getUserObject() instanceof VisualObjectInfo)) {
+		    System.out.println("rescaleAction:: placeholder text can't be selected");
+		    continue;
+		}
+		
+		VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
+		sketchPanel.scaleToVisualObject(vinfo);
+		if (vinfo instanceof SketchInfo)
+		    {
+			((SketchInfo)vinfo).unloadImage();
+		    }
+	    }
+	}
+	valueChanged(null); // redraw
+    }
+
+    public void refreshlistAction() throws IOException {
+	// send command to refresh the sketch tree list
+	if(netout==null)
+	    reconnect();
+	if(netout==null)
+	    return;
+	root.removeAllChildren();
+	sketchStack = new Vector();
+	
+	// reset bounds **** THIS CODE ASSUMES ERS-2XX CAMERA DIMENSIONS; SHOULD FIX
+	sketchPanel.leftBound = 0;
+	sketchPanel.rightBound = 176;
+	sketchPanel.topBound = 0;
+	sketchPanel.bottomBound = 144;
+	
+	// read in new sketch/shape list
+	netout.println("list");
+	String inputLine;
+	System.out.println(inputLine = readLine());
+	while((inputLine=readLine()).compareTo("list end") != 0) {
+	    // parse type (sketch or shape)	
+	    StringTokenizer st = new StringTokenizer(inputLine,": ");
+	    String type = st.nextToken();
+	    
+	    // parse id
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    int id = Integer.parseInt(st.nextToken());
+	    
+	    //parse parentId
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    int parentId = Integer.parseInt(st.nextToken());
+	    
+	    // parse name
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,":\r\n");
+	    st.nextToken();
+	    String name = st.nextToken();
+	    
+	    // parse sketch or shape subtype
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    int subtype = Integer.parseInt(st.nextToken());
+	    System.out.println(type+"type:" + subtype);
+	    
+	    // parse color
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    Color color = new Color( Integer.parseInt(st.nextToken()),
+				     Integer.parseInt(st.nextToken()),
+				     Integer.parseInt(st.nextToken()));
+	    System.out.println("color: " + color);
+	    
+	    // create node
+	    System.out.println(type + " id:"+id+"parentId:"+parentId+"name:"+name);
+	    VisualObjectInfo oinfo;
+	    if(type.equals("sketch")) 
+		oinfo =  new SketchInfo(id, parentId, name, color, subtype);
+	    else if (type.equals("shape"))
+		oinfo = parseShape(id, parentId, name, color, subtype);
+	    else {
+		System.out.println("Invalid type!");
+		color = new Color(0);
+		oinfo = new VisualObjectInfo(id, parentId, name, color);
+	    }
+	    
+	    //	    if (!isCam) sketchPanel.scaleToVisualObject(oinfo);
+	    if (space != 1) sketchPanel.scaleToVisualObject(oinfo);
+	    
+	    DefaultMutableTreeNode newnode = new DefaultMutableTreeNode(oinfo);
+	    root.add(newnode);
+	    
+	    sketchTree.updateUI();
+	}
+
+	// pair children with parents
+	DefaultMutableTreeNode curNode;
+	Vector allnodes = new Vector();
+	Enumeration nodeEn = root.preorderEnumeration();
+	while(nodeEn.hasMoreElements()){
+	    allnodes.add(nodeEn.nextElement());
+	}
+	for (int i=0; i<allnodes.size(); i++)
+	    {
+		curNode = (DefaultMutableTreeNode)(allnodes.elementAt(i));
+		DefaultMutableTreeNode potentialParent = root;
+		while((potentialParent = potentialParent.getNextNode()) != null) {
+		    
+		    if (curNode != root)
+			{
+			    if(((VisualObjectInfo)(curNode.getUserObject())).parentId == 
+			       ((VisualObjectInfo)(potentialParent.getUserObject())).id && 
+			       !potentialParent.isNodeAncestor(curNode)) {
+				potentialParent.add(curNode);
+				break;
+			    }
+			}
+		}
+		
+	    }
+	sortTree(root);
+	
+	// display the first sketch
+	SketchInfo firstinfo = (SketchInfo)(((DefaultMutableTreeNode)(root.getFirstChild())).getUserObject());
+	netout.println("get "+firstinfo.getId());
+	while((inputLine=readLine()).compareTo("get end") != 0) {
+	    System.out.println(inputLine);
+	}	
+	
+	System.out.println(inputLine);
+	for (int i = 0; i < sketchTree.getRowCount(); i++) {
+	    sketchTree.expandRow(i);
+	}
+	sketchTree.clearSelection();
+	sketchTree.updateUI();
+    }
+    
+    public VisualObjectInfo parseShape(int id, int parentId, String name, Color color, int shapetype) 
+	throws IOException
+    {
+	String inputLine;
+	StringTokenizer st;
+    
+	inputLine = readLine();
+	st = new StringTokenizer(inputLine,": ");
+	st.nextToken();
+	float cx = Float.parseFloat(st.nextToken());
+	float cy = Float.parseFloat(st.nextToken());
+	float cz = Float.parseFloat(st.nextToken());
+	System.out.println("cxyz:" +cx+" "+cy+" "+cz);
+    
+	if(shapetype == 1) { // lineshape
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    float e1x = Float.parseFloat(st.nextToken());
+	    float e1y = Float.parseFloat(st.nextToken());
+	    float e1v = Float.parseFloat(st.nextToken());
+	    System.out.println("e1xyv:"+e1x+" "+e1y +" "+e1v);
+	    
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    float e2x = Float.parseFloat(st.nextToken());
+	    float e2y = Float.parseFloat(st.nextToken());
+	    float e2v = Float.parseFloat(st.nextToken());
+	    System.out.println("e1xyv:"+e1x+" "+e1y +" "+e1v);
+	    
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    float r = Float.parseFloat(st.nextToken());
+	    System.out.println("r:"+r);
+	    
+	    inputLine = readLine();
+	    st = new StringTokenizer(inputLine,": ");
+	    st.nextToken();
+	    float theta = Float.parseFloat(st.nextToken());
+	    System.out.println("theta:"+theta);
+	    
+	    return new LineShapeInfo(id, parentId, name, color,
+				     cx,cy,cz, e1x, e1y, e1v, e2x, e2y, e2v, r, theta);
+	
+    } else if(shapetype == 2) { // ellipseshape
+	inputLine = readLine();
+	st = new StringTokenizer(inputLine,": ");
+	st.nextToken();
+	float semimajor = Float.parseFloat(st.nextToken());
+	float semiminor = Float.parseFloat(st.nextToken());
+	System.out.println("axes:"+semimajor+" "+semiminor);
+	
+	inputLine = readLine();
+	st = new StringTokenizer(inputLine,": ");
+	st.nextToken();
+	float orientation = Float.parseFloat(st.nextToken());
+	System.out.println("orientation:"+orientation);
+	
+	return new EllipseShapeInfo(id,parentId,name,color,
+				     cx,cy,cz, semimajor, semiminor, orientation);
+	
+    } else if (shapetype == 4) { // agentshape
+	inputLine = readLine();
+	st = new StringTokenizer(inputLine,": ");
+	st.nextToken();
+	float orientation = Float.parseFloat(st.nextToken());
+	System.out.println("orientation:"+orientation);
+	
+	return new AgentShapeInfo(id,parentId, name, color,
+				   cx,cy,cz, orientation);
+    } else if (shapetype == 5) { // sphereshape
+	inputLine = readLine();
+	st = new StringTokenizer(inputLine,": ");
+	st.nextToken();
+	float radius = Float.parseFloat(st.nextToken());
+	System.out.println("radius:"+radius);
+	
+	return new SphereShapeInfo(id,parentId,name,color,cx,cy,cz,radius);
+    } else {
+	System.out.println("Invalid shape!");
+	return new ShapeInfo(id, parentId, name, color, cx, cy, cz);
+    }
+}
+
+public SketchGUI(String host, int _listingPort, int _sketchPort, 
+		 //		 boolean _isCam) {
+		 int _space) {
+    super();
+    this.host = host;
+    this.listingPort = _listingPort;
+    this.sketchPort = _sketchPort;
+    //    this.isCam = _isCam;
+    this.space = _space;
+    
+    //    if(isCam)
+    if(space == 1)
+	root = new DefaultMutableTreeNode("camspace");
+    else if (space == 2)
+	root = new DefaultMutableTreeNode("localspace");
+    else
+	root = new DefaultMutableTreeNode("worldspace");
+
+    img = new BufferedImage(VisionListener.DEFAULT_WIDTH, VisionListener.DEFAULT_HEIGHT, BufferedImage.TYPE_INT_RGB);
+    Graphics2D g = img.createGraphics();
+    // g.setBackground(Color.GRAY);
+    g.clearRect(0,0,VisionListener.DEFAULT_WIDTH, VisionListener.DEFAULT_HEIGHT);
+    sketchStack = new Vector();
+    
+    init();
+    
+    // network setup
+    reconnect();
+}
+	
+    public void init() {
+
+	int strutsize=10;
+	int sepsize=5;
+	getContentPane().setLayout(new BorderLayout());
+	getContentPane().add(Box.createVerticalStrut(strutsize),BorderLayout.NORTH);
+	getContentPane().add(Box.createHorizontalStrut(strutsize),BorderLayout.WEST);
+	getContentPane().add(Box.createHorizontalStrut(strutsize),BorderLayout.EAST);
+		
+	//	setTitle("TekkotsuMon: "+(isCam ? "Cam" : "World")+" Space");
+	setTitle("TekkotsuMon: "+((space==1) ? "Cam" : ((space==2) ? "Local" : "World"))+" Space");
+	listener = new TCPVisionListener(host, sketchPort);
+	//	sketchPanel = new SketchPanel(this, listener, isCam, prefs);
+	sketchPanel = new SketchPanel(this, listener, space, prefs);
+	sketchPanel.setMinimumSize(new Dimension(VisionListener.DEFAULT_WIDTH/2, VisionListener.DEFAULT_HEIGHT/2));
+	sketchPanel.setPreferredSize(new Dimension(VisionListener.DEFAULT_WIDTH*2, VisionListener.DEFAULT_HEIGHT*2));
+	sketchPanel.setLockAspectRatio(true);
+
+	curSketchPanel = sketchPanel;
+	//	sketchPanel.makeSketchFrame(sketchPanel, isCam ? "Cam" : "World");
+	sketchPanel.makeSketchFrame(sketchPanel, (space==1) ? "Cam" : ((space==2) ? "Local" : "World"));
+	{
+
+	    Box tmp1 = Box.createHorizontalBox();
+	    tmp1.add(Box.createHorizontalStrut(strutsize));
+	    {		Box tmp2 = Box.createVerticalBox();
+
+		tmp2.add(Box.createVerticalStrut(strutsize));
+
+		{
+		    Box tmp3 = Box.createHorizontalBox();
+		    tmp3.add(status=new JLabel(state));
+		    tmp3.add(Box.createHorizontalGlue());
+
+		    tmp3.add(Box.createHorizontalStrut(strutsize));
+		
+		    rescaleBut = new JButton("Rescale the Image");
+		    rescaleBut.setAlignmentX(0.5f);
+		    rescaleBut.addActionListener(this);
+		    rescaleBut.setActionCommand("refresh");
+		    rescaleBut.setEnabled(true);
+		    rescaleBut.setToolTipText("Rescales the displayed sketch;");
+		    tmp3.add(rescaleBut);
+		    tmp3.add(Box.createHorizontalStrut(strutsize));
+
+		    refreshListBut = new JButton("Refresh Listing");
+		    refreshListBut.setAlignmentX(0.5f);
+		    refreshListBut.addActionListener(this);
+		    refreshListBut.setActionCommand("refreshlist");
+		    refreshListBut.setEnabled(true);
+		    refreshListBut.setToolTipText("Refreshes the sketch listing;");
+		    tmp3.add(refreshListBut);
+		    
+		    tmp2.add(tmp3, BorderLayout.CENTER);
+		}
+
+		tmp2.add(Box.createVerticalStrut(strutsize));
+		// Sketch Tree:
+		sketchTree = new JTree(new DefaultTreeModel(initSketchTree(host, listingPort)));
+		tmp2.add(new JScrollPane(sketchTree));
+		// set up sketch node selection
+		sketchTree.getSelectionModel().setSelectionMode
+		            (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
+		//Listen for when the selection changes.
+		sketchTree.addTreeSelectionListener(this);
+		sketchTree.addMouseListener(this);
+		sketchTree.setCellRenderer(new SketchTreeRenderer());
+
+		tmp2.add(Box.createVerticalStrut(strutsize));
+		{
+		    Box tmp4 = Box.createHorizontalBox();
+		    tmp4.add(status=new JLabel(state));
+		    tmp4.add(Box.createHorizontalGlue());
+		    tmp2.add(tmp4);
+		}
+		tmp2.add(Box.createVerticalStrut(strutsize));
+		tmp1.add(tmp2);
+	    }	    tmp1.add(Box.createHorizontalStrut(strutsize));
+	    getContentPane().add(tmp1,BorderLayout.CENTER);
+	}
+	pack();
+	
+	String name="SketchGUI"+".location";
+	setLocation(prefs.getInt(name+".x",50),prefs.getInt(name+".y",50));
+	addWindowListener(new CloseSketchGUIAdapter(this));
+
+	sketchPanel.getListener().addListener(this);
+
+
+	popMenu = new PopupMenu();
+	MenuItem invBox = new MenuItem("Invert");
+	invBox.addActionListener(new PopupInvertListener());
+	popMenu.add(invBox);
+	MenuItem newWindow = new MenuItem("Clone current window");
+	newWindow.addActionListener(new PopupNewWindowListener(this));
+	popMenu.add(newWindow);
+	this.add(popMenu);
+    }
+
+    class CloseSketchGUIAdapter extends WindowAdapter {		SketchGUI gui;
+	CloseSketchGUIAdapter(SketchGUI gui) {this.gui=gui;}
+	public void windowClosing(WindowEvent e) {
+	    gui.close();
+	}
+    }
+
+    class PopupInvertListener implements ActionListener {
+ 	public void actionPerformed(ActionEvent e)
+	{
+	    currentMenuObject.invert();
+	    valueChanged(lastEvent);
+	    sketchTree.treeDidChange();
+	}
+    }
+
+    class PopupNewWindowListener implements ActionListener {
+	SketchGUI gui;
+
+        public PopupNewWindowListener(SketchGUI _gui) { gui = _gui; }
+
+	public void actionPerformed(ActionEvent e)
+	{
+	    //		 SketchPanel sketchPanel=new SketchPanel(gui, listener, true, prefs);
+		 SketchPanel sketchPanel=new SketchPanel(gui, listener, 1, prefs);
+	    sketchPanel.setMinimumSize(new Dimension(VisionListener.DEFAULT_WIDTH/2, 
+							  VisionListener.DEFAULT_HEIGHT/2));
+		 sketchPanel.setPreferredSize(new Dimension(VisionListener.DEFAULT_WIDTH*2, 
+							    VisionListener.DEFAULT_HEIGHT*2));
+		 sketchPanel.setLockAspectRatio(true);
+		 
+		 sketchPanel.makeSketchFrame(sketchPanel, "Cloned");
+		 		 
+		 sketchPanel.imageUpdated(getSketchImage(),sketchTree.getSelectionPaths());   
+	}
+    }
+
+	public void close() {
+		try {
+			if(listingSocket!=null && !listingSocket.isClosed())
+				listingSocket.close();		} catch (IOException ioe) {
+			System.err.println("close failed:");
+			ioe.printStackTrace();
+		}
+		prefs.putInt("SketchGUI.location.x",getLocation().x);
+		prefs.putInt("SketchGUI.location.y",getLocation().y);
+		sketchPanel.getListener().removeListener(this);
+		Component p=sketchPanel;
+		while(p.getParent()!=null)
+			p=p.getParent();
+		if(p instanceof Window) {
+			Window w=(Window)p;
+			prefs.putInt("SketchPanel.location.x",w.getLocation().x);
+			prefs.putInt("SketchPanel.location.y",w.getLocation().y);
+			w.dispose();
+		} else
+			System.out.println("That's weird - root container isn't window");
+		dispose();
+	}
+
+    public TreeNode initSketchTree(String host, int port) {
+
+	// Just for demonstration:
+	DefaultMutableTreeNode cam = new DefaultMutableTreeNode("hit refresh");
+	root.insert(cam,0);
+	return root;
+    }
+
+    public void sortTree(DefaultMutableTreeNode curNode) {
+		// set up comparator
+		Comparator comp =
+			new Comparator() {
+				public int compare(Object o1, Object o2) {
+					return compare((DefaultMutableTreeNode) o1, (DefaultMutableTreeNode) o2);  
+				}
+				public int compare(DefaultMutableTreeNode n1, DefaultMutableTreeNode n2) {
+					Integer i1 = new Integer(((VisualObjectInfo)n1.getUserObject()).id);
+					Integer i2 = new Integer(((VisualObjectInfo)n2.getUserObject()).id);
+					return i1.compareTo(i2);
+				}
+			};
+
+		// sort the roots children
+		Object[] objs = new Object[curNode.getChildCount()];
+		Enumeration children = curNode.children();
+		for (int i=0;children.hasMoreElements();i++) {
+			DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
+			objs[i] = child;
+		}
+
+		Arrays.sort(objs, comp);
+		curNode.removeAllChildren();
+
+		// insert newly ordered children
+		for (int i=0;i<objs.length;i++) {
+			DefaultMutableTreeNode orderedNode = (DefaultMutableTreeNode) objs[i];
+			curNode.add(orderedNode);
+			if (!orderedNode.isLeaf()) {
+				sortTree(orderedNode);
+			}
+		}
+	}
+
+	// gets called when a Sketch selection is clicked
+    public void valueChanged(TreeSelectionEvent e) {
+	imageNeedsUpdate = true;
+	lastEvent = e;
+	TreePath[] paths = sketchTree.getSelectionPaths();
+	
+	// Go through all objects and set visible to false
+	DefaultMutableTreeNode n = root;
+	while((n = n.getNextNode())!= null)
+	    {
+		((VisualObjectInfo)n.getUserObject()).setVisible(false);
+	    }
+	
+
+	if (paths == null) {
+	    //renderSelectedInTree(null);
+	    curSketchPanel.imageUpdated(null, null);
+	    return;
+	}
+
+	for (int path_i = 0; path_i < paths.length; path_i++) {
+	    DefaultMutableTreeNode node 
+		=(DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
+	    
+	    if (node == root) continue;	
+	    if (node == null) {System.err.println("node is null???"); return; }
+	    
+	    if(!(node.getUserObject() instanceof VisualObjectInfo)) {
+		System.out.println("valueChanged:: placeholder text can't be displayed");
+		continue;
+	    }
+	    
+	    
+	    VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
+	    if (!node.isRoot()) {
+		System.out.println("id clicked:"+vinfo.id);
+		if (! (vinfo instanceof SketchInfo) || ! ((SketchInfo)vinfo).isImageLoaded())
+		    {
+			((TCPVisionListener)listener).setReadingImage();
+			netout.println("get "+vinfo.id);
+			try {
+			    String inputLine;
+			    while((inputLine=readLine()).compareTo("get end") != 0) {
+				System.out.println(inputLine);
+			    }
+			} catch (IOException ioe) {
+			    System.err.println("Transfer error");
+			    reconnect();
+			    valueChanged(null);
+			}
+			if (vinfo instanceof SketchInfo)
+			    {
+				while(((TCPVisionListener)listener).isReadingImage())
+				    ;
+				((SketchInfo)vinfo).copyImage(((TCPVisionListener)listener).getImage());
+			    }
+			System.out.println("done with id:"+vinfo.id);
+		    }
+		vinfo.setVisible(true);
+		if (!sketchStack.contains(vinfo)) { sketchStack.add(vinfo); }
+	    } else {
+
+	    }
+	}
+	
+	curSketchPanel.imageUpdated(getSketchImage(), paths);
+    }
+
+    protected String readLine() throws java.io.IOException {
+	if(netin==null)
+	    reconnect();
+	if(netin==null)
+	    throw new java.io.IOException("no connection");
+	String ans=netin.readLine();
+	if(ans==null)
+	    throw new java.io.IOException("lost connection");
+	return ans;
+    }
+	
+	public void reconnect() {
+		System.out.print(host+":"+listingPort+" reconnecting...");
+		try {
+			if(listingSocket!=null && !listingSocket.isClosed())
+				listingSocket.close();
+			netin=null;
+			netout=null;
+			listingSocket = new Socket(host,listingPort);
+			netout = new PrintWriter(listingSocket.getOutputStream(), true);
+			netin = new BufferedReader(new InputStreamReader(listingSocket.getInputStream()));
+		} catch (UnknownHostException e) {
+			System.err.println("Don't know about host:"+host);
+			System.exit(1);
+		} catch (IOException ioe) {
+			System.err.println("reconnection failed:");
+			//ioe.printStackTrace();
+			return;
+		}
+		System.out.println("done");
+		refreshListBut.doClick(); //auto refresh on reconnect
+	}
+
+	public void visionUpdated(VisionListener listener) {
+	    //renderSelectedInTree(l.getImage().createGraphics());
+		listener.removeListener(this);
+		listener.fireVisionUpdate();
+		listener.addListener(this);
+	}
+	
+	// renders all the currently selected elements in the tree
+	public void renderSelectedInTree(Graphics2D g) {
+		if(g==null) {
+			g = img.createGraphics();
+			// g.setBackground(Color.GRAY);
+			g.clearRect(0,0,img.getWidth(),img.getHeight());
+		}
+		TreePath[] paths = sketchTree.getSelectionPaths();
+		if (paths == null) {
+			sketchPanel.repaint();
+			return;
+		}
+		for (int path_i = 0; path_i < paths.length; path_i++) {
+			DefaultMutableTreeNode node 
+				=(DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
+
+			if (node == root) continue;
+			if (node == null) return;
+			
+			if(!(node.getUserObject() instanceof VisualObjectInfo)) {
+				System.out.println("renderSelectedInTree:: placeholder text can't be displayed");
+				continue;
+			}
+			
+			VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
+			g.setColor(vinfo.getColor());
+
+			//g.setTransform(sketchPanel.resultAtrans);
+			//vinfo.renderTo(g);
+		}
+		sketchPanel.repaint();
+		//repaint(); // repaints this frame
+		//paintAll(); // repaints everything in this frame
+	}
+
+    public void mousePressed(MouseEvent e)
+    {
+	TreePath selectedPath = sketchTree.getPathForLocation(e.getX(),e.getY());
+	//System.out.println("Got mouse event for "+selectedPath);
+	if (e.getButton() == MouseEvent.BUTTON3)
+	    {
+		if (selectedPath != null)
+		    {
+			currentMenuObject = ((VisualObjectInfo)(((DefaultMutableTreeNode)(selectedPath.getLastPathComponent())).getUserObject()));
+			popMenu.show(sketchTree,e.getX(), e.getY());
+		    }
+	    }
+    }
+
+    public void mouseClicked(MouseEvent e){}
+    public void mouseReleased(MouseEvent e){}
+    public void mouseEntered(MouseEvent e){}
+    public void mouseExited(MouseEvent e){}
+
+    public BufferedImage getSketchImage()
+    {
+	if (imageNeedsUpdate) createSketchImage();
+	return img;
+    }
+
+    private void createSketchImage()
+    {
+	// Cull not visible objects from vector
+	// render all the sketches in the vector
+
+	img = new BufferedImage(VisionListener.DEFAULT_WIDTH, VisionListener.DEFAULT_HEIGHT, BufferedImage.TYPE_INT_RGB	);
+	Graphics2D g = img.createGraphics();
+	g.setBackground(Color.GRAY);
+	g.clearRect(0,0,VisionListener.DEFAULT_WIDTH, VisionListener.DEFAULT_HEIGHT);
+
+	int pixcount = img.getWidth()*img.getHeight();
+	int rarr[] = new int[pixcount];
+	int garr[] = new int[pixcount];
+	int barr[] = new int[pixcount];
+	int counts[] = new int[pixcount];
+	for (int i=0; i < pixcount; i++)
+	    {
+		rarr[i] = 0;
+		garr[i] = 0;
+		barr[i] = 0;
+		counts[i] = 0;
+	    }
+
+	// Draw SketchINTS
+	for (int i=0; i<sketchStack.size(); i++)
+	    {
+		VisualObjectInfo vinfo = (VisualObjectInfo)sketchStack.elementAt(i);
+		if (vinfo.getVisible()) {
+		    if (vinfo instanceof SketchInfo && !((SketchInfo)vinfo).isSketchBool()) {
+			((SketchInfo)vinfo).renderToArrays(rarr,garr,barr,counts);
+		    }
+		} else {
+		    sketchStack.removeElementAt(i--);
+		}
+	    }
+
+	for (int y=0; y<img.getHeight(); y++)
+	    {
+		for (int x=0; x<img.getWidth(); x++)
+		    {
+			int pos = y*img.getWidth()+x;
+			if (counts[pos] > 0)
+			    {
+				g.setColor(new Color(rarr[pos]/counts[pos],
+						     garr[pos]/counts[pos],
+						     barr[pos]/counts[pos]));
+				g.drawLine(x,y,x,y);
+			    }
+		    }
+	    }
+
+
+	// Draw SketchBOOLs
+	for (int i=0; i < img.getWidth()*img.getHeight(); i++)
+	    {
+		rarr[i] = 0;
+		garr[i] = 0;
+		barr[i] = 0;
+		counts[i] = 0;
+	    }
+
+	for (int i=0; i<sketchStack.size(); i++)
+	    {
+		VisualObjectInfo vinfo = (VisualObjectInfo)sketchStack.elementAt(i);
+		if (vinfo.getVisible())
+		    {
+			if (vinfo instanceof SketchInfo && ((SketchInfo)vinfo).isSketchBool())
+			    {
+				((SketchInfo)vinfo).renderToArrays(rarr,garr,barr,counts);
+			    }
+		    }
+		else
+		    {
+			sketchStack.removeElementAt(i--);
+ 		    }
+	    }
+
+	for (int y=0; y<img.getHeight(); y++)
+	    {
+		for (int x=0; x<img.getWidth(); x++)
+		    {
+			int pos = y*img.getWidth()+x;
+			if (counts[pos] > 0)
+			    {
+				g.setColor(new Color(rarr[pos]/counts[pos],
+						     garr[pos]/counts[pos],
+						     barr[pos]/counts[pos]));
+				g.drawLine(x,y,x,y);
+			    }
+		    }
+	    }
+
+	imageNeedsUpdate = false;
+
+	//renderSelectedInTree(img.createGraphics());
+    }
+
+    public void setCurrentSketchPanel(SketchPanel s, TreePath[] paths)
+    {
+	if (curSketchPanel != s)
+	    {
+		curSketchPanel.loseFocus();
+	    }
+	curSketchPanel = s;
+	if (sketchTree != null)
+	    {
+		sketchTree.setSelectionPaths(paths);
+	    }
+    }
+
+
+	private class SketchTreeRenderer extends DefaultTreeCellRenderer {
+		public SketchTreeRenderer(/*Icon icon*/) {
+//			tutorialIcon = icon;
+		}
+
+		public Component getTreeCellRendererComponent(
+				JTree tree,
+				Object value,
+				boolean sel,
+				boolean expanded,
+				boolean leaf,
+				int row,
+				boolean hasFocus) {
+			super.getTreeCellRendererComponent(
+					tree, value, sel,
+					expanded, leaf, row,
+					hasFocus);
+			try {
+			VisualObjectInfo vinfo = (VisualObjectInfo)(((DefaultMutableTreeNode)value).getUserObject());
+			
+			setIcon(vinfo.getIcon());
+			setToolTipText(vinfo.toString());
+			} catch (ClassCastException e) {}
+
+			return this;
+		}
+	}
+}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SketchInfo.java ./tools/mon/org/tekkotsu/sketch/SketchInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SketchInfo.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/SketchInfo.java	Sun Jun 19 08:56:21 2005
@@ -0,0 +1,196 @@
+package org.tekkotsu.sketch;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+
+import java.util.Hashtable;
+import java.awt.image.IndexColorModel;
+import java.awt.Graphics;
+
+// stores info for a Sketch, to use as UserObject for DefaultMutableTreeNode
+public class SketchInfo extends VisualObjectInfo {
+    static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/sketch.png");
+    static Icon inverted_icon = new ImageIcon("org/tekkotsu/mon/icons/sketchinv.png");;
+
+    static Icon int_icon = new ImageIcon("org/tekkotsu/mon/icons/sketchint.png");
+    static Icon inverted_int_icon = new ImageIcon("org/tekkotsu/mon/icons/sketchintinv.png");
+
+
+    public static final int SKETCH_INT_TYPE   = 1;
+    public static final int SKETCH_BOOL_TYPE  = 2;
+    public static final int SKETCH_FLOAT_TYPE = 3;
+    
+
+    boolean imageLoaded;
+    BufferedImage img;
+    boolean isSketchBool;
+    int grayColor;
+
+    public SketchInfo(int _id, int _parentId, String _name, 
+		      Color _color, int sketchType) {
+	super(_id, _parentId, _name, _color);
+	imageLoaded = false;
+	img = null;
+	isSketchBool = true;
+	if (sketchType == SKETCH_INT_TYPE)
+	    {
+		isSketchBool = false;
+	    }
+	else if (sketchType == SKETCH_FLOAT_TYPE)
+	    {
+		System.out.println("Warning, got a SketchFloat, treating it like a SketchInt");
+		isSketchBool = false;
+	    }
+    }
+    
+    public Icon getIcon() { 
+	if (inverted)
+	    {
+		if (isSketchBool)
+		    return inverted_icon;
+		else
+		    return inverted_int_icon;
+	    }
+	else
+	    {
+		if (isSketchBool)
+		    return icon;
+		else
+		    return int_icon;
+	    }
+	}
+
+    public boolean isImageLoaded() { return imageLoaded; }
+
+    public BufferedImage getImage() { return img; }
+
+    public void unloadImage()
+    {
+	imageLoaded = false;
+	img = null;
+    }
+
+
+    // Deep image copying
+    public void copyImage(BufferedImage _img)
+    {
+	Hashtable colortable = new Hashtable();
+	int colorCount = 0;
+	boolean lookingForGray = true;
+
+	if (_img == null)
+	    return;
+	System.out.println("Type = "+_img.getType()+" RGB="+BufferedImage.TYPE_INT_ARGB);
+	img = new BufferedImage(_img.getWidth(), _img.getHeight(), _img.getType(),((IndexColorModel) _img.getColorModel()));
+	img.getRaster().setRect(_img.getRaster());
+
+	for (int i=0; i<_img.getWidth()*_img.getHeight(); i++)
+	    {
+		int x = i % _img.getWidth();
+		int y = i / _img.getWidth();
+
+		// Count the colors
+		if (!colortable.containsKey(new Integer(_img.getRGB(x,y))))
+		{
+		    System.out.println("Color found: "+new Color(_img.getRGB(x,y)));
+		    colortable.put(new Integer(_img.getRGB(x,y)),new Integer(_img.getRGB(x,y)));
+		    if (++colorCount > 2)
+			{
+			    isSketchBool = false;
+			    break;
+			}
+		}
+		
+		if (lookingForGray && _img.getRGB(x,y) == Color.GRAY.getRGB())
+		    {
+			grayColor = img.getRGB(x,y);
+			lookingForGray = false; 
+		    }
+	    
+		/*if (!newttable.containsKey(new Integer(img.getRGB(x,y))))
+		{
+		    System.out.println("New Color found: "+new Color(img.getRGB(x,y)));
+		    newttable.put(new Integer(img.getRGB(x,y)),new Integer(img.getRGB(x,y)));
+		    }*/
+	    }
+	imageLoaded = true;
+    }
+
+    public boolean isSketchBool() { return isSketchBool; }
+
+    public void renderTo(Graphics2D g)
+    {
+	if (inverted)
+	    System.out.print("Inverted ");
+	System.out.println("Sketch rendering");
+	if (img != null)
+	    {
+		g.setColor(getColor());
+		for (int x = 0; x<img.getWidth(); x++)
+		    {
+			for (int y=0; y< img.getHeight(); y++)
+			    {
+				int cur = img.getRGB(x,y);
+				if (cur != grayColor)
+				    {
+					if (isSketchBool)
+					    g.drawLine(x,y,x,y);
+					else
+					{
+					    g.setColor(new Color(cur));
+					    g.drawLine(x,y,x,y);
+					}
+				    }
+			    }
+		    }
+	    }
+    }
+
+
+    public void renderToArrays(int r[], int g[], int b[], int counts[])
+    {
+	int curR = getColor().getRed();
+	int curG = getColor().getGreen();
+	int curB = getColor().getBlue();
+	if (img!= null)
+	    {
+		for (int y=0; y< img.getHeight(); y++)
+		    {
+			for (int x = 0; x<img.getWidth(); x++)
+			    {
+				int pos = y*img.getWidth()+x;
+				int cur = img.getRGB(x,y);
+				if (cur != grayColor)
+				    {
+					if (!isSketchBool)
+					    {
+						Color c = new Color(cur);
+						curR = c.getRed();
+						curG = c.getGreen();
+						curB = c.getBlue();
+						if (inverted)
+						    {
+							curR = 255 - curR;
+							curG = 255 - curG;
+							curB = 255 - curB;
+						    }
+					    }
+					
+					r[pos] += curR;
+					g[pos] += curG;
+					b[pos] += curB;
+					counts[pos]++;
+				    }
+			    }
+		    }
+	    }
+   }
+
+}
+
+
+
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SketchPanel.java ./tools/mon/org/tekkotsu/sketch/SketchPanel.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SketchPanel.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/SketchPanel.java	Fri Aug  5 17:26:57 2005
@@ -0,0 +1,410 @@
+package org.tekkotsu.sketch;
+
+import org.tekkotsu.mon.*;
+
+import javax.swing.*;
+import javax.imageio.ImageIO;
+import javax.swing.SwingConstants;
+import javax.swing.JLabel;
+import java.awt.Color;
+import java.awt.image.BufferedImage;
+import java.awt.Component;
+import java.awt.BorderLayout;
+import java.awt.Graphics;
+import java.awt.BasicStroke;
+import java.awt.Graphics2D;
+import java.awt.FontMetrics;
+import java.awt.Cursor;
+import java.awt.Rectangle;
+import java.awt.geom.*;
+import javax.swing.JFrame;
+import javax.swing.Box;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowEvent;
+import java.awt.event.WindowFocusListener;
+import java.awt.image.IndexColorModel;
+import java.util.prefs.Preferences;
+import java.io.File;
+import java.io.*;
+import javax.swing.tree.*;
+
+
+public class SketchPanel extends VisionPanel 
+    implements ActionListener, WindowFocusListener
+ {
+     SketchGUI gui; // reference back to owning SketchGUI
+     AffineTransform atrans;
+     AffineTransform resultAtrans;
+     //     boolean isCam;
+     int space;
+
+    //Vector featureList = null;
+    protected TreePath[] paths;
+
+     boolean drawText;
+
+     Box buttonBox = null;
+     Component buttonStrut;
+
+     static Preferences prefs;
+
+     // coordinate bounds for the view of the SketchPanel
+     float leftBound=0, rightBound=176, topBound=0, bottomBound=144;
+     
+     //     protected SketchPanel(SketchGUI _gui, VisionListener listener, 
+     //			   boolean _isCam, Preferences _prefs) {
+     protected SketchPanel(SketchGUI _gui, VisionListener listener, 
+     			   int _space, Preferences _prefs) {
+	 //	 super(listener, _gui, _isCam);
+	 super(listener, _gui, _space);
+	 gui = _gui;
+	 space = _space;
+	 prefs = _prefs;
+	 drawText = true;
+	 mouseX = -1;
+	 mouseY = -1;
+    }	
+	
+     public void visionUpdated(VisionListener listener) {
+	 super.visionUpdated(listener);
+     }
+     
+     protected void drawImage(Graphics _g, BufferedImage img, int x, int y, int w, int h) {
+	 Graphics2D g2d = (Graphics2D)_g;
+	 AffineTransform origtrans = g2d.getTransform();
+	 float scaling = 1;
+	 // right now sketches start at (0,0) but this will change someday for worldspace
+	 int imgLeft = 0; int imgTop = 0;
+	 if (img != null) {
+	     //if(isCam) {
+	     if(space == 1) {
+		 scaling = java.lang.Math.min(w/(rightBound-leftBound),
+					      h/(bottomBound-topBound));
+		 atrans = new AffineTransform(scaling, 0, 0, scaling, x, y);
+	     } else {
+		 scaling = java.lang.Math.min(w/(bottomBound-topBound),
+					      h/(rightBound-leftBound));
+		 atrans = new AffineTransform(0, -scaling, -scaling, 0,
+					      bottomBound*scaling, rightBound*scaling);
+	     }
+	     // System.out.println("SketchPanel::img width/height = "+img.getWidth() + " " + img.getHeight());
+	     // System.out.println("Bounds = "+leftBound+" "+rightBound+" "+topBound+" "+bottomBound);
+	     // System.out.println("SketchPanel::scaling = "+scaling);
+
+	     g2d.transform(atrans);
+	     resultAtrans = atrans;
+	     g2d.drawImage(img,imgLeft,imgTop,img.getWidth(),img.getHeight(),null);
+
+	 } else {
+	     g2d.setColor(getBackground());
+	     g2d.fillRect(x,y,w,h);
+	     FontMetrics fmet=g2d.getFontMetrics();
+	     String msg="No image";
+	     int strw=fmet.stringWidth(msg);
+	     int strh=fmet.getHeight();
+	     g2d.setColor(getForeground());
+	     g2d.drawString(msg,(getSize().width-strw)/2,(getSize().height-strh)/2+fmet.getAscent());
+	 }
+	
+	 // draw the Shapes:
+	 drawFeatures(g2d);
+
+	 // undo the transform so we can write worldspace text that isn't flipped
+	 g2d.setTransform(origtrans);
+
+	 // draw image bounds and mouse coordinates
+	 if (img != null && drawText) {
+	     FontMetrics fmet=g2d.getFontMetrics();
+	     //	     if (isCam) {
+	     if (space == 1) {
+		 // draw bounds and mouse position in cam coordinates
+		 g2d.setColor(getForeground());
+		 String msg="("+String.valueOf((int)leftBound)+","+String.valueOf((int)topBound)+")";
+		 int strw=fmet.stringWidth(msg);
+		 g2d.drawString(msg,x,y+fmet.getAscent());
+		 msg="("+String.valueOf((int)rightBound)+","+String.valueOf((int)bottomBound)+")";
+		 strw=fmet.stringWidth(msg);
+		 g2d.drawString(msg,x+w-strw,y+h-fmet.getDescent());
+		 if (mouseX >= 0 && mouseY >= 0) {
+		     int camX = java.lang.Math.round(mouseX/scaling+leftBound);
+		     int camY = java.lang.Math.round(mouseY/scaling+topBound);
+		     g2d.setColor(Color.YELLOW);
+		     g2d.drawString("("+camX+","+camY+")", x, y+h-fmet.getDescent());
+		     g2d.setColor(getForeground());
+		 }
+	     } else {
+		 // draw bounds and mouse position in world coordinates
+		 g2d.setXORMode(Color.GRAY);
+		 g2d.setColor(getForeground());
+		 String msg="("+String.valueOf((int)rightBound)+","+String.valueOf((int)bottomBound)+")";
+		 int strw=fmet.stringWidth(msg);
+		 g2d.drawString(msg,x,y+fmet.getAscent());
+		 msg="("+String.valueOf((int)leftBound)+","+String.valueOf((int)topBound)+")";
+		 strw=fmet.stringWidth(msg);
+		 g2d.drawString(msg,x+(bottomBound-topBound)*scaling-strw,y+(rightBound-leftBound)*scaling-fmet.getDescent());
+		 g2d.setPaintMode();
+		 if (mouseX >= 0 && mouseY >= 0) {
+		     int worldX = java.lang.Math.round(rightBound-mouseY/scaling);
+		     int worldY = java.lang.Math.round(bottomBound-mouseX/scaling);
+		     g2d.setXORMode(Color.BLUE);
+		     g2d.drawString("(" + worldX + "," + worldY + ")", x, y+h-fmet.getDescent());
+		     g2d.setPaintMode();
+		 }
+		 // add crosshairs if requested
+		 if (crosshairsEnabled) {
+		     g2d.setXORMode(Color.GRAY);
+		     g2d.setColor(Color.WHITE);
+		     g2d.setStroke(new BasicStroke(1.0f));
+		     int tmpx = java.lang.Math.round(x+(bottomBound-topBound)*scaling/2);
+		     g2d.drawLine(tmpx,y,tmpx,java.lang.Math.round(y+(rightBound-leftBound)*scaling));
+		     int tmpy = java.lang.Math.round(y+(rightBound-leftBound)*scaling/2);
+		     g2d.drawLine(x,tmpy,java.lang.Math.round(x+(bottomBound-topBound)*scaling),tmpy);
+		     g2d.setPaintMode();
+
+		 }
+	     }
+	     if (idEnabled) {
+		 for (int path_i = 0; path_i < paths.length; path_i++) {
+		     DefaultMutableTreeNode node = (DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
+		     if (node == null) break;
+		     
+		     if((node.getUserObject() instanceof VisualObjectInfo)) {
+			 VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
+			 g2d.setColor(vinfo.getColor());
+			 float[] id_coords = new float[2];
+			 if (vinfo instanceof EllipseShapeInfo) { // id added at the centroid
+			     id_coords[0] = ((EllipseShapeInfo)vinfo).getCentroidX();
+			     id_coords[1] =  ((EllipseShapeInfo)vinfo).getCentroidY();
+			 }
+			 else if (vinfo instanceof SphereShapeInfo) { // id added at the centroid
+			     id_coords[0] = ((SphereShapeInfo)vinfo).getCentroidX();
+			     id_coords[1] =  ((SphereShapeInfo)vinfo).getCentroidY();
+			 }
+			 else if(vinfo instanceof LineShapeInfo) { // id added at the first end point
+			     id_coords[0] = ((LineShapeInfo)vinfo).getE1X();
+			     id_coords[1] = ((LineShapeInfo)vinfo).getE1Y();
+			 }
+			 //if (isCam)
+			 if (space == 1)
+			     atrans.transform(id_coords, 0, id_coords, 0, 1);//chage this, or no id for cam
+			 else
+			     atrans.transform(id_coords, 0, id_coords, 0, 1);
+			 g2d.drawString(Integer.toString(vinfo.getId()),(int)id_coords[0], (int)id_coords[1]);
+		     }
+		     g2d.setPaintMode();
+		 }
+	     }
+	 }
+     }
+     
+     public void makeSketchFrame(SketchPanel sketchPanel, String title)
+     {
+	 JFrame sketchFrame = new JFrame(title+" space");
+	 Box sketchBox = Box.createVerticalBox();
+	 buttonBox = Box.createHorizontalBox();
+	 buttonBox.setBackground(Color.red);
+	 JButton cloneButton = new JButton("Clone");
+	 cloneButton.addActionListener(sketchPanel);
+	 cloneButton.setActionCommand("clone");
+	 cloneButton.setEnabled(true);
+	 buttonBox.add(cloneButton);
+	 
+	 buttonBox.add(Box.createHorizontalStrut(10));
+
+	 JButton saveButton = new JButton("Save Image");
+	 saveButton.setAlignmentX(0.5f);
+	 saveButton.addActionListener(sketchPanel);
+	 saveButton.setActionCommand("saveimg");
+	 saveButton.setEnabled(true);
+	 saveButton.setToolTipText("Saves sketch to a file - use .jpg or .png extension to choose format;");
+	 buttonBox.add(saveButton);
+
+	 buttonBox.add(Box.createHorizontalStrut(10));
+	
+	 //Icon xhairIcon = new ImageIcon("org/tekkotsu/sketch/crosshairs.png");
+	 //JCheckBox xhairsBox = new JCheckBox(xhairIcon, true);
+	 JCheckBox xhairsBox = new JCheckBox("Crosshairs", false);
+	 xhairsBox.addActionListener(sketchPanel);
+	 xhairsBox.setActionCommand("xhairs");
+	 xhairsBox.setEnabled(true);
+	 buttonBox.setVisible(windowHasFocus);
+	 buttonBox.add(xhairsBox);
+
+	 JCheckBox idBox = new JCheckBox("ID", false);
+	 idBox.addActionListener(sketchPanel);
+	 idBox.setActionCommand("id");
+	 idBox.setEnabled(true);
+	 buttonBox.setVisible(windowHasFocus);
+	 buttonBox.add(idBox);
+
+
+	 Box bigButtonBox = Box.createHorizontalBox();
+
+	 bigButtonBox.add(buttonBox);
+	 buttonStrut = Box.createVerticalStrut((int)cloneButton.getPreferredSize().getHeight());
+	 buttonStrut.setVisible(true);
+	 bigButtonBox.add(buttonStrut);
+	 sketchBox.add(bigButtonBox);
+	 sketchBox.add(sketchPanel);
+	 sketchFrame.getContentPane().add(sketchBox);
+	 sketchFrame.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
+	 //sketchFrame.getContentPane().add(sketchPanel);
+	 sketchFrame.pack();
+	 //sketchFrame.setLocation(prefs.getInt("SketchPanel.location.x",50),prefs.getInt("SketchPanel.location.y",50));
+	 
+	 sketchFrame.addWindowFocusListener(sketchPanel);
+
+	 sketchFrame.setVisible(true);
+     }
+
+     public void actionPerformed(ActionEvent e) 
+     {
+	 if (e.getActionCommand().compareTo("clone")==0)
+	     {
+		 SketchPanel sketchPanel=new SketchPanel(gui, _listener, space, prefs);
+		 sketchPanel.setMinimumSize(new Dimension(VisionListener.DEFAULT_WIDTH/2, 
+							  VisionListener.DEFAULT_HEIGHT/2));
+		 sketchPanel.setPreferredSize(new Dimension(VisionListener.DEFAULT_WIDTH*2, 
+							    VisionListener.DEFAULT_HEIGHT*2));
+		 sketchPanel.setLockAspectRatio(true);
+		 
+		 //getContentPane().add(sketch,BorderLayout.NORTH);
+		 
+		 sketchPanel.makeSketchFrame(sketchPanel, "Cloned");
+		 
+		 
+		 //BufferedImage newImage = new BufferedImage(_image.getWidth(), _image.getHeight(), _image.getType());
+		 //newImage.createGraphics().drawImage(_image,0,0,null);
+		 
+		 //sketchPanel.imageUpdated(newImage, null);
+		 sketchPanel.imageUpdated(_image,paths);		
+	     } 
+	 else if(e.getActionCommand().compareTo("saveimg")==0) 
+	     {
+		 File cursavepath = new File(prefs.get("cursavepath",""));
+		 JFileChooser dia=new JFileChooser(cursavepath);
+		 dia.setDialogTitle("Save Image...");
+		 Component cur=this;
+		 while(cur.getParent()!=null)
+		     cur=cur.getParent();
+		 if(dia.showSaveDialog(cur)==JFileChooser.APPROVE_OPTION) {
+		     prefs.put("cursavepath",dia.getCurrentDirectory().getPath());
+		     String base=dia.getSelectedFile().getName();
+		     String format;
+		     if(base.lastIndexOf('.')==-1) {
+			 format="png";
+		     } else {
+			 int i=base.lastIndexOf(".");
+			 format=base.substring(i+1);
+			 base=base.substring(0,i);
+		     }
+		     try {
+			 FileOutputStream fileout=new FileOutputStream(dia.getSelectedFile().getParent()+File.separator+base+"."+format);
+			 //ImageIO.write(sketchPanel.getListener().getImage(),format,fileout);
+			 ImageIO.write(getSaveImage(),format,fileout);
+		     } catch(IOException ex) {}
+		 }
+	     }
+	 else if (e.getActionCommand().compareTo("xhairs") == 0)
+	     {
+		 crosshairsEnabled = ((JCheckBox)(e.getSource())).isSelected();
+		 repaint();
+	     }
+	 else if (e.getActionCommand().compareTo("id") == 0)
+	     {
+		 idEnabled = ((JCheckBox)(e.getSource())).isSelected();
+		 repaint();
+	     }	 
+     }
+     
+
+
+	// stretches the view of the SketchPanel to accomodate the specified object 
+	public void scaleToVisualObject(VisualObjectInfo oinfo) {
+	    if(oinfo.getLeft() < leftBound)
+		leftBound = oinfo.getLeft();
+	    if(oinfo.getRight() > rightBound)
+		rightBound = oinfo.getRight();
+	    if(oinfo.getTop() < topBound)
+		topBound = oinfo.getTop();
+	    if(oinfo.getBottom() > bottomBound)
+		bottomBound = oinfo.getBottom();
+	}
+
+    public void imageUpdated(BufferedImage sketchImage, TreePath[] _paths)
+    {
+		_image = sketchImage;
+		paths = _paths;
+		repaint();
+    }
+    
+     public void loseFocus()
+     {
+	 windowHasFocus = false;
+	 buttonBox.setVisible(false);
+	 buttonStrut.setVisible(true);
+	 repaint();
+     }
+
+     public void windowGainedFocus(WindowEvent e) {
+	 gui.setCurrentSketchPanel(this,paths);
+	 windowHasFocus = true;
+	 if (buttonBox != null) {
+	     buttonBox.setVisible(true);
+	     buttonStrut.setVisible(true);
+	 }
+	 repaint();
+     }
+
+     public void windowLostFocus(WindowEvent e) {}
+
+     public BufferedImage getSaveImage() {
+	 int width=0, height=0;
+	 //if (isCam) {
+	 if (space==1) {
+	     width = (int)(rightBound-leftBound);
+	     height = (int)(bottomBound-topBound);
+	 } else {
+	     width = (int)(bottomBound-topBound);
+	     height = (int)(rightBound-leftBound);
+	 }
+	 BufferedImage saveimg = new BufferedImage(width,height,_image.getType());
+	 boolean oldxhairs = crosshairsEnabled;
+	 boolean olddrawtext = drawText;
+	 crosshairsEnabled = false;
+	 drawText = false;
+	 Graphics g = saveimg.createGraphics();
+	 g.setColor(Color.WHITE);
+	 g.fillRect(0,0,width,height);
+	 drawImage(g,_image,0,0,width,height);
+	 drawFeatures((Graphics2D)g);
+	 crosshairsEnabled = oldxhairs;
+	 drawText = olddrawtext;
+	 return saveimg;
+     }
+
+     public void drawFeatures(Graphics2D g)
+    {
+	if (paths == null) return;
+
+	for (int path_i = 0; path_i < paths.length; path_i++) 
+	    {
+		DefaultMutableTreeNode node = (DefaultMutableTreeNode)(paths[path_i].getLastPathComponent());
+		if (node == null) return;
+
+		// check for dummy node; it's used for "camspace" or "worldspace" folder
+		if((node.getUserObject() instanceof VisualObjectInfo)) {
+		    VisualObjectInfo vinfo = (VisualObjectInfo)(node.getUserObject());
+		    if (vinfo instanceof ShapeInfo)
+			{
+			    g.setColor(vinfo.getColor());
+			    vinfo.renderTo(g);
+			}
+		}
+	    }
+    }
+}
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SphereShapeInfo.java ./tools/mon/org/tekkotsu/sketch/SphereShapeInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/SphereShapeInfo.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/SphereShapeInfo.java	Fri Aug  5 21:04:58 2005
@@ -0,0 +1,59 @@
+package org.tekkotsu.sketch;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics2D;
+import java.awt.Graphics;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import java.awt.Rectangle;
+import java.awt.geom.*;
+import java.awt.BasicStroke;
+
+// stores info for a EllipseShape
+// note that ellipse center is same as centroid
+public class SphereShapeInfo extends ShapeInfo {
+    static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/ellipse.png");
+    static Icon inv_icon = new ImageIcon("org/tekkotsu/mon/icons/ellipseinv.png");
+    float radius; // length of semimajor axes
+    int id;
+
+	public SphereShapeInfo(int _id, int _parentId, String _name, Color _color,
+			float _centroidx, float _centroidy, float _centroidz,
+			float _radius) {
+		super(_id, _parentId, _name, _color, _centroidx, _centroidy, _centroidz);
+		radius = _radius;
+		id = _id;
+	}
+
+	// returns left-most coordinate of object
+	public float getLeft() { return centroidx-radius; }
+	// returns right-most coordinate of object
+	public float getRight() { return centroidx+radius; }
+	// returns top-most coordinate of object
+	public float getTop() { return centroidy-radius; }
+	// returns bottom-most coordinate of object
+	public float getBottom() { return centroidy+radius; }
+
+
+	public String toString() {
+		return (super.toString() + " center=(" + centroidx + "," + centroidy + "," + centroidz + ")"
+			+ ", radius=" + radius);
+	}
+
+	public Icon getIcon() { 
+	    if (inverted)
+		return inv_icon;
+	    return icon; 
+	}
+
+    public void renderTo(Graphics2D graphics) {
+	graphics.setStroke(new BasicStroke(1.0f));
+	graphics.drawOval((int)(getCentroidX()-radius+1), 
+			  (int)(getCentroidY()-radius+1),
+			  (int)(radius*2), (int)(radius*2));
+    }
+
+	public float getRadius() { return radius; }
+}
+
diff -urdN ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/VisualObjectInfo.java ./tools/mon/org/tekkotsu/sketch/VisualObjectInfo.java
--- ../Tekkotsu_2.3/tools/mon/org/tekkotsu/sketch/VisualObjectInfo.java	Wed Dec 31 19:00:00 1969
+++ ./tools/mon/org/tekkotsu/sketch/VisualObjectInfo.java	Mon May 23 02:27:18 2005
@@ -0,0 +1,94 @@
+package org.tekkotsu.sketch;
+
+import java.awt.Graphics2D;
+import java.awt.Graphics;
+import java.awt.Color;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import java.awt.PopupMenu;
+
+import java.awt.Rectangle;
+import java.awt.geom.*;
+
+// stores info for a VisualObject
+
+public class VisualObjectInfo {
+    static Icon icon = new ImageIcon("org/tekkotsu/mon/icons/unknown.png");
+    static Icon inverted_icon = null;
+    int id;
+    int parentId;
+    String name;
+    Color color;
+    boolean isVisible;
+    boolean inverted;
+
+	public VisualObjectInfo(int _id, int _parentId, String _name, 
+				Color _color){
+		id = _id;
+		parentId = _parentId;
+		name = _name;
+		color = _color;
+	}
+
+	public int getId() { return id; }
+	public int getParentId() { return parentId; }
+	public String getName() { return name; }
+
+	public float getLeft() { return 0; }
+	public float getRight() { return 176; }
+	public float getTop() { return 0; }
+	public float getBottom() { return 144; }
+
+    public Color getColor() 
+    { 
+	if (inverted)
+	    return new Color(255-color.getRed(),
+				 255-color.getGreen(),
+				 255-color.getBlue());
+	else
+	    return color; 
+    }
+
+    public Color getColorInverted()
+    {
+	return new Color(255-color.getRed(),
+			 255-color.getGreen(),
+			 255-color.getBlue());
+    }
+
+    public void setVisible(boolean vis) {
+	isVisible = vis;
+    }
+
+    public boolean getVisible() {
+	return isVisible;
+    }
+    
+    public String toString() {
+	return (name + "(id " + id + ", parentId " + parentId + ")");
+    }
+
+    public Icon getIcon() { 
+	if (!inverted || inverted_icon == null)
+	    return icon;
+	else
+	    return inverted_icon;
+    }
+
+    public void renderTo(Graphics2D graphics) {
+	System.out.println("Rendering "+id);
+    }
+    
+    public void renderTo(Graphics graphics, Rectangle2D.Double r) {}
+
+    public void invert() {
+	inverted = !inverted;
+    }
+
+    public void setInverted(boolean _inverted) {
+	inverted = _inverted;
+    }
+    
+}
+
+
diff -urdN ../Tekkotsu_2.3/tools/safemot/CVS/Entries ./tools/safemot/CVS/Entries
--- ../Tekkotsu_2.3/tools/safemot/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,4 @@
+/Makefile/1.7/Wed Aug 10 01:58:36 2005//Ttekkotsu-2_4
+/safemot.cc/1.2/Mon Nov  8 21:48:19 2004//Ttekkotsu-2_4
+/tekkotsu.cfg/1.1/Mon Nov  8 21:48:19 2004//Ttekkotsu-2_4
+D/from_cmpack02////
diff -urdN ../Tekkotsu_2.3/tools/safemot/CVS/Repository ./tools/safemot/CVS/Repository
--- ../Tekkotsu_2.3/tools/safemot/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/safemot
diff -urdN ../Tekkotsu_2.3/tools/safemot/CVS/Root ./tools/safemot/CVS/Root
--- ../Tekkotsu_2.3/tools/safemot/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/safemot/CVS/Tag ./tools/safemot/CVS/Tag
--- ../Tekkotsu_2.3/tools/safemot/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/safemot/Makefile ./tools/safemot/Makefile
--- ../Tekkotsu_2.3/tools/safemot/Makefile	Tue Nov  9 17:15:03 2004
+++ ./tools/safemot/Makefile	Tue Aug  9 21:58:36 2005
@@ -1,75 +1,69 @@
 
+# This Makefile will handle most aspects of compiling and
+# linking a tool against the Tekkotsu framework.  You probably
+# won't need to make any modifications, but here's the major controls
 
-#if you want to change the target model, it is recommended
-#to set the TEKKOTSU_TARGET_MODEL environment variable
+# Executable name, defaults to:
+#   `basename \`pwd\``-$(TEKKOTSU_TARGET_MODEL)
+TEKKOTSU_TARGET_MODEL?=TGT_ERS7
+BIN:=$(shell pwd | sed 's@.*/@@')-$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)))
 
-.PHONY: all tk_bd
+# Build directory
+PROJECT_BUILDDIR:=build
 
-# We use this TK_RT instead of TEKKOTSU_ROOT so things will
-# still work if TEKKOTSU_ROOT is a relative path
-TK_RT:=../..
+# Source files, defaults to all files ending matching *$(SRCSUFFIX)
+SRCSUFFIX:=.cc
+PROJ_SRC:=$(shell find . -name "*$(SRCSUFFIX)")
 
-TEMPLATE_PROJECT:=$(TK_RT)/project
-TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
-TEKKOTSU_TARGET_PLATFORM = PLATFORM_LOCAL
-include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
-FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(FILTERSYSWARN))
-COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(COLORFILT))
+# Use the containing framework, regardless of TEKKOTSU_ROOT setting (no '?=')
+TEKKOTSU_ROOT=../..
 
-BIN:=safemot_$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)) | tr [:upper:] [:lower:])
+.PHONY: all test
 
-SRCSUFFIX=.cc
+TEMPLATE_PROJECT:=$(TEKKOTSU_ROOT)/project
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
+$(if $(shell if [ \! -r $(TEKKOTSU_ENVIRONMENT_CONFIGURATION) ] \; then echo failure \; fi),$(error An error has occured, `$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)' could not be found.  You may need to edit TEKKOTSU_ROOT in the Makefile))
 
-PROJ_OBJ:= \
-	$(PROJ_BD)/safemot.o \
+TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(FILTERSYSWARN))
+COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(COLORFILT))
+$(shell mkdir -p $(PROJ_BD))
 
-TK_TGTS:= \
-	$(TK_BD)/Events/EventBase.o \
-	$(TK_BD)/Events/EventRouter.o \
-	$(TK_BD)/Motion/MotionManager.o \
-	$(TK_BD)/Motion/MotionSequenceMC.o \
-	$(TK_BD)/Motion/PostureEngine.o \
-	$(TK_BD)/Motion/Kinematics.o \
-	$(TK_BD)/Shared/get_time.o \
-	$(TK_BD)/Shared/LoadSave.o \
-	$(TK_BD)/Shared/Config.o \
-	$(TK_BD)/Shared/Profiler.o \
-	$(TK_BD)/Shared/TimeET.o \
-	$(TK_BD)/Shared/WorldState.o \
-	$(TK_BD)/Wireless/Socket.o \
-	$(TK_BD)/Shared/newmat/libnewmat.a \
-	$(TK_BD)/Motion/roboop/libroboop.a \
+PROJ_OBJ:=$(patsubst ./%$(SRCSUFFIX),$(PROJ_BD)/%.o,$(PROJ_SRC))
 
-LIBS:= $(TK_BD)/Motion/roboop/libroboop.a $(TK_BD)/Shared/newmat/libnewmat.a
+LIBS:= $(TK_BD)/libtekkotsu.a $(TK_BD)/../Motion/roboop/libroboop.a $(TK_BD)/../Shared/newmat/libnewmat.a
 
 DEPENDS:=$(PROJ_OBJ:.o=.d)
 
-CXXFLAGS=-g -Wall -O2 \
-         -I$(TK_RT) \
+CXXFLAGS:=-g -Wall -O2 \
+         -I$(TEKKOTSU_ROOT) \
+         -I../../Shared/jpeg-6b $(shell xml2-config --cflags) \
          -D$(TEKKOTSU_TARGET_PLATFORM) -D$(TEKKOTSU_TARGET_MODEL) 
 
 
 all: $(BIN)
 
-$(BIN): tk_bd $(PROJ_OBJ)
+$(BIN): $(PROJ_OBJ) $(LIBS)
 	@echo "Linking $@..."
-	@g++ $(PROJ_OBJ) $(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(TK_TGTS) $(LIBS)) -o $@
+	@$(CXX) $(PROJ_OBJ) $(LIBS) $(shell xml2-config --libs) -lpthread -o $@
 
 ifeq ($(findstring clean,$(MAKECMDGOALS)),)
 -include $(DEPENDS)
 endif
 
+%.a :
+	@echo "ERROR: $@ was not found.  You may need to compile the Tekkotsu framework."
+	@echo "Press return to attempt to build it, ctl-C to cancel."
+	@read;
+	$(MAKE) -C $(TEKKOTSU_ROOT) compile
+
 %.d :
 	@mkdir -p $(dir $@)
 	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
 	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
 	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
 
-tk_bd:
-	@echo "Making Tekkotsu files..."
-	@export TEKKOTSU_TARGET_PLATFORM=PLATFORM_LOCAL && $(MAKE) -C $(TEMPLATE_PROJECT) $(TK_TGTS)
-
-
 %.o:
 	@mkdir -p $(dir $@)
 	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
@@ -80,5 +74,15 @@
 	test $$retval -eq 0; \
 
 clean:
-	rm -f $(BIN) $(PROJ_OBJ) $(DEPENDS) *~
+	rm -rf $(BIN) $(PROJECT_BUILDDIR) *~
 
+test: $(BIN)
+	@for x in * ; do \
+		if [ -r "ideal-$$x" ] ; then \
+			if diff -u "ideal-$$x" "$$x" ; then \
+				echo "Test '$$x' passed"; \
+			else \
+				echo "Test output '$$x' does not match ideal"; \
+			fi; \
+		fi; \
+	done
\ No newline at end of file
diff -urdN ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Entries ./tools/safemot/from_cmpack02/CVS/Entries
--- ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/from_cmpack02/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,15 @@
+/dance.mot/1.1/Fri May  2 04:57:52 2003//Ttekkotsu-2_4
+/gu_back.mot/1.1/Fri May  2 04:57:52 2003//Ttekkotsu-2_4
+/gu_front.mot/1.1/Fri May  2 04:57:52 2003//Ttekkotsu-2_4
+/gu_side.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_bump.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_diag.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_dive.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_fwd.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_grab.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_head.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_heads.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_hold.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/k_punch.mot/1.1/Fri May  2 04:57:53 2003//Ttekkotsu-2_4
+/readme.txt/1.1/Fri Apr 16 20:23:09 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Repository ./tools/safemot/from_cmpack02/CVS/Repository
--- ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/from_cmpack02/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/safemot/from_cmpack02
diff -urdN ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Root ./tools/safemot/from_cmpack02/CVS/Root
--- ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/from_cmpack02/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Tag ./tools/safemot/from_cmpack02/CVS/Tag
--- ../Tekkotsu_2.3/tools/safemot/from_cmpack02/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/safemot/from_cmpack02/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/safemot/tekkotsu.cfg ./tools/safemot/tekkotsu.cfg
--- ../Tekkotsu_2.3/tools/safemot/tekkotsu.cfg	Mon Nov  8 16:48:19 2004
+++ ./tools/safemot/tekkotsu.cfg	Mon Nov  8 16:48:19 2004
@@ -1,7 +1,7 @@
 ##################################################################
 ##################   Tekkotsu::safemot config   ##################
 ##################################################################
-##################### $Name: tekkotsu-2_3 $ ######################
+##################### $Name: tekkotsu-2_4 $ ######################
 ####################### $Revision: 1.1 $ ########################
 ################## $Date: 2004/11/08 21:48:19 $ ##################
 ##################################################################
diff -urdN ../Tekkotsu_2.3/tools/seg/CVS/Entries ./tools/seg/CVS/Entries
--- ../Tekkotsu_2.3/tools/seg/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/seg/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,24 @@
+/ClassPathModifier.java/1.1/Sun Jul 27 01:55:58 2003//Ttekkotsu-2_4
+/ColorControlPanel.java/1.1/Wed Aug 10 01:53:10 2005//Ttekkotsu-2_4
+/ColorConverter.java/1.1/Sun Jul 27 01:55:59 2003//Ttekkotsu-2_4
+/DogConfig.java/1.1/Sun Jul 27 01:55:59 2003//Ttekkotsu-2_4
+/DogConfigFTP.java/1.2/Thu Oct  9 06:29:39 2003//Ttekkotsu-2_4
+/ImageData.java/1.2/Wed Jan 21 03:32:26 2004//Ttekkotsu-2_4
+/ImageShow.java/1.5/Mon May  9 19:19:51 2005//Ttekkotsu-2_4
+/ImageShowArea.java/1.1/Tue May 24 02:32:40 2005//Ttekkotsu-2_4
+/Listener.java/1.1/Sun Jul 27 01:55:59 2003//Ttekkotsu-2_4
+/Makefile/1.2/Wed Oct  8 18:26:51 2003//Ttekkotsu-2_4
+/MoveIndex.java/1.1/Thu Oct  9 06:30:08 2003//Ttekkotsu-2_4
+/README/1.1/Mon Sep 22 09:51:26 2003//Ttekkotsu-2_4
+/TCPListener.java/1.1/Sun Jul 27 01:55:59 2003//Ttekkotsu-2_4
+/TextListener.java/1.1/Sun Jul 27 01:55:59 2003//Ttekkotsu-2_4
+/ThresholdAdd.java/1.2/Thu Oct  9 06:29:39 2003//Ttekkotsu-2_4
+/ThresholdMerge.java/1.2/Thu Oct  9 06:29:39 2003//Ttekkotsu-2_4
+/TileTrain.java/1.1/Tue Sep 28 20:51:43 2004//Ttekkotsu-2_4
+/TrainCanvas.java/1.1/Wed Aug 10 01:53:10 2005//Ttekkotsu-2_4
+/UseThresh.java/1.4/Thu Oct  9 19:54:36 2003//Ttekkotsu-2_4
+/VisionFilter.java/1.2/Mon Jul 28 06:31:46 2003//Ttekkotsu-2_4
+/VisionSegment.java/1.2/Wed Jan 21 03:32:26 2004//Ttekkotsu-2_4
+/VisionTrain.java/1.9/Wed Aug 10 01:53:10 2005//Ttekkotsu-2_4
+/createyuv.m/1.1/Sat Aug  9 03:49:37 2003//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/seg/CVS/Repository ./tools/seg/CVS/Repository
--- ../Tekkotsu_2.3/tools/seg/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/seg/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/seg
diff -urdN ../Tekkotsu_2.3/tools/seg/CVS/Root ./tools/seg/CVS/Root
--- ../Tekkotsu_2.3/tools/seg/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/seg/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/seg/CVS/Tag ./tools/seg/CVS/Tag
--- ../Tekkotsu_2.3/tools/seg/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/seg/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/seg/ColorControlPanel.java ./tools/seg/ColorControlPanel.java
--- ../Tekkotsu_2.3/tools/seg/ColorControlPanel.java	Wed Dec 31 19:00:00 1969
+++ ./tools/seg/ColorControlPanel.java	Tue Aug  9 21:53:10 2005
@@ -0,0 +1,128 @@
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.io.*;
+
+class ColorControlPanel extends JFrame implements ActionListener,
+    ListSelectionListener {
+  Container root;
+  JTextField colorname;
+  JList colorlist;
+  DefaultListModel list;
+  JScrollPane colorlistscroll;
+  JButton remove, clear, save, imageview, invert;
+  int curcolor;
+
+  TrainCanvas trainCanvas;
+  ImageShow imageShow;
+
+  public ColorControlPanel (TrainCanvas trainCanvas, ImageShow imageShow) {
+    this.trainCanvas=trainCanvas;
+    this.imageShow=imageShow;
+    imageShow.addMouseMotionListener(trainCanvas);
+    imageShow.addMouseListener(trainCanvas);
+
+    setSize(new Dimension (120,350));
+    setLocation(800,50);
+
+    setResizable(false);
+    root=this.getContentPane();
+    root.setLayout(new FlowLayout());
+
+    colorname=new JTextField(10);
+    colorname.addActionListener(this);
+    root.add(colorname);
+
+    list=new DefaultListModel();
+    colorlist=new JList(list);
+    colorlist.setFixedCellWidth(90);
+    colorlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+    colorlist.addListSelectionListener(this);
+
+    colorlistscroll=new JScrollPane(colorlist,
+                       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
+                       JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+    root.add(colorlistscroll);
+
+    remove=new JButton("remove");
+    remove.addActionListener(this);
+    root.add(remove);
+
+    clear=new JButton("clear");
+    clear.addActionListener(this);
+    root.add(clear);
+
+    invert=new JButton("invert");
+    invert.addActionListener(this);
+    root.add(invert);
+
+    imageview=new JButton("image view");
+    imageview.addActionListener(this);
+    root.add(imageview);
+
+    save=new JButton("save");
+    save.addActionListener(this);
+    root.add(save);
+
+    setCurColor(-1);
+    show();
+  }
+
+  public void actionPerformed(ActionEvent e) {
+    if (e.getSource()==save) {
+      JFileChooser chooser=new JFileChooser();
+      chooser.setSelectedFile(new File("default.tm"));
+      int returnval=chooser.showSaveDialog(save);
+      if (returnval==JFileChooser.APPROVE_OPTION) {
+        trainCanvas.save(chooser.getSelectedFile().getAbsolutePath());
+      }
+    } else if (e.getSource()==clear) {
+      trainCanvas.clear();
+    } else if (e.getSource()==invert) {
+      trainCanvas.invert();
+    } else if (e.getSource()==remove) {
+      trainCanvas.remove((String)list.get(curcolor));
+      list.remove(curcolor);
+      setCurColor(-1);
+    } else if (e.getSource()==imageview) {
+      imageShow.show();
+    } else if (e.getSource()==colorname) {
+      String s=e.getActionCommand();
+      if (!s.equals("")) {
+        int i=0;
+        while (i<list.getSize() && !list.get(i).equals(s)) {
+          i++;
+        }
+        if (i==list.getSize()) {
+          list.addElement(s);
+          colorname.setText("");
+          colorlist.setSelectedIndex(i);
+        }
+      }
+    }
+  }
+
+  public void valueChanged(ListSelectionEvent e) {
+    if (!e.getValueIsAdjusting()) {
+      setCurColor(colorlist.getSelectedIndex());
+    }
+  }
+
+  void setCurColor(int index) {
+    curcolor=index;
+
+    if (index<0) {
+      remove.setEnabled(false);
+      clear.setEnabled(false);
+      trainCanvas.setCurColor(null);
+    } else {
+      remove.setEnabled(true);
+      clear.setEnabled(true);
+      trainCanvas.setCurColor((String)list.get(curcolor));
+    }
+  }
+}
diff -urdN ../Tekkotsu_2.3/tools/seg/ImageShow.java ./tools/seg/ImageShow.java
--- ../Tekkotsu_2.3/tools/seg/ImageShow.java	Wed Feb 18 00:10:13 2004
+++ ./tools/seg/ImageShow.java	Mon May  9 15:19:51 2005
@@ -55,6 +55,7 @@
 
     setBackground(Color.black);
     setSize(imageData.image_width*2, imageData.image_height*2);
+    setTitle(args[0]);
     _image=new BufferedImage(imageData.image_width, imageData.image_height,
         BufferedImage.TYPE_INT_RGB);
    
@@ -112,6 +113,8 @@
 				imageData.loadRGBFileAsRGB(imglist[curimg]);
 			else
 				imageData.loadYUVFileAsRGB(imglist[curimg]);
+
+      setTitle(imglist[curimg]);
       int[] data=imageData.getPixels();
       showImage(data, tmap, imageData.image_width, imageData.image_height);
     }
diff -urdN ../Tekkotsu_2.3/tools/seg/ImageShowArea.java ./tools/seg/ImageShowArea.java
--- ../Tekkotsu_2.3/tools/seg/ImageShowArea.java	Wed Dec 31 19:00:00 1969
+++ ./tools/seg/ImageShowArea.java	Mon May 23 22:32:40 2005
@@ -0,0 +1,151 @@
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.io.*;
+import java.util.*;
+import java.awt.geom.*;
+
+public class ImageShowArea extends JFrame implements KeyListener {
+  BufferedImage _image;
+  String[] imglist;
+  byte[] tmap;
+  ImageData imageData;
+  int curimg;
+	boolean isRGB;
+
+    Polygon curPoly;
+    Area curArea;
+
+
+  public static void main(String args[]) {
+    if (args.length<1)
+			usageAndExit();
+		boolean isRGB=true;
+		if(args[0].equals("-isRGB"))
+			isRGB=true;
+		else if(args[0].equals("-isYUV"))
+			isRGB=false;
+		else {
+			System.out.println(args[0]+" is not valid color mode");
+			usageAndExit();
+		}
+		
+		String files[]=new String[args.length-1];
+		for(int i=0; i<files.length; i++)
+			files[i]=args[i+1];
+
+    ImageShowArea imageShow=new ImageShowArea(isRGB,files);
+    imageShow.show();
+    imageShow.addWindowListener(new WindowAdapter() {
+        public void windowClosing(WindowEvent e) { System.exit(0); } });
+  }
+
+
+	public static void usageAndExit() {
+		System.out.println("usage: java ImageShow (-isRGB|-isYUV) raw_image [raw images]");
+		System.exit(1);
+	}
+
+  public ImageShowArea (boolean isRGB, String args[]) {
+      curPoly = null;
+      curArea = null;
+
+    imageData=new ImageData();
+		this.isRGB=isRGB;
+		if(isRGB)
+			imageData.loadRGBFileAsRGB(args[0]);
+		else
+			imageData.loadYUVFileAsRGB(args[0]);
+
+    int[] data=imageData.getPixels();
+
+    setBackground(Color.black);
+    setSize(imageData.image_width*2, imageData.image_height*2);
+    setTitle(args[0]);
+    _image=new BufferedImage(imageData.image_width, imageData.image_height,
+        BufferedImage.TYPE_INT_RGB);
+   
+    showImage(data, tmap, imageData.image_width, imageData.image_height);
+
+    imglist=new String[args.length];
+    curimg=0;
+    for (int i=0; i<args.length; i++) {
+      imglist[i]=args[i];
+    }
+
+    addKeyListener(this);
+  }
+
+  void showImage(int[] data, byte[] tmap, int width, int height) {
+    _image.getRaster().setDataElements(0,0,width,height,data);
+    repaint();
+  }
+
+    public void setCurArea(Area _curArea)
+    {
+	curArea = _curArea;
+	repaint();
+    }
+
+    public void setCurPoly(Polygon _curPoly)
+    {
+	curPoly = _curPoly;
+	repaint();
+    }
+
+  public void paint(Graphics graphics) {
+    Dimension sz=getSize();
+    if (_image!=null)
+      graphics.drawImage(_image, 0, 0, sz.width, sz.height, null);
+
+    graphics.setColor(Color.white);
+    if (curArea!=null)
+      ((Graphics2D)graphics).draw(curArea);
+
+    if (curPoly!=null)
+      ((Graphics2D)graphics).draw(curPoly);
+  }
+
+  public int getPixel(int x, int y) {
+    Dimension sz=getSize();
+    x=(x*_image.getWidth())/sz.width;
+    y=(y*_image.getHeight())/sz.height;
+    return _image.getRGB(x, y);
+  }
+
+  public void keyPressed(KeyEvent e) {
+    if (e.getKeyCode()==KeyEvent.VK_LEFT ||
+        e.getKeyCode()==KeyEvent.VK_UP ||
+        e.getKeyCode()==KeyEvent.VK_PAGE_UP ||
+        e.getKeyCode()==KeyEvent.VK_KP_UP ||
+        e.getKeyCode()==KeyEvent.VK_KP_LEFT) {
+      curimg--;
+      if (curimg<0) curimg+=imglist.length;
+			if(isRGB)
+				imageData.loadRGBFileAsRGB(imglist[curimg]);
+			else
+				imageData.loadYUVFileAsRGB(imglist[curimg]);
+      int[] data=imageData.getPixels();
+      showImage(data, tmap, imageData.image_width, imageData.image_height);
+    } else if (e.getKeyCode()==KeyEvent.VK_RIGHT ||
+        e.getKeyCode()==KeyEvent.VK_DOWN ||
+        e.getKeyCode()==KeyEvent.VK_PAGE_DOWN ||
+        e.getKeyCode()==KeyEvent.VK_KP_DOWN ||
+        e.getKeyCode()==KeyEvent.VK_KP_RIGHT) {
+      curimg++;
+      if (curimg>=imglist.length) curimg-=imglist.length;
+			if(isRGB)
+				imageData.loadRGBFileAsRGB(imglist[curimg]);
+			else
+				imageData.loadYUVFileAsRGB(imglist[curimg]);
+
+      setTitle(imglist[curimg]);
+      int[] data=imageData.getPixels();
+      showImage(data, tmap, imageData.image_width, imageData.image_height);
+    }
+  }
+  public void keyReleased(KeyEvent e) { }
+  public void keyTyped(KeyEvent e) { }
+}
diff -urdN ../Tekkotsu_2.3/tools/seg/TrainCanvas.java ./tools/seg/TrainCanvas.java
--- ../Tekkotsu_2.3/tools/seg/TrainCanvas.java	Wed Dec 31 19:00:00 1969
+++ ./tools/seg/TrainCanvas.java	Tue Aug  9 21:53:10 2005
@@ -0,0 +1,349 @@
+import java.awt.image.*;
+import java.awt.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.util.*;
+import java.awt.geom.*;
+import java.io.*;
+
+class TrainCanvas extends Canvas implements MouseListener,
+    MouseMotionListener, KeyListener {
+  BufferedImage image;
+  BufferedImage cachedplot;
+  BufferedImage inv_cachedplot;
+
+  Graphics2D graphics;
+  Polygon curPoly;
+  int lastx, lasty;
+  float f_width, f_height, f_offset;
+
+  Area curArea;
+  String curColor;
+  int curSelectModifier;
+  int curSelectModified;
+
+  Point imageHint;
+
+  Hashtable areasHash;
+
+  boolean inverted;
+
+  public static final int MODIFIER_NONE=0;
+  public static final int MODIFIER_SHIFT=1;
+  public static final int MODIFIER_CTRL=2;
+
+  float[] xy;
+  int[] rgb;
+
+  public TrainCanvas() {
+    setBackground(Color.black);
+    addMouseListener(this);
+    addMouseMotionListener(this);
+    curSelectModifier=MODIFIER_NONE;
+    curSelectModified=MODIFIER_NONE;
+    addKeyListener(this);
+    areasHash=new Hashtable();
+    inverted=false;
+    imageHint=null;
+  }
+
+  public void plotImage(float[] xy, int[] rgb) {
+    this.xy=xy;
+    this.rgb=rgb;
+    Dimension d=getSize();
+    f_width=(float)d.width-41;
+    f_height=(float)d.height-41;
+    f_offset=20;
+    cachedplot=new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
+    inv_cachedplot=
+               new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
+
+    graphics=(Graphics2D)cachedplot.getGraphics();
+    Graphics2D inv_graphics=(Graphics2D)inv_cachedplot.getGraphics();
+
+    inv_graphics.setColor(Color.white);
+    inv_graphics.fillRect(0,0,d.width, d.height);
+
+    for (int i=0; i<rgb.length; i++) {
+      //      draws thin
+      //      cachedplot.setRGB((int)(xy[i*2]*f_width),
+      //                        (int)(xy[i*2+1]*f_height), rgb[i]);
+
+      // draws thick
+      graphics.setColor(new Color(rgb[i]));
+      graphics.drawRect((int)(xy[i*2]*f_width+f_offset),
+                        (int)(xy[i*2+1]*f_height+f_offset), 1,1);
+
+      inv_graphics.setColor(new Color(rgb[i]));
+      inv_graphics.drawRect((int)(xy[i*2]*f_width+f_offset),
+                        (int)(xy[i*2+1]*f_height+f_offset), 1,1);
+    }
+
+    image=new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
+    graphics=(Graphics2D)image.getGraphics();
+//    graphics.drawImage(cachedplot,0,0,this);
+    redrawScene();
+    repaint();
+  }
+
+  public void mousePressed(MouseEvent e) {
+    if (curArea==null) return;
+    if (e.getButton()!=MouseEvent.BUTTON1) return;
+
+    curSelectModified=curSelectModifier;
+
+    if (curSelectModified!=MODIFIER_SHIFT
+        && curSelectModified!=MODIFIER_CTRL)
+      curArea.reset();
+
+    curPoly=new Polygon();
+    lastx=e.getX();
+    lasty=e.getY();
+    curPoly.addPoint(e.getX(), e.getY());
+    repaint();
+  }
+
+  public void mouseDragged(MouseEvent e) {
+    if (curArea==null) return;
+
+    int x=e.getX();
+    int y=e.getY();
+    if ((Math.abs(x-lastx)+Math.abs(y-lasty))>2) {
+      curPoly.addPoint(e.getX(), e.getY());
+      lastx=x;
+      lasty=y;
+      repaint();
+    }
+  }
+
+  public void mouseReleased(MouseEvent e) {
+    if (curArea==null) return;
+    if (e.getButton()!=MouseEvent.BUTTON1) return;
+
+    curPoly.addPoint(e.getX(), e.getY());
+    if (curPoly.npoints>=3) {
+      if (curSelectModified==MODIFIER_CTRL) curArea.subtract(new Area(curPoly));
+      else curArea.add(new Area(curPoly));
+    }
+    curPoly=null;
+    repaint();
+  }
+
+  public void mouseMoved(MouseEvent e){
+    Object source=e.getSource();
+    if (source instanceof ImageShow) {
+      ImageShow imageShow=(ImageShow)source;
+      int rgb=imageShow.getPixel(e.getX(), e.getY());
+      float[] xy=VisionTrain.colorConverter.getColor(rgb);
+      int x=(int)(xy[0]*f_width+f_offset);
+      int y=(int)(xy[1]*f_height+f_offset);
+      imageHint=new Point(x, y);
+      repaint();
+    }
+  }
+
+  public void mouseClicked(MouseEvent e){}
+  public void mouseExited(MouseEvent e){
+    if (e.getSource() instanceof ImageShow) {
+      imageHint=null;
+      repaint();
+    }
+  }
+  public void mouseEntered(MouseEvent e){}
+  public void updateLocation(MouseEvent e){}
+
+  public void paint(Graphics g) {
+    update(g);
+  }
+
+  public void update(Graphics g) {
+    Graphics2D g2d=(Graphics2D) g;
+    if (image!=null) g.drawImage(image, 0, 0, this);
+    if (inverted)
+      g2d.setColor(Color.black);
+    else
+      g2d.setColor(Color.white);
+
+    if (curArea!=null)
+      g2d.draw(curArea);
+
+    if (curPoly!=null)
+      g2d.draw(curPoly);
+
+    if (imageHint!=null) {
+      g2d.drawRect(imageHint.x-2, imageHint.y-2, 5, 5);
+    }
+  }
+
+  public void setCurColor(String color) {
+    curColor=color;
+    if (color==null) {
+      curArea=null;
+      return;
+    }
+
+    curArea=(Area)areasHash.get(color);
+    if (curArea==null) {
+      curArea=new Area();
+      areasHash.put(color, curArea);
+    }
+    redrawScene();
+  }
+
+  public void clear () {
+    if (curArea==null) return;
+    curArea.reset();
+    redrawScene();
+  }
+
+  public void invert () {
+    inverted=!inverted;
+    redrawScene();
+  }
+
+  public void remove(String color) {
+    curColor=null;
+    curArea=null;
+    areasHash.remove(color);
+    redrawScene();
+  }
+
+  public void redrawScene() {
+    if (inverted)
+      graphics.drawImage(inv_cachedplot,0,0,this);
+    else 
+      graphics.drawImage(cachedplot,0,0,this);
+    graphics.setColor(Color.gray);
+    Collection values=areasHash.values();
+    for (Iterator i=values.iterator(); i.hasNext(); ) {
+      Area area=(Area)i.next();
+      if (area!=curArea)
+        graphics.draw(area);
+    }
+    repaint();  
+  }
+
+  public void keyPressed(KeyEvent e) {
+    if (e.getKeyCode()==KeyEvent.VK_SHIFT) {
+      curSelectModifier=MODIFIER_SHIFT;
+    } else if (e.getKeyCode()==KeyEvent.VK_CONTROL) {
+      curSelectModifier=MODIFIER_CTRL;
+    }
+  }
+
+  public void keyReleased(KeyEvent e) {
+    if (e.getKeyCode()==KeyEvent.VK_SHIFT
+        ||e.getKeyCode()==KeyEvent.VK_CONTROL) {
+      curSelectModifier=MODIFIER_NONE;
+    }
+  }
+
+  public void keyTyped(KeyEvent e) { }
+
+  public void save (String filename) {
+    int dotpos=filename.lastIndexOf('.');
+    if (dotpos>0) filename=filename.substring(0,dotpos);
+    
+    Enumeration colors=areasHash.keys();
+    ArrayList colornames=new ArrayList(20);
+    while (colors.hasMoreElements()) colornames.add(colors.nextElement());
+    Collections.sort(colornames);
+    ArrayList areas=new ArrayList(20);
+
+    for (Iterator i=colornames.iterator(); i.hasNext();
+         areas.add(areasHash.get(i.next())));
+    
+    int size_y=16, size_u=64, size_v=64;
+    byte[] tmap=new byte[size_y*size_u*size_v];
+
+    float[] hsb=new float[3];
+    int y, u, v, r, g, b, h, s;
+    int iy, iu, iv, i;
+
+    for (iy=0; iy<16; iy++) {
+      for (iu=0; iu<64; iu++) {
+        for (iv=0; iv<64; iv++) {
+          y=iy<<4; u=iu<<2; v=iv<<2;
+          u=u*2-255;
+          v=v*2-255;
+          r=y+u;
+          b=y+v;
+          u=u>>1;
+          v=(v>>2)-(v>>4);
+          g=y-u-v;
+          if (r<0) r=0; if (g<0) g=0; if (b<0) b=0;
+          if (r>255) r=255; if (g>255) g=255; if (b>255) b=255;
+          float[] xy=VisionTrain.colorConverter.getColor(r, g, b);
+          h=(int)(xy[0]*f_width+f_offset);
+          s=(int)(xy[1]*f_height+f_offset);
+          Point point=new Point(h, s);
+          for (i=0; i<areas.size(); i++) {
+            Area area = (Area) areas.get(i);
+            if (area.contains(point)) {
+              tmap[(iy*size_u+iu)*size_v+iv]=(byte)(i+1);
+              break;
+            }
+          }
+        }
+      }
+    }
+
+    try {
+      FileOutputStream file_tm_fos=new FileOutputStream(filename + ".tm");
+      OutputStreamWriter file_tm_osw=new OutputStreamWriter(file_tm_fos);
+      file_tm_osw.write("TMAP\nYUV8\n" +
+          size_y + " " + size_u + " " + size_v + "\n");
+      file_tm_osw.flush();
+      file_tm_fos.write(tmap);
+      file_tm_osw.close();
+    } catch (Exception ex) {
+      System.out.println("Error saving to "+filename +".tm: " + ex);
+    }
+
+    int[][] avgcolors=new int[areas.size()][4]; 
+
+    int skip=(rgb.length/10000)+1;
+    for (i=0; i<rgb.length; i+=skip) {
+      for (int a=0; a<areas.size(); a++) {
+        Area area=(Area)areas.get(a);
+        Point p=new Point((int)(xy[i*2]*f_width+f_offset),
+                          (int)(xy[i*2+1]*f_height+f_offset));
+        if (area.contains(p)) {
+          avgcolors[a][0]+=(rgb[i]>>16)&0xff;
+          avgcolors[a][1]+=(rgb[i]>>8)&0xff;
+          avgcolors[a][2]+=rgb[i]&0xff;
+          avgcolors[a][3]++;
+        }
+      }
+    }
+
+    for (i=0; i<avgcolors.length; i++) {
+      if (avgcolors[i][3]>0) {
+        avgcolors[i][0]=avgcolors[i][0]/avgcolors[i][3];
+        avgcolors[i][1]=avgcolors[i][1]/avgcolors[i][3];
+        avgcolors[i][2]=avgcolors[i][2]/avgcolors[i][3];
+      } else {
+        avgcolors[i][0]=0;
+        avgcolors[i][1]=0;
+        avgcolors[i][2]=0;
+      }
+    }
+ 
+    try {
+      FileWriter file_col_fw=new FileWriter(filename + ".col");
+      file_col_fw.write("0 (128 128 128) \"unclassified\" 8 1.00\n");
+      for (i=0; i<areas.size(); i++) {
+        file_col_fw.write((i+1)+ " (" +
+                          avgcolors[i][0] + " " +
+                          avgcolors[i][1] + " " +
+                          avgcolors[i][2] + ") " +
+                          "\"" + colornames.get(i)+ "\" 8 0.75\n");
+      }
+
+      file_col_fw.close();
+    } catch (Exception ex) {
+      System.out.println("Error saving to "+filename + ".col: " + ex);
+    }
+  }
+}
diff -urdN ../Tekkotsu_2.3/tools/seg/VisionTrain.java ./tools/seg/VisionTrain.java
--- ../Tekkotsu_2.3/tools/seg/VisionTrain.java	Tue Feb 24 17:17:38 2004
+++ ./tools/seg/VisionTrain.java	Tue Aug  9 21:53:10 2005
@@ -81,463 +81,3 @@
   }
 }
 
-class ColorControlPanel extends JFrame implements ActionListener,
-    ListSelectionListener {
-  Container root;
-  JTextField colorname;
-  JList colorlist;
-  DefaultListModel list;
-  JScrollPane colorlistscroll;
-  JButton remove, clear, save, imageview, invert;
-  int curcolor;
-
-  TrainCanvas trainCanvas;
-  ImageShow imageShow;
-
-  public ColorControlPanel (TrainCanvas trainCanvas, ImageShow imageShow) {
-    this.trainCanvas=trainCanvas;
-    this.imageShow=imageShow;
-    imageShow.addMouseMotionListener(trainCanvas);
-    imageShow.addMouseListener(trainCanvas);
-
-    setSize(new Dimension (120,350));
-    setLocation(800,50);
-
-    setResizable(false);
-    root=this.getContentPane();
-    root.setLayout(new FlowLayout());
-
-    colorname=new JTextField(10);
-    colorname.addActionListener(this);
-    root.add(colorname);
-
-    list=new DefaultListModel();
-    colorlist=new JList(list);
-    colorlist.setFixedCellWidth(90);
-    colorlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
-    colorlist.addListSelectionListener(this);
-
-    colorlistscroll=new JScrollPane(colorlist,
-                       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
-                       JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
-    root.add(colorlistscroll);
-
-    remove=new JButton("remove");
-    remove.addActionListener(this);
-    root.add(remove);
-
-    clear=new JButton("clear");
-    clear.addActionListener(this);
-    root.add(clear);
-
-    invert=new JButton("invert");
-    invert.addActionListener(this);
-    root.add(invert);
-
-    imageview=new JButton("image view");
-    imageview.addActionListener(this);
-    root.add(imageview);
-
-    save=new JButton("save");
-    save.addActionListener(this);
-    root.add(save);
-
-    setCurColor(-1);
-    show();
-  }
-
-  public void actionPerformed(ActionEvent e) {
-    if (e.getSource()==save) {
-      JFileChooser chooser=new JFileChooser();
-      chooser.setSelectedFile(new File("default.tm"));
-      int returnval=chooser.showSaveDialog(save);
-      if (returnval==JFileChooser.APPROVE_OPTION) {
-        trainCanvas.save(chooser.getSelectedFile().getName());   
-      }
-    } else if (e.getSource()==clear) {
-      trainCanvas.clear();
-    } else if (e.getSource()==invert) {
-      trainCanvas.invert();
-    } else if (e.getSource()==remove) {
-      trainCanvas.remove((String)list.get(curcolor));
-      list.remove(curcolor);
-      setCurColor(-1);
-    } else if (e.getSource()==imageview) {
-      imageShow.show();
-    } else if (e.getSource()==colorname) {
-      String s=e.getActionCommand();
-      if (!s.equals("")) {
-        int i=0;
-        while (i<list.getSize() && !list.get(i).equals(s)) {
-          i++;
-        }
-        if (i==list.getSize()) {
-          list.addElement(s);
-          colorname.setText("");
-          colorlist.setSelectedIndex(i);
-        }
-      }
-    }
-  }
-
-  public void valueChanged(ListSelectionEvent e) {
-    if (!e.getValueIsAdjusting()) {
-      setCurColor(colorlist.getSelectedIndex());
-    }
-  }
-
-  void setCurColor(int index) {
-    curcolor=index;
-
-    if (index<0) {
-      remove.setEnabled(false);
-      clear.setEnabled(false);
-      trainCanvas.setCurColor(null);
-    } else {
-      remove.setEnabled(true);
-      clear.setEnabled(true);
-      trainCanvas.setCurColor((String)list.get(curcolor));
-    }
-  }
-}
-
-class TrainCanvas extends Canvas implements MouseListener,
-    MouseMotionListener, KeyListener {
-  BufferedImage image;
-  BufferedImage cachedplot;
-  BufferedImage inv_cachedplot;
-
-  Graphics2D graphics;
-  Polygon curPoly;
-  int lastx, lasty;
-  float f_width, f_height, f_offset;
-
-  Area curArea;
-  String curColor;
-  int curSelectModifier;
-  int curSelectModified;
-
-  Point imageHint;
-
-  Hashtable areasHash;
-
-  boolean inverted;
-
-  public static final int MODIFIER_NONE=0;
-  public static final int MODIFIER_SHIFT=1;
-  public static final int MODIFIER_CTRL=2;
-
-  float[] xy;
-  int[] rgb;
-
-  public TrainCanvas() {
-    setBackground(Color.black);
-    addMouseListener(this);
-    addMouseMotionListener(this);
-    curSelectModifier=MODIFIER_NONE;
-    curSelectModified=MODIFIER_NONE;
-    addKeyListener(this);
-    areasHash=new Hashtable();
-    inverted=false;
-    imageHint=null;
-  }
-
-  public void plotImage(float[] xy, int[] rgb) {
-    this.xy=xy;
-    this.rgb=rgb;
-    Dimension d=getSize();
-    f_width=(float)d.width-41;
-    f_height=(float)d.height-41;
-    f_offset=20;
-    cachedplot=new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
-    inv_cachedplot=
-               new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
-
-    graphics=(Graphics2D)cachedplot.getGraphics();
-    Graphics2D inv_graphics=(Graphics2D)inv_cachedplot.getGraphics();
-
-    inv_graphics.setColor(Color.white);
-    inv_graphics.fillRect(0,0,d.width, d.height);
-
-    for (int i=0; i<rgb.length; i++) {
-      //      draws thin
-      //      cachedplot.setRGB((int)(xy[i*2]*f_width),
-      //                        (int)(xy[i*2+1]*f_height), rgb[i]);
-
-      // draws thick
-      graphics.setColor(new Color(rgb[i]));
-      graphics.drawRect((int)(xy[i*2]*f_width+f_offset),
-                        (int)(xy[i*2+1]*f_height+f_offset), 1,1);
-
-      inv_graphics.setColor(new Color(rgb[i]));
-      inv_graphics.drawRect((int)(xy[i*2]*f_width+f_offset),
-                        (int)(xy[i*2+1]*f_height+f_offset), 1,1);
-    }
-
-    image=new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
-    graphics=(Graphics2D)image.getGraphics();
-//    graphics.drawImage(cachedplot,0,0,this);
-    redrawScene();
-    repaint();
-  }
-
-  public void mousePressed(MouseEvent e) {
-    if (curArea==null) return;
-    if (e.getButton()!=MouseEvent.BUTTON1) return;
-
-    curSelectModified=curSelectModifier;
-
-    if (curSelectModified!=MODIFIER_SHIFT
-        && curSelectModified!=MODIFIER_CTRL)
-      curArea.reset();
-
-    curPoly=new Polygon();
-    lastx=e.getX();
-    lasty=e.getY();
-    curPoly.addPoint(e.getX(), e.getY());
-    repaint();
-  }
-
-  public void mouseDragged(MouseEvent e) {
-    if (curArea==null) return;
-
-    int x=e.getX();
-    int y=e.getY();
-    if ((Math.abs(x-lastx)+Math.abs(y-lasty))>2) {
-      curPoly.addPoint(e.getX(), e.getY());
-      lastx=x;
-      lasty=y;
-      repaint();
-    }
-  }
-
-  public void mouseReleased(MouseEvent e) {
-    if (curArea==null) return;
-    if (e.getButton()!=MouseEvent.BUTTON1) return;
-
-    curPoly.addPoint(e.getX(), e.getY());
-    if (curPoly.npoints>=3) {
-      if (curSelectModified==MODIFIER_CTRL) curArea.subtract(new Area(curPoly));
-      else curArea.add(new Area(curPoly));
-    }
-    curPoly=null;
-    repaint();
-  }
-
-  public void mouseMoved(MouseEvent e){
-    Object source=e.getSource();
-    if (source instanceof ImageShow) {
-      ImageShow imageShow=(ImageShow)source;
-      int rgb=imageShow.getPixel(e.getX(), e.getY());
-      float[] xy=VisionTrain.colorConverter.getColor(rgb);
-      int x=(int)(xy[0]*f_width+f_offset);
-      int y=(int)(xy[1]*f_height+f_offset);
-      imageHint=new Point(x, y);
-      repaint();
-    }
-  }
-
-  public void mouseClicked(MouseEvent e){}
-  public void mouseExited(MouseEvent e){
-    if (e.getSource() instanceof ImageShow) {
-      imageHint=null;
-      repaint();
-    }
-  }
-  public void mouseEntered(MouseEvent e){}
-  public void updateLocation(MouseEvent e){}
-
-  public void paint(Graphics g) {
-    update(g);
-  }
-
-  public void update(Graphics g) {
-    Graphics2D g2d=(Graphics2D) g;
-    if (image!=null) g.drawImage(image, 0, 0, this);
-    if (inverted)
-      g2d.setColor(Color.black);
-    else
-      g2d.setColor(Color.white);
-
-    if (curArea!=null)
-      g2d.draw(curArea);
-
-    if (curPoly!=null)
-      g2d.draw(curPoly);
-
-    if (imageHint!=null) {
-      g2d.drawRect(imageHint.x-2, imageHint.y-2, 5, 5);
-    }
-  }
-
-  public void setCurColor(String color) {
-    curColor=color;
-    if (color==null) {
-      curArea=null;
-      return;
-    }
-
-    curArea=(Area)areasHash.get(color);
-    if (curArea==null) {
-      curArea=new Area();
-      areasHash.put(color, curArea);
-    }
-    redrawScene();
-  }
-
-  public void clear () {
-    if (curArea==null) return;
-    curArea.reset();
-    redrawScene();
-  }
-
-  public void invert () {
-    inverted=!inverted;
-    redrawScene();
-  }
-
-  public void remove(String color) {
-    curColor=null;
-    curArea=null;
-    areasHash.remove(color);
-    redrawScene();
-  }
-
-  public void redrawScene() {
-    if (inverted)
-      graphics.drawImage(inv_cachedplot,0,0,this);
-    else 
-      graphics.drawImage(cachedplot,0,0,this);
-    graphics.setColor(Color.gray);
-    Collection values=areasHash.values();
-    for (Iterator i=values.iterator(); i.hasNext(); ) {
-      Area area=(Area)i.next();
-      if (area!=curArea)
-        graphics.draw(area);
-    }
-    repaint();  
-  }
-
-  public void keyPressed(KeyEvent e) {
-    if (e.getKeyCode()==KeyEvent.VK_SHIFT) {
-      curSelectModifier=MODIFIER_SHIFT;
-    } else if (e.getKeyCode()==KeyEvent.VK_CONTROL) {
-      curSelectModifier=MODIFIER_CTRL;
-    }
-  }
-
-  public void keyReleased(KeyEvent e) {
-    if (e.getKeyCode()==KeyEvent.VK_SHIFT
-        ||e.getKeyCode()==KeyEvent.VK_CONTROL) {
-      curSelectModifier=MODIFIER_NONE;
-    }
-  }
-
-  public void keyTyped(KeyEvent e) { }
-
-  public void save (String filename) {
-    int dotpos=filename.lastIndexOf('.');
-    if (dotpos>0) filename=filename.substring(0,dotpos);
-    
-    Enumeration colors=areasHash.keys();
-    ArrayList colornames=new ArrayList(20);
-    while (colors.hasMoreElements()) colornames.add(colors.nextElement());
-    Collections.sort(colornames);
-    ArrayList areas=new ArrayList(20);
-
-    for (Iterator i=colornames.iterator(); i.hasNext();
-         areas.add(areasHash.get(i.next())));
-    
-    int size_y=16, size_u=64, size_v=64;
-    byte[] tmap=new byte[size_y*size_u*size_v];
-
-    float[] hsb=new float[3];
-    int y, u, v, r, g, b, h, s;
-    int iy, iu, iv, i;
-
-    for (iy=0; iy<16; iy++) {
-      for (iu=0; iu<64; iu++) {
-        for (iv=0; iv<64; iv++) {
-          y=iy<<4; u=iu<<2; v=iv<<2;
-          u=u*2-255;
-          v=v*2-255;
-          r=y+u;
-          b=y+v;
-          u=u>>1;
-          v=(v>>2)-(v>>4);
-          g=y-u-v;
-          if (r<0) r=0; if (g<0) g=0; if (b<0) b=0;
-          if (r>255) r=255; if (g>255) g=255; if (b>255) b=255;
-          float[] xy=VisionTrain.colorConverter.getColor(r, g, b);
-          h=(int)(xy[0]*f_width+f_offset);
-          s=(int)(xy[1]*f_height+f_offset);
-          Point point=new Point(h, s);
-          for (i=0; i<areas.size(); i++) {
-            Area area = (Area) areas.get(i);
-            if (area.contains(point)) {
-              tmap[(iy*size_u+iu)*size_v+iv]=(byte)(i+1);
-              break;
-            }
-          }
-        }
-      }
-    }
-
-    try {
-      FileOutputStream file_tm_fos=new FileOutputStream(filename + ".tm");
-      OutputStreamWriter file_tm_osw=new OutputStreamWriter(file_tm_fos);
-      file_tm_osw.write("TMAP\nYUV8\n" +
-          size_y + " " + size_u + " " + size_v + "\n");
-      file_tm_osw.flush();
-      file_tm_fos.write(tmap);
-      file_tm_osw.close();
-    } catch (Exception ex) {
-      System.out.println("Error saving to "+filename +".tm: " + ex);
-    }
-
-    int[][] avgcolors=new int[areas.size()][4]; 
-
-    int skip=(rgb.length/10000)+1;
-    for (i=0; i<rgb.length; i+=skip) {
-      for (int a=0; a<areas.size(); a++) {
-        Area area=(Area)areas.get(a);
-        Point p=new Point((int)(xy[i*2]*f_width+f_offset),
-                          (int)(xy[i*2+1]*f_height+f_offset));
-        if (area.contains(p)) {
-          avgcolors[a][0]+=(rgb[i]>>16)&0xff;
-          avgcolors[a][1]+=(rgb[i]>>8)&0xff;
-          avgcolors[a][2]+=rgb[i]&0xff;
-          avgcolors[a][3]++;
-        }
-      }
-    }
-
-    for (i=0; i<avgcolors.length; i++) {
-      if (avgcolors[i][3]>0) {
-        avgcolors[i][0]=avgcolors[i][0]/avgcolors[i][3];
-        avgcolors[i][1]=avgcolors[i][1]/avgcolors[i][3];
-        avgcolors[i][2]=avgcolors[i][2]/avgcolors[i][3];
-      } else {
-        avgcolors[i][0]=0;
-        avgcolors[i][1]=0;
-        avgcolors[i][2]=0;
-      }
-    }
- 
-    try {
-      FileWriter file_col_fw=new FileWriter(filename + ".col");
-      file_col_fw.write("0 (128 128 128) \"unclassified\" 8 1.00\n");
-      for (i=0; i<areas.size(); i++) {
-        file_col_fw.write((i+1)+ " (" +
-                          avgcolors[i][0] + " " +
-                          avgcolors[i][1] + " " +
-                          avgcolors[i][2] + ") " +
-                          "\"" + colornames.get(i)+ "\" 8 0.75\n");
-      }
-
-      file_col_fw.close();
-    } catch (Exception ex) {
-      System.out.println("Error saving to "+filename + ".col: " + ex);
-    }
-  }
-}
diff -urdN ../Tekkotsu_2.3/tools/test/CVS/Entries ./tools/test/CVS/Entries
--- ../Tekkotsu_2.3/tools/test/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/test/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,5 @@
+D/base64////
+D/kinematics////
+D/mon////
+D/network////
+D/plist////
diff -urdN ../Tekkotsu_2.3/tools/test/CVS/Repository ./tools/test/CVS/Repository
--- ../Tekkotsu_2.3/tools/test/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/test/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/test
diff -urdN ../Tekkotsu_2.3/tools/test/CVS/Root ./tools/test/CVS/Root
--- ../Tekkotsu_2.3/tools/test/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/test/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/test/CVS/Tag ./tools/test/CVS/Tag
--- ../Tekkotsu_2.3/tools/test/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/test/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ttekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/test/base64/CVS/Entries ./tools/test/base64/CVS/Entries
--- ../Tekkotsu_2.3/tools/test/base64/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/test/base64/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,3 @@
+/Makefile/1.1/Wed Jun  1 05:48:09 2005//Ttekkotsu-2_4
+/base64.cc/1.1/Wed Jun  1 05:48:09 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/test/base64/CVS/Repository ./tools/test/base64/CVS/Repository
--- ../Tekkotsu_2.3/tools/test/base64/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/test/base64/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/test/base64
diff -urdN ../Tekkotsu_2.3/tools/test/base64/CVS/Root ./tools/test/base64/CVS/Root
--- ../Tekkotsu_2.3/tools/test/base64/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/test/base64/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/test/base64/CVS/Tag ./tools/test/base64/CVS/Tag
--- ../Tekkotsu_2.3/tools/test/base64/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/test/base64/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/test/base64/Makefile ./tools/test/base64/Makefile
--- ../Tekkotsu_2.3/tools/test/base64/Makefile	Wed Dec 31 19:00:00 1969
+++ ./tools/test/base64/Makefile	Wed Jun  1 01:48:09 2005
@@ -0,0 +1,78 @@
+
+
+#if you want to change the target model, it is recommended
+#to set the TEKKOTSU_TARGET_MODEL environment variable
+
+.PHONY: all tk
+
+# We use this TK_RT instead of TEKKOTSU_ROOT so things will
+# still work if TEKKOTSU_ROOT is a relative path from some
+# unknown project directory (and thus would be invalid from
+# this subdirectory of 'tools')
+TK_RT:=../../..
+
+TEMPLATE_PROJECT:=$(TK_RT)/project
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
+$(if $(shell if [ \! -r $(TEKKOTSU_ENVIRONMENT_CONFIGURATION) ] \; then echo failure \; fi),$(error An error has occured, `$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)' could not be found.  You may need to edit TK_RT in the Makefile))
+
+TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+PROJECT_BUILDDIR:=build
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(FILTERSYSWARN))
+COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(COLORFILT))
+$(shell mkdir -p $(PROJ_BD))
+
+BIN:=$(shell pwd | sed 's@.*/@@')-$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)))
+
+SRCSUFFIX:=.cc
+
+PROJ_SRC:=$(shell find . -name "*$(SRCSUFFIX)")
+
+PROJ_OBJ:=$(patsubst ./%$(SRCSUFFIX),$(PROJ_BD)/%.o,$(PROJ_SRC))
+
+LIBS:= $(TK_BD)/libtekkotsu.a $(TK_BD)/../Motion/roboop/libroboop.a $(TK_BD)/../Shared/newmat/libnewmat.a
+
+DEPENDS:=$(PROJ_OBJ:.o=.d)
+
+CXXFLAGS=-g -Wall -O2 \
+         -I$(TK_RT) \
+         -D$(TEKKOTSU_TARGET_PLATFORM) -D$(TEKKOTSU_TARGET_MODEL) 
+
+
+all: tk $(BIN)
+
+$(BIN): $(PROJ_OBJ) $(LIBS)
+	@echo "Linking $@..."
+	@g++ $(PROJ_OBJ) $(LIBS) -o $@
+
+ifeq ($(findstring clean,$(MAKECMDGOALS)),)
+-include $(DEPENDS)
+endif
+
+tk :
+	export TEKKOTSU_TARGET_PLATFORM=PLATFORM_LOCAL; $(MAKE) -C $(TK_RT) compile
+
+%.a :
+	@echo "ERROR: $@ was not found.  You may need to compile the Tekkotsu framework."
+	@echo "Press return to attempt to build it, ctl-C to cancel."
+	@read;
+	export TEKKOTSU_TARGET_PLATFORM=PLATFORM_LOCAL; $(MAKE) -C $(TK_RT) compile
+
+%.d :
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
+	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
+
+%.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "Compiling $$src..."; \
+	$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0; \
+
+clean:
+	rm -rf $(BIN) $(PROJECT_BUILDDIR) *~
+
diff -urdN ../Tekkotsu_2.3/tools/test/base64/base64.cc ./tools/test/base64/base64.cc
--- ../Tekkotsu_2.3/tools/test/base64/base64.cc	Wed Dec 31 19:00:00 1969
+++ ./tools/test/base64/base64.cc	Wed Jun  1 01:48:09 2005
@@ -0,0 +1,64 @@
+#include "local/minisim.h"
+
+#include "Shared/Base64.h"
+
+#include <iostream>
+#include <string>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/fcntl.h>
+
+using namespace std;
+using namespace minisim;
+
+int main(int argc, char** argv) {
+  initialize();
+
+  if(argc<2 || strcmp(argv[1],"encode") && strcmp(argv[1],"decode")) {
+    cerr << "Usage: " << argv[0] << " (encode|decode) filename" << endl;
+    exit(2);
+  }
+
+  bool isEncode=!strcmp(argv[1],"encode");
+  string file=argv[2];
+  
+  struct stat sb;
+  if(stat(file.c_str(),&sb)) {
+    perror("stat");
+    exit(1);
+  }
+  char * buf = new char[sb.st_size];
+  int fd=open(file.c_str(),O_RDONLY,0);
+  if(fd==-1) {
+    perror("open");
+    exit(1);
+  }
+  unsigned int r=0;
+  while(r<sb.st_size) {
+    unsigned int n=read(fd,buf,sb.st_size-r);
+    if(n<=0) {
+      cerr << "file load error" << endl;
+      close(fd);
+      exit(1);
+    }
+    r+=n;
+  }
+  close(fd);
+
+  if(isEncode) {
+    cout << base64::encode(buf,sb.st_size);
+  } else {
+    string enc(buf);
+    char * dat = base64::decode(enc);
+    if(dat==NULL) {
+      cerr << "decoding error" << endl;
+      exit(1);
+    }
+    unsigned int len=base64::decodeSize(enc);
+    write(STDOUT_FILENO,dat,len);
+  }
+  
+  destruct();
+  return 0;
+}
+
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/CVS/Entries ./tools/test/kinematics/CVS/Entries
--- ../Tekkotsu_2.3/tools/test/kinematics/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,69 @@
+/IP210Body.txt/1.1/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP210Camera.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP210IR.txt/1.1/Wed Jan 12 19:25:00 2005//Ttekkotsu-2_4
+/IP210LBk.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP210LFr.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP210Mouth.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP210RBk.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP210RFr.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP220Body.txt/1.1/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP220Camera.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP220IR.txt/1.1/Wed Jan 12 19:25:00 2005//Ttekkotsu-2_4
+/IP220LBk.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP220LFr.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP220RBk.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP220RFr.txt/1.3/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP7Body.txt/1.1/Fri Dec 10 20:43:22 2004//Ttekkotsu-2_4
+/IP7Camera.txt/1.3/Fri Dec 10 20:43:23 2004//Ttekkotsu-2_4
+/IP7ChestIR.txt/1.1/Wed Jan 12 19:25:00 2005//Ttekkotsu-2_4
+/IP7FarIR.txt/1.1/Wed Jan 12 19:25:00 2005//Ttekkotsu-2_4
+/IP7LBk.txt/1.4/Fri Dec 10 20:43:23 2004//Ttekkotsu-2_4
+/IP7LFr.txt/1.4/Fri Dec 10 20:43:23 2004//Ttekkotsu-2_4
+/IP7Mouth.txt/1.3/Fri Dec 10 20:43:23 2004//Ttekkotsu-2_4
+/IP7NearIR.txt/1.1/Wed Jan 12 19:25:00 2005//Ttekkotsu-2_4
+/IP7PantsBody.txt/1.1/Fri Dec 10 20:43:23 2004//Ttekkotsu-2_4
+/IP7RBk.txt/1.4/Fri Dec 10 20:43:23 2004//Ttekkotsu-2_4
+/IP7RFr.txt/1.4/Fri Dec 10 20:43:23 2004//Ttekkotsu-2_4
+/Makefile/1.11/Wed Jun  1 05:48:09 2005//Ttekkotsu-2_4
+/cam2xx.txt/1.1/Tue Sep 14 22:07:01 2004//Ttekkotsu-2_4
+/cam7.txt/1.1/Tue Sep 14 22:07:01 2004//Ttekkotsu-2_4
+/cam_range210/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/cam_range220/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/cam_range7/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/cam_type2xx.txt/1.1/Tue Sep 14 22:07:01 2004//Ttekkotsu-2_4
+/cam_type7.txt/1.1/Tue Sep 14 22:07:01 2004//Ttekkotsu-2_4
+/closest_point_on_line.m/1.1/Tue Sep 14 22:07:01 2004//Ttekkotsu-2_4
+/dhtransform.m/1.1/Sun Sep 12 06:07:46 2004//Ttekkotsu-2_4
+/dhvisualize.m/1.5/Mon Sep 27 01:32:06 2004//Ttekkotsu-2_4
+/dist_point_to_vector.m/1.1/Tue Sep 14 22:07:01 2004//Ttekkotsu-2_4
+/front_leg_range7/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/hind_leg_range7/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/inv_kin.m/1.16/Thu Oct 14 21:59:29 2004//Ttekkotsu-2_4
+/ipvisualize.m/1.4/Tue Oct  5 19:12:37 2004//Ttekkotsu-2_4
+/kine.m/1.1/Mon Sep 27 01:32:06 2004//Ttekkotsu-2_4
+/kinverify.nb/1.2/Tue Sep 14 22:07:01 2004//Ttekkotsu-2_4
+/leg_range2xx/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/leg_type.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/lf2xx.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/lf7.txt/1.2/Tue Oct 19 07:37:20 2004//Ttekkotsu-2_4
+/lh2xx.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/lh7.txt/1.2/Tue Oct 19 07:37:20 2004//Ttekkotsu-2_4
+/limit_angle.m/1.1/Mon Sep 27 01:32:06 2004//Ttekkotsu-2_4
+/loadDH.m/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/matlab.mat/1.7/Tue Oct 19 07:37:20 2004/-kb/Ttekkotsu-2_4
+/mouth2xx.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/mouth7.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/mouth7b.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/mouth_range210/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/mouth_range7/1.1/Mon Sep 20 21:54:32 2004//Ttekkotsu-2_4
+/mouth_type.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/rf2xx.txt/1.1/Tue Sep 14 22:07:02 2004//Ttekkotsu-2_4
+/rf7.txt/1.2/Tue Oct 19 07:37:21 2004//Ttekkotsu-2_4
+/rh2xx.txt/1.1/Tue Sep 14 22:07:03 2004//Ttekkotsu-2_4
+/rh7.txt/1.2/Tue Oct 19 07:37:21 2004//Ttekkotsu-2_4
+/set_q.m/1.4/Mon Sep 20 22:54:21 2004//Ttekkotsu-2_4
+/test2xx.m/1.1/Fri Sep 24 21:37:37 2004//Ttekkotsu-2_4
+/test7.m/1.4/Thu Oct 14 19:25:23 2004//Ttekkotsu-2_4
+/test_kinematics.cc/1.13/Wed Jun  1 05:48:09 2005//Ttekkotsu-2_4
+/vector_from_point_to_vector.m/1.1/Tue Sep 14 22:07:03 2004//Ttekkotsu-2_4
+D/IPorig////
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/CVS/Repository ./tools/test/kinematics/CVS/Repository
--- ../Tekkotsu_2.3/tools/test/kinematics/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/test/kinematics
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/CVS/Root ./tools/test/kinematics/CVS/Root
--- ../Tekkotsu_2.3/tools/test/kinematics/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/CVS/Tag ./tools/test/kinematics/CVS/Tag
--- ../Tekkotsu_2.3/tools/test/kinematics/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Entries ./tools/test/kinematics/IPorig/CVS/Entries
--- ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/IPorig/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,9 @@
+/210.txt/1.5/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+/210scale.txt/1.3/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+/220.txt/1.5/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+/220scale.txt/1.3/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+/7.txt/1.7/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+/7scale.txt/1.2/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+/ipenlist/1.3/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+/ipsplit/1.2/Fri Dec 10 20:43:34 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Repository ./tools/test/kinematics/IPorig/CVS/Repository
--- ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/IPorig/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/test/kinematics/IPorig
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Root ./tools/test/kinematics/IPorig/CVS/Root
--- ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/IPorig/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Tag ./tools/test/kinematics/IPorig/CVS/Tag
--- ../Tekkotsu_2.3/tools/test/kinematics/IPorig/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/test/kinematics/IPorig/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/Makefile ./tools/test/kinematics/Makefile
--- ../Tekkotsu_2.3/tools/test/kinematics/Makefile	Tue Oct  5 17:06:57 2004
+++ ./tools/test/kinematics/Makefile	Wed Jun  1 01:48:09 2005
@@ -1,175 +1,75 @@
-# Modified from Roboop Makefile for GNU g++
 
-TEKKOTSU_ROOT ?= ../..
-TEKKOTSU_TARGET_MODEL ?= TGT_ERS7
-ROBOOP_ROOT := $(TEKKOTSU_ROOT)/Motion/roboop
-NEWMAT_ROOT := $(TEKKOTSU_ROOT)/Shared/newmat
+#if you want to change the target model, it is recommended
+#to set the TEKKOTSU_TARGET_MODEL environment variable
 
-CXX = g++
-CXXFLAGS = -I $(NEWMAT_ROOT) -I $(ROBOOP_ROOT) -I $(TEKKOTSU_ROOT) -Wall -D_REENTRANT -g \
-	-Wall -W -Wlarger-than-8192 -Wpointer-arith -Wcast-qual \
-	-D$(TEKKOTSU_TARGET_MODEL) \
+.PHONY: all
 
-#  -O2 -frename-registers -fomit-frame-pointer -ffast-math -fno-common \
+# We use this TK_RT instead of TEKKOTSU_ROOT so things will
+# still work if TEKKOTSU_ROOT is a relative path from some
+# unknown project directory (and thus would be invalid from
+# this subdirectory of 'tools')
+TK_RT:=../../..
 
-#-Wno-long-double
-LIBS = -L./ -ltekkotsu -lroboop -lnewmat -lm
-AR = ar
-AR2= ranlib
+TEMPLATE_PROJECT:=$(TK_RT)/project
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
+$(if $(shell if [ \! -r $(TEKKOTSU_ENVIRONMENT_CONFIGURATION) ] \; then echo failure \; fi),$(error An error has occured, `$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)' could not be found.  You may need to edit TK_RT in the Makefile))
 
-all: test_kinematics
+TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+PROJECT_BUILDDIR:=build
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(FILTERSYSWARN))
+COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(COLORFILT))
+$(shell mkdir -p $(PROJ_BD))
 
-test_kinematics: test_kinematics.o libnewmat.a libroboop.a libtekkotsu.a
-	$(CXX) test_kinematics.o $(LIBS) -g -Wall -o $@
+BIN:=test_kinematics-$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)))
 
-Deprobooplib = \
-   roboop/gnugraph.o   roboop/comp_dq.o   roboop/comp_dqp.o   roboop/delta_t.o \
-   roboop/dynamics.o   roboop/homogen.o   roboop/kinemat.o    roboop/robot.o   \
-   roboop/sensitiv.o   roboop/utils.o     roboop/quaternion.o roboop/config.o  \
-   roboop/trajectory.o roboop/clik.o      roboop/controller.o roboop/invkine.o \
-   roboop/control_select.o roboop/dynamics_sim.o
+SRCSUFFIX:=.cc
 
-Depnewmatlib = \
-   newmat/bandmat.o    newmat/cholesky.o   newmat/evalue.o     newmat/fft.o\
-   newmat/hholder.o    newmat/jacobi.o     newmat/myexcept.o   newmat/newmat1.o\
-   newmat/newmat2.o    newmat/newmat3.o    newmat/newmat4.o    newmat/newmat5.o\
-   newmat/newmat6.o    newmat/newmat7.o    newmat/newmat8.o    newmat/newmat9.o\
-   newmat/newmatex.o   newmat/newmatnl.o   newmat/newmatrm.o   \
-   newmat/sort.o       newmat/submat.o     newmat/svd.o        newmat/newfft.o
-   
-Deptekkotsulib = \
-   tekkotsu/Motion/Kinematics.o   tekkotsu/Motion/PostureEngine.o  \
-   tekkotsu/Shared/Config.o       tekkotsu/Wireless/Socket.o       \
-   tekkotsu/Shared/WorldState.o   tekkotsu/Shared/get_time.o       \
-   tekkotsu/Shared/Profiler.o     tekkotsu/Events/EventBase.o      \
-   tekkotsu/Shared/LoadSave.o     tekkotsu/Shared/TimeET.o
+PROJ_SRC:=$(shell find . -name "*$(SRCSUFFIX)")
 
-DEPENDS = $(Deptekkotsulib:.o=.d)
+PROJ_OBJ:=$(patsubst ./%$(SRCSUFFIX),$(PROJ_BD)/%.o,$(PROJ_SRC))
 
-test_kinematics.o: $(Deproboooplib) $(Depnewmatlib) $(Deptekkotsulib)
+LIBS:= $(TK_BD)/libtekkotsu.a $(TK_BD)/../Motion/roboop/libroboop.a $(TK_BD)/../Shared/newmat/libnewmat.a
 
-roboop/%.o : $(ROBOOP_ROOT)/%.cpp $(Depnewmatlib)
-	@if [ ! -e $(dir $@) ] ; then mkdir -p $(dir $@) ; fi
-	$(CXX) -c $(CXXFLAGS) -o $@ $<
+DEPENDS:=$(PROJ_OBJ:.o=.d)
 
-newmat/%.o : $(NEWMAT_ROOT)/%.cpp
-	@if [ ! -e $(dir $@) ] ; then mkdir -p $(dir $@) ; fi
-	$(CXX) -c $(CXXFLAGS) -o $@ $<
+CXXFLAGS=-g -Wall -O2 \
+         -I$(TK_RT) \
+         -D$(TEKKOTSU_TARGET_PLATFORM) -D$(TEKKOTSU_TARGET_MODEL) \
+	 `xml2-config --cflags`
 
-tekkotsu/%.o :
-	@if [ ! -e $(dir $@) ] ; then mkdir -p $(dir $@) ; fi
-	$(CXX) -c $(CXXFLAGS) -o $@ $<
 
-%.o : %.cpp
-	$(CXX) -c $(CXXFLAGS) -o $@ $<
+all: $(BIN)
 
-%.d :
-	@src=$(patsubst %.d,%.cc,$(patsubst tekkotsu/%,$(TEKKOTSU_ROOT)/%,$@)); \
-	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
-	if [ ! -e $(dir $@) ] ; then mkdir -p $(dir $@) ; fi ; \
-	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
+$(BIN): $(PROJ_OBJ) $(LIBS)
+	@echo "Linking $@..."
+	@$(CXX) $(PROJ_OBJ) $(LIBS) `xml2-config --libs` -o $@
 
 ifeq ($(findstring clean,$(MAKECMDGOALS)),)
 -include $(DEPENDS)
 endif
 
-libroboop.a : $(Deprobooplib)
-	rm -f $@
-	$(AR) rc $@ $(Deprobooplib)
-	$(AR2) $@
-
-libnewmat.a: $(Depnewmatlib)
-	rm -f $@
-	$(AR) rc $@ $(Depnewmatlib)
-	$(AR2) $@
-
-libtekkotsu.a: $(Deptekkotsulib)
-	rm -f $@
-	$(AR) rc $@ $(Deptekkotsulib)
-	$(AR2) $@
-
-roboop/controller.o: $(ROBOOP_ROOT)/controller.cpp $(ROBOOP_ROOT)/controller.h
-
-roboop/control_select.o: $(ROBOOP_ROOT)/control_select.cpp $(ROBOOP_ROOT)/control_select.h
-
-roboop/dynamics_sim.o: $(ROBOOP_ROOT)/dynamics_sim.cpp $(ROBOOP_ROOT)/dynamics_sim.h
-
-roboop/trajectory.o: $(ROBOOP_ROOT)/trajectory.cpp $(ROBOOP_ROOT)/trajectory.h
-
-roboop/clik.o :  $(ROBOOP_ROOT)/clik.cpp $(ROBOOP_ROOT)/clik.h $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/robot.o :  $(ROBOOP_ROOT)/robot.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/config.o : $(ROBOOP_ROOT)/config.cpp $(ROBOOP_ROOT)/config.h
-
-roboop/quaternion.o : $(ROBOOP_ROOT)/quaternion.cpp $(ROBOOP_ROOT)/quaternion.h
-
-roboop/gnugraph.o :  $(ROBOOP_ROOT)/gnugraph.cpp $(ROBOOP_ROOT)/gnugraph.h $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/comp_dq.o :  $(ROBOOP_ROOT)/comp_dq.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/comp_dqp.o :  $(ROBOOP_ROOT)/comp_dqp.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/delta_t.o :  $(ROBOOP_ROOT)/delta_t.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/dynamics.o :  $(ROBOOP_ROOT)/dynamics.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/homogen.o :  $(ROBOOP_ROOT)/homogen.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/invkine.o :  $(ROBOOP_ROOT)/invkine.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/kinemat.o :  $(ROBOOP_ROOT)/kinemat.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/sensitiv.o :  $(ROBOOP_ROOT)/sensitiv.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-roboop/utils.o :  $(ROBOOP_ROOT)/utils.cpp $(ROBOOP_ROOT)/utils.h $(ROBOOP_ROOT)/robot.h
-
-newmat/bandmat.o :  $(NEWMAT_ROOT)/bandmat.cpp
-
-newmat/cholesky.o :  $(NEWMAT_ROOT)/cholesky.cpp
-
-newmat/evalue.o :  $(NEWMAT_ROOT)/evalue.cpp
-
-newmat/fft.o :  $(NEWMAT_ROOT)/fft.cpp
-
-newmat/newfft.o :  $(NEWMAT_ROOT)/newfft.cpp
-
-newmat/hholder.o :  $(NEWMAT_ROOT)/hholder.cpp
-
-newmat/jacobi.o :  $(NEWMAT_ROOT)/jacobi.cpp
-
-newmat/myexcept.o :  $(NEWMAT_ROOT)/myexcept.cpp
-
-newmat/newmat1.o :  $(NEWMAT_ROOT)/newmat1.cpp
-
-newmat/newmat2.o :  $(NEWMAT_ROOT)/newmat2.cpp
-
-newmat/newmat3.o :  $(NEWMAT_ROOT)/newmat3.cpp
-
-newmat/newmat4.o :  $(NEWMAT_ROOT)/newmat4.cpp
-
-newmat/newmat5.o :  $(NEWMAT_ROOT)/newmat5.cpp
-
-newmat/newmat6.o :  $(NEWMAT_ROOT)/newmat6.cpp
-
-newmat/newmat7.o :  $(NEWMAT_ROOT)/newmat7.cpp
-
-newmat/newmat8.o :  $(NEWMAT_ROOT)/newmat8.cpp
-
-newmat/newmat9.o :  $(NEWMAT_ROOT)/newmat9.cpp
-
-newmat/newmatex.o :  $(NEWMAT_ROOT)/newmatex.cpp
-
-newmat/newmatnl.o :  $(NEWMAT_ROOT)/newmatnl.cpp
-
-newmat/newmatrm.o :  $(NEWMAT_ROOT)/newmatrm.cpp
-
-newmat/sort.o :  $(NEWMAT_ROOT)/sort.cpp
+%.a :
+	@echo "ERROR: $@ was not found.  You may need to compile the Tekkotsu framework."
+	@echo "Press return to attempt to build it, ctl-C to cancel."
+	@read;
+	$(MAKE) -C $(TK_RT) compile
 
-newmat/submat.o :  $(NEWMAT_ROOT)/submat.cpp
+%.d :
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
+	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
 
-newmat/svd.o :  $(NEWMAT_ROOT)/svd.cpp
+%.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "Compiling $$src..."; \
+	$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0; \
 
 clean:
-	rm -f *.o *.a
-	rm -rf newmat roboop tekkotsu
+	rm -rf $(BIN) $(PROJECT_BUILDDIR) *~
+
diff -urdN ../Tekkotsu_2.3/tools/test/kinematics/test_kinematics.cc ./tools/test/kinematics/test_kinematics.cc
--- ../Tekkotsu_2.3/tools/test/kinematics/test_kinematics.cc	Thu Nov  4 14:45:26 2004
+++ ./tools/test/kinematics/test_kinematics.cc	Wed Jun  1 01:48:09 2005
@@ -1,7 +1,10 @@
+#define TK_ENABLE_CONFIG 
+#define TK_ENABLE_SOUTSERR
+#define TK_ENABLE_KINEMATICS
+#include "local/minisim.h"
+
 #include <iostream>
 #include <stdlib.h>
-#include "Motion/Kinematics.h"
-#include "Shared/Config.h"
 #include "Motion/PostureEngine.h"
 #include "Shared/newmat/newmatio.h"
 
@@ -13,15 +16,22 @@
 
 using namespace std;
 using namespace NEWMAT;
-
-unsigned int simulator_time=0;
+using namespace minisim;
 
 int main(int /*argc*/, char** /*argv*/) {
-	//Read config file
 	config=new Config("../../../project/ms/config/tekkotsu.cfg");
 	config->setValue(Config::sec_motion,"root","../../../project/ms/data/motion");
-	config->setValue(Config::sec_motion,"kinematics","../../config/ers7.kin");
-	kine = new Kinematics();
+#if defined( TGT_ERS7 )
+	config->setValue(Config::sec_motion,"kinematics","../../../project/ms/config/ers7.kin");
+#elif defined( TGT_ERS210 ) || defined( TGT_ERS2xx )
+	config->setValue(Config::sec_motion,"kinematics","../../../project/ms/config/ers210.kin");
+#elif defined( TGT_ERS220 )
+	config->setValue(Config::sec_motion,"kinematics","../../../project/ms/config/ers220.kin");
+#else
+#  error Unknown target model
+#endif
+	initialize();
+
 	
 	PostureEngine pose;
 	for(unsigned int i=0; i<NumOutputs; i++)
@@ -102,6 +112,7 @@
 	cout << pose.getTransformLinks(LFrLegOffset+KneeOffset,BaseFrameOffset) << endl;
 	cout << pose.getTransformLinks(PawFrameOffset+LFrLegOrder,BaseFrameOffset) << endl; */
 	
+	destruct();
 	return 0;
 }
 
diff -urdN ../Tekkotsu_2.3/tools/test/mon/CVS/Entries ./tools/test/mon/CVS/Entries
--- ../Tekkotsu_2.3/tools/test/mon/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/test/mon/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,5 @@
+/ControllerGUITest.java/1.2/Sat May 24 04:56:20 2003//Ttekkotsu-2_4
+/Listener.java/1.3/Tue Nov  2 05:23:41 2004//Ttekkotsu-2_4
+/TCPListener.java/1.3/Tue Nov  2 05:23:41 2004//Ttekkotsu-2_4
+/listen.java/1.1/Tue Nov  2 05:23:41 2004//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/test/mon/CVS/Repository ./tools/test/mon/CVS/Repository
--- ../Tekkotsu_2.3/tools/test/mon/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/test/mon/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/test/mon
diff -urdN ../Tekkotsu_2.3/tools/test/mon/CVS/Root ./tools/test/mon/CVS/Root
--- ../Tekkotsu_2.3/tools/test/mon/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/test/mon/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/test/mon/CVS/Tag ./tools/test/mon/CVS/Tag
--- ../Tekkotsu_2.3/tools/test/mon/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/test/mon/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/test/network/CVS/Entries ./tools/test/network/CVS/Entries
--- ../Tekkotsu_2.3/tools/test/network/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/test/network/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,3 @@
+/Makefile/1.2/Wed Jun  1 05:48:09 2005//Ttekkotsu-2_4
+/network.cc/1.3/Mon Aug  1 23:18:00 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/test/network/CVS/Repository ./tools/test/network/CVS/Repository
--- ../Tekkotsu_2.3/tools/test/network/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/test/network/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/test/network
diff -urdN ../Tekkotsu_2.3/tools/test/network/CVS/Root ./tools/test/network/CVS/Root
--- ../Tekkotsu_2.3/tools/test/network/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/test/network/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/test/network/CVS/Tag ./tools/test/network/CVS/Tag
--- ../Tekkotsu_2.3/tools/test/network/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/test/network/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/test/network/Makefile ./tools/test/network/Makefile
--- ../Tekkotsu_2.3/tools/test/network/Makefile	Wed Dec 31 19:00:00 1969
+++ ./tools/test/network/Makefile	Wed Jun  1 01:48:09 2005
@@ -0,0 +1,79 @@
+
+
+#if you want to change the target model, it is recommended
+#to set the TEKKOTSU_TARGET_MODEL environment variable
+
+.PHONY: all tk
+
+# We use this TK_RT instead of TEKKOTSU_ROOT so things will
+# still work if TEKKOTSU_ROOT is a relative path from some
+# unknown project directory (and thus would be invalid from
+# this subdirectory of 'tools')
+TK_RT:=../../..
+
+TEMPLATE_PROJECT:=$(TK_RT)/project
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
+$(if $(shell if [ \! -r $(TEKKOTSU_ENVIRONMENT_CONFIGURATION) ] \; then echo failure \; fi),$(error An error has occured, `$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)' could not be found.  You may need to edit TK_RT in the Makefile))
+
+TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+PROJECT_BUILDDIR:=build
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(FILTERSYSWARN))
+COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TK_RT)/%,$(COLORFILT))
+$(shell mkdir -p $(PROJ_BD))
+
+BIN:=$(shell pwd | sed 's@.*/@@')-$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)))
+
+SRCSUFFIX:=.cc
+
+PROJ_SRC:=$(shell find . -name "*$(SRCSUFFIX)")
+
+PROJ_OBJ:=$(patsubst ./%$(SRCSUFFIX),$(PROJ_BD)/%.o,$(PROJ_SRC))
+
+LIBS:= $(TK_BD)/libtekkotsu.a $(TK_BD)/../Motion/roboop/libroboop.a $(TK_BD)/../Shared/newmat/libnewmat.a
+
+DEPENDS:=$(PROJ_OBJ:.o=.d)
+
+CXXFLAGS=-g -Wall -O2 \
+         -I$(TK_RT) \
+         -D$(TEKKOTSU_TARGET_PLATFORM) -D$(TEKKOTSU_TARGET_MODEL) \
+         `xml2-config --cflags`
+
+
+all: tk $(BIN)
+
+$(BIN): $(PROJ_OBJ) $(LIBS)
+	@echo "Linking $@..."
+	@g++ $(PROJ_OBJ) $(LIBS) `xml2-config --libs` -lpthread -o $@
+
+ifeq ($(findstring clean,$(MAKECMDGOALS)),)
+-include $(DEPENDS)
+endif
+
+tk :
+	export TEKKOTSU_TARGET_PLATFORM=PLATFORM_LOCAL; $(MAKE) -C $(TK_RT) compile
+
+%.a :
+	@echo "ERROR: $@ was not found.  You may need to compile the Tekkotsu framework."
+	@echo "Press return to attempt to build it, ctl-C to cancel."
+	@read;
+	export TEKKOTSU_TARGET_PLATFORM=PLATFORM_LOCAL; $(MAKE) -C $(TK_RT) compile
+
+%.d :
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
+	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
+
+%.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "Compiling $$src..."; \
+	$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0; \
+
+clean:
+	rm -rf $(BIN) $(PROJECT_BUILDDIR) *~
+
diff -urdN ../Tekkotsu_2.3/tools/test/network/network.cc ./tools/test/network/network.cc
--- ../Tekkotsu_2.3/tools/test/network/network.cc	Wed Dec 31 19:00:00 1969
+++ ./tools/test/network/network.cc	Mon Aug  1 19:18:00 2005
@@ -0,0 +1,34 @@
+#define TK_ENABLE_EROUTER
+#define TK_ENABLE_WIRELESS
+#include "local/minisim.h"
+
+#include "Behaviors/Mon/EchoBehavior.h"
+#include "Events/TextMsgEvent.h"
+
+#include <iostream>
+#include <string>
+
+using namespace std;
+using namespace minisim;
+
+int main(int argc, char** argv) {
+	initialize(); //minisim function for global setup
+	
+
+	EchoBehavior eb;
+	eb.SetAutoDelete(false); //needed when using stack allocation
+	eb.DoStart();
+
+	for(string in; cin; getline(cin,in)) {
+		if(in.size()>0) {
+			erouter->postEvent(new TextMsgEvent(in));
+		}
+	}
+
+	eb.DoStop();
+	
+	
+	destruct(); //minisim function for global teardown
+	return 0;
+}
+
diff -urdN ../Tekkotsu_2.3/tools/test/plist/CVS/Entries ./tools/test/plist/CVS/Entries
--- ../Tekkotsu_2.3/tools/test/plist/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,7 @@
+/Makefile/1.2/Wed Jul 27 05:58:55 2005//Ttekkotsu-2_4
+/ideal-savetest.plist/1.2/Wed Jul 27 05:58:55 2005//Ttekkotsu-2_4
+/ideal-virgin.plist/1.2/Wed Jul 27 05:58:55 2005//Ttekkotsu-2_4
+/ideal-vision.event/1.1/Thu Jul 28 17:10:38 2005//Ttekkotsu-2_4
+/loadtest.plist/1.1/Tue Jul 26 18:05:35 2005//Ttekkotsu-2_4
+/plist.cc/1.2/Wed Jul 27 05:58:55 2005//Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/test/plist/CVS/Repository ./tools/test/plist/CVS/Repository
--- ../Tekkotsu_2.3/tools/test/plist/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/test/plist
diff -urdN ../Tekkotsu_2.3/tools/test/plist/CVS/Root ./tools/test/plist/CVS/Root
--- ../Tekkotsu_2.3/tools/test/plist/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/test/plist/CVS/Tag ./tools/test/plist/CVS/Tag
--- ../Tekkotsu_2.3/tools/test/plist/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
diff -urdN ../Tekkotsu_2.3/tools/test/plist/Makefile ./tools/test/plist/Makefile
--- ../Tekkotsu_2.3/tools/test/plist/Makefile	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/Makefile	Wed Jul 27 01:58:55 2005
@@ -0,0 +1,92 @@
+
+# This Makefile will handle most aspects of compiling and
+# linking a tool against the Tekkotsu framework.  You probably
+# won't need to make any modifications, but here's the major controls
+
+# Executable name, defaults to:
+#   `basename \`pwd\``-$(TEKKOTSU_TARGET_MODEL)
+TEKKOTSU_TARGET_MODEL?=TGT_ERS7
+BIN:=$(shell pwd | sed 's@.*/@@')-$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)))
+
+# Build directory
+PROJECT_BUILDDIR:=build
+
+# Source files, defaults to all files ending matching *$(SRCSUFFIX)
+SRCSUFFIX:=.cc
+PROJ_SRC:=$(shell find . -name "*$(SRCSUFFIX)")
+
+# Other default values are drawn from the template project's
+# Environment.conf file.  This is found using $(TEKKOTSU_ROOT)
+# Remove the '?' if you want to override an environment variable
+# with a value of your own.
+TEKKOTSU_ROOT?=/usr/local/Tekkotsu
+
+.PHONY: all test
+
+TEMPLATE_PROJECT:=$(TEKKOTSU_ROOT)/project
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
+$(if $(shell if [ \! -r $(TEKKOTSU_ENVIRONMENT_CONFIGURATION) ] \; then echo failure \; fi),$(error An error has occured, `$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)' could not be found.  You may need to edit TEKKOTSU_ROOT in the Makefile))
+
+TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(FILTERSYSWARN))
+COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(COLORFILT))
+$(shell mkdir -p $(PROJ_BD))
+
+PROJ_OBJ:=$(patsubst ./%$(SRCSUFFIX),$(PROJ_BD)/%.o,$(PROJ_SRC))
+
+LIBS:= $(TK_BD)/libtekkotsu.a $(TK_BD)/../Motion/roboop/libroboop.a $(TK_BD)/../Shared/newmat/libnewmat.a
+
+DEPENDS:=$(PROJ_OBJ:.o=.d)
+
+CXXFLAGS:=-g -Wall -O2 \
+         -I$(TEKKOTSU_ROOT) \
+         -I../../Shared/jpeg-6b $(shell xml2-config --cflags) \
+         -D$(TEKKOTSU_TARGET_PLATFORM) -D$(TEKKOTSU_TARGET_MODEL) 
+
+
+all: $(BIN)
+
+$(BIN): $(PROJ_OBJ) $(LIBS)
+	@echo "Linking $@..."
+	@g++ $(PROJ_OBJ) $(LIBS) $(shell xml2-config --libs) -o $@
+
+ifeq ($(findstring clean,$(MAKECMDGOALS)),)
+-include $(DEPENDS)
+endif
+
+%.a :
+	@echo "ERROR: $@ was not found.  You may need to compile the Tekkotsu framework."
+	@echo "Press return to attempt to build it, ctl-C to cancel."
+	@read;
+	$(MAKE) -C $(TEKKOTSU_ROOT) compile
+
+%.d :
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
+	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
+
+%.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "Compiling $$src..."; \
+	$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0; \
+
+clean:
+	rm -rf $(BIN) $(PROJECT_BUILDDIR) *~
+
+test: $(BIN)
+	@./plist-ERS7
+	@for x in * ; do \
+		if [ -r "ideal-$$x" ] ; then \
+			if diff -u "ideal-$$x" "$$x" ; then \
+				echo "Test '$$x' passed"; \
+			else \
+				echo "Test output '$$x' does not match ideal"; \
+			fi; \
+		fi; \
+	done
\ No newline at end of file
diff -urdN ../Tekkotsu_2.3/tools/test/plist/ideal-savetest.plist ./tools/test/plist/ideal-savetest.plist
--- ../Tekkotsu_2.3/tools/test/plist/ideal-savetest.plist	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/ideal-savetest.plist	Wed Jul 27 01:58:55 2005
@@ -0,0 +1,22 @@
+<?xml version="1.0"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+  <dict>
+	<!--numeric contains two numeric values,
+	with a comment split
+	over several lines-->
+    <key>numeric</key>
+    <dict>
+      <key>fooF</key>
+      <real>1.5</real>
+      
+<!--fooI: This is an integer value, the other is a float-->
+    <key>fooI</key>
+      <integer>16</integer>
+    </dict>
+
+<!--This is a common string-->
+    <key>test str</key>
+    <string>Hello World, again!</string>
+  </dict>
+</plist>
diff -urdN ../Tekkotsu_2.3/tools/test/plist/ideal-virgin.plist ./tools/test/plist/ideal-virgin.plist
--- ../Tekkotsu_2.3/tools/test/plist/ideal-virgin.plist	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/ideal-virgin.plist	Wed Jul 27 01:58:55 2005
@@ -0,0 +1,16 @@
+<?xml version="1.0"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<!--numeric contains some numeric values
+	One is a float
+	The other is an int-->
+<key>numeric</key> <dict>
+    <key>fooF</key> <real>3.1415927410125732421875</real>
+
+<!--fooI: This is an integer value, the other is a float-->
+    <key>fooI</key> <integer>42</integer>
+</dict>
+
+<!--test str: Seen this one before?-->
+<key>test str</key> <string>Hello world!</string>
+</dict></plist>
diff -urdN ../Tekkotsu_2.3/tools/test/plist/ideal-vision.event ./tools/test/plist/ideal-vision.event
--- ../Tekkotsu_2.3/tools/test/plist/ideal-vision.event	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/ideal-vision.event	Thu Jul 28 13:10:38 2005
@@ -0,0 +1,11 @@
+<?xml version="1.0"?>
+<event egid="visObjEGID" sid="0" etid="A" time="1" duration="0" magnitude="1">
+  <param name="x1" value="0"/>
+  <param name="y1" value="0"/>
+  <param name="x2" value="0"/>
+  <param name="y2" value="0"/>
+  <param name="clipLeft" value="0"/>
+  <param name="clipRight" value="0"/>
+  <param name="clipTop" value="0"/>
+  <param name="clipBottom" value="0"/>
+</event>
diff -urdN ../Tekkotsu_2.3/tools/test/plist/loadtest.plist ./tools/test/plist/loadtest.plist
--- ../Tekkotsu_2.3/tools/test/plist/loadtest.plist	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/loadtest.plist	Tue Jul 26 14:05:35 2005
@@ -0,0 +1,20 @@
+<?xml version="1.0"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+  <dict>
+	<!--numeric contains two numeric values,
+	with a comment split
+	over several lines-->
+    <key>numeric</key>
+    <dict>
+      <key>fooF</key>
+      <real>1.5</real>
+      <key>fooI</key>
+      <integer>16</integer>
+    </dict>
+
+<!--This is a common string-->
+    <key>test str</key>
+    <string>Once upon a time</string>
+  </dict>
+</plist>
diff -urdN ../Tekkotsu_2.3/tools/test/plist/plist.cc ./tools/test/plist/plist.cc
--- ../Tekkotsu_2.3/tools/test/plist/plist.cc	Wed Dec 31 19:00:00 1969
+++ ./tools/test/plist/plist.cc	Wed Jul 27 01:58:55 2005
@@ -0,0 +1,37 @@
+#include "Shared/plist.h"
+#include "Events/VisionObjectEvent.h"
+#include <cmath>
+
+using namespace plist;
+using namespace std;
+
+int main(int argc, const char** argv) {
+  Primitive<int> fooI=42;
+  Primitive<float> fooF=M_PI;
+  Primitive<std::string> str("Hello world!");
+	
+  Dictionary outer;
+  Dictionary inner;
+  inner.addEntry("fooI",fooI,"This is an integer value, the other is a float");
+  inner.addEntry("fooF",fooF);
+  outer.addEntry("numeric",inner,"numeric contains some numeric values\n\tOne is a float\n\tThe other is an int");
+  outer.addEntry("test str",str,"Seen this one before?");
+	
+  if(!outer.SaveFile("virgin.plist")) {
+    cerr << "Save virgin had error" << endl;
+    return 1;
+  }
+  if(!outer.LoadFile("loadtest.plist")) {
+    cerr << "Load test had error" << endl;
+    return 1;
+  }
+  str="Hello World, again!";
+  if(!outer.SaveFile("savetest.plist")) {
+    cerr << "Save test had error" << endl;
+    return 1;
+  }
+
+  VisionObjectEvent e(0,EventBase::activateETID);
+  e.SaveFile("vision.event");
+  return 0;
+}
diff -urdN ../Tekkotsu_2.3/tools/tool_makefile ./tools/tool_makefile
--- ../Tekkotsu_2.3/tools/tool_makefile	Wed Dec 31 19:00:00 1969
+++ ./tools/tool_makefile	Tue Aug  9 21:58:36 2005
@@ -0,0 +1,91 @@
+
+# This Makefile will handle most aspects of compiling and
+# linking a tool against the Tekkotsu framework.  You probably
+# won't need to make any modifications, but here's the major controls
+
+# Executable name, defaults to:
+#   `basename \`pwd\``-$(TEKKOTSU_TARGET_MODEL)
+TEKKOTSU_TARGET_MODEL?=TGT_ERS7
+BIN:=$(shell pwd | sed 's@.*/@@')-$(shell echo $(patsubst TGT_%,%,$(TEKKOTSU_TARGET_MODEL)))
+
+# Build directory
+PROJECT_BUILDDIR:=build
+
+# Source files, defaults to all files ending matching *$(SRCSUFFIX)
+SRCSUFFIX:=.cc
+PROJ_SRC:=$(shell find . -name "*$(SRCSUFFIX)")
+
+# Other default values are drawn from the template project's
+# Environment.conf file.  This is found using $(TEKKOTSU_ROOT)
+# Remove the '?' if you want to override an environment variable
+# with a value of your own.
+TEKKOTSU_ROOT?=/usr/local/Tekkotsu
+
+.PHONY: all test
+
+TEMPLATE_PROJECT:=$(TEKKOTSU_ROOT)/project
+TEKKOTSU_ENVIRONMENT_CONFIGURATION?=$(TEMPLATE_PROJECT)/Environment.conf
+$(if $(shell if [ \! -r $(TEKKOTSU_ENVIRONMENT_CONFIGURATION) ] \; then echo failure \; fi),$(error An error has occured, `$(TEKKOTSU_ENVIRONMENT_CONFIGURATION)' could not be found.  You may need to edit TEKKOTSU_ROOT in the Makefile))
+
+TEKKOTSU_TARGET_PLATFORM:=PLATFORM_LOCAL
+include $(TEKKOTSU_ENVIRONMENT_CONFIGURATION)
+FILTERSYSWARN:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(FILTERSYSWARN))
+COLORFILT:=$(patsubst $(TEKKOTSU_ROOT)/%,$(TEKKOTSU_ROOT)/%,$(COLORFILT))
+$(shell mkdir -p $(PROJ_BD))
+
+PROJ_OBJ:=$(patsubst ./%$(SRCSUFFIX),$(PROJ_BD)/%.o,$(PROJ_SRC))
+
+LIBS:= $(TK_BD)/libtekkotsu.a $(TK_BD)/../Motion/roboop/libroboop.a $(TK_BD)/../Shared/newmat/libnewmat.a
+
+DEPENDS:=$(PROJ_OBJ:.o=.d)
+
+CXXFLAGS:=-g -Wall -O2 \
+         -I$(TEKKOTSU_ROOT) \
+         -I../../Shared/jpeg-6b $(shell xml2-config --cflags) \
+         -D$(TEKKOTSU_TARGET_PLATFORM) -D$(TEKKOTSU_TARGET_MODEL) 
+
+
+all: $(BIN)
+
+$(BIN): $(PROJ_OBJ) $(LIBS)
+	@echo "Linking $@..."
+	@$(CXX) $(PROJ_OBJ) $(LIBS) $(shell xml2-config --libs) -lpthread -o $@
+
+ifeq ($(findstring clean,$(MAKECMDGOALS)),)
+-include $(DEPENDS)
+endif
+
+%.a :
+	@echo "ERROR: $@ was not found.  You may need to compile the Tekkotsu framework."
+	@echo "Press return to attempt to build it, ctl-C to cancel."
+	@read;
+	$(MAKE) -C $(TEKKOTSU_ROOT) compile
+
+%.d :
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.d,%.cc,$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "$@..." | sed 's@.*$(TGT_BD)/@Generating @'; \
+	$(CXX) $(CXXFLAGS) -MP -MG -MT "$@" -MT "$(@:.d=.o)" -MM "$$src" > $@
+
+%.o:
+	@mkdir -p $(dir $@)
+	@src=$(patsubst %.o,%$(SRCSUFFIX),$(patsubst $(PROJ_BD)/%,%,$@)); \
+	echo "Compiling $$src..."; \
+	$(CXX) $(CXXFLAGS) -o $@ -c $$src > $*.log 2>&1; \
+	retval=$$?; \
+	cat $*.log | $(FILTERSYSWARN) | $(COLORFILT) | $(TEKKOTSU_LOGVIEW); \
+	test $$retval -eq 0; \
+
+clean:
+	rm -rf $(BIN) $(PROJECT_BUILDDIR) *~
+
+test: $(BIN)
+	@for x in * ; do \
+		if [ -r "ideal-$$x" ] ; then \
+			if diff -u "ideal-$$x" "$$x" ; then \
+				echo "Test '$$x' passed"; \
+			else \
+				echo "Test output '$$x' does not match ideal"; \
+			fi; \
+		fi; \
+	done
\ No newline at end of file
diff -urdN ../Tekkotsu_2.3/tools/walk_calibration/CVS/Entries ./tools/walk_calibration/CVS/Entries
--- ../Tekkotsu_2.3/tools/walk_calibration/CVS/Entries	Wed Dec 31 19:00:00 1969
+++ ./tools/walk_calibration/CVS/Entries	Wed Aug 10 11:03:30 2005
@@ -0,0 +1,11 @@
+/WalkCalibration.m/1.3/Sat Feb 28 01:58:59 2004//Ttekkotsu-2_4
+/data.tgz/1.1/Fri Jan 16 05:15:18 2004/-kb/Ttekkotsu-2_4
+/final3br.txt/1.1/Fri Jan 16 05:15:18 2004//Ttekkotsu-2_4
+/final3bs.txt/1.1/Fri Jan 16 05:15:18 2004//Ttekkotsu-2_4
+/final3fr.txt/1.1/Fri Jan 16 05:15:18 2004//Ttekkotsu-2_4
+/final3fs.txt/1.1/Fri Jan 16 05:15:18 2004//Ttekkotsu-2_4
+/final3outliers.txt/1.2/Thu Feb 26 01:03:19 2004//Ttekkotsu-2_4
+/final3rr.txt/1.2/Thu Feb 26 01:03:19 2004//Ttekkotsu-2_4
+/final3sr.txt/1.2/Thu Feb 26 01:03:19 2004//Ttekkotsu-2_4
+/logs.tgz/1.1/Fri Jan 16 05:15:19 2004/-kb/Ttekkotsu-2_4
+D
diff -urdN ../Tekkotsu_2.3/tools/walk_calibration/CVS/Repository ./tools/walk_calibration/CVS/Repository
--- ../Tekkotsu_2.3/tools/walk_calibration/CVS/Repository	Wed Dec 31 19:00:00 1969
+++ ./tools/walk_calibration/CVS/Repository	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Tekkotsu/tools/walk_calibration
diff -urdN ../Tekkotsu_2.3/tools/walk_calibration/CVS/Root ./tools/walk_calibration/CVS/Root
--- ../Tekkotsu_2.3/tools/walk_calibration/CVS/Root	Wed Dec 31 19:00:00 1969
+++ ./tools/walk_calibration/CVS/Root	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+:pserver:anonymous@cvs.tekkotsu.org:/cvs
diff -urdN ../Tekkotsu_2.3/tools/walk_calibration/CVS/Tag ./tools/walk_calibration/CVS/Tag
--- ../Tekkotsu_2.3/tools/walk_calibration/CVS/Tag	Wed Dec 31 19:00:00 1969
+++ ./tools/walk_calibration/CVS/Tag	Wed Aug 10 11:03:30 2005
@@ -0,0 +1 @@
+Ntekkotsu-2_4
