/*
* Copyright (c) 2004-2005, The Hong Kong University of Science and Technology (HKUST)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   * Redistributions of source code must retain the above copyright notice,
*     this list of conditions,the authors and the following disclaimer.
*   * Redistributions in binary form must reproduce the above copyright notice,
*     this list of conditions,the authors and the following disclaimer in
*     the documentation and/or other materials provided with the distribution.
*   * Neither the name of the university nor the names of its
*     contributors may be used to endorse or promote products derived from
*     this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
 * SDGEN: a data generator for Bisque
 * @Author: Bingsheng He (saven@cs.ust.hk)
 * @Date:28/3/3005
 * @Version: 1.0
 * @Function: the main entry of the DGEN
 */
 import java.io.*;
 import java.util.*;
 import java.sql.*;

import org.xml.sax.Attributes;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.ParserAdapter;
import org.xml.sax.helpers.ParserFactory;


 public class SDGEN{
 	String inputSchema;
 	Vector types;
 	Vector schema;
 	Vector columnToInterp;
 	String outputSchema;
 	int inputSamplePeriod;
 	int outputSamplePeriod;
 	long outputStart=0;
 	long outputEnd=0;
 	InputParser IP;
 	OutputParser OP;
 	String inputXML;
 	String outputXML;
 	String tableName;
 	String dataSets;
 	String inputCondition="";
 	boolean forVMNET=true;
 	String []inputTokens=new String[100];
 	String []outputTokens=new String[100];



 	int totalSize=0;// the total number of readings in each output file.

 	void dumpInputFiles()
 	{
 		try{
 		SDAnalyzer log=new SDAnalyzer();
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		 // set this to a MS Access DB you have on your machine
		String filename = "Bisque.mdb";
		String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
		database+= filename.trim() + ";DriverID=22}"; // add on to the end
		 // now we can get the connection from the DriverManager
		log.con = DriverManager.getConnection(database ,"","");

 		for(int id=1;id<=IP.topo.nodes.size();id++)
 		{
	 		String query="select ";
	 		/*for(int i=0;i<(inputSchema.size()-1);i++)
	 		query=query+inputSchema.elementAt(i)+",";
	 		query=query+inputSchema.elementAt(inputSchema.size()-1);*/
	 		int sid=IP.topo.getIndexFromID(id);
	 		query=query+inputSchema;
	 		query=query+" from "+tableName;
	 		query=query+" where nodeid="+sid+" order by ts asc";
	 		log.doQueryToFile(query,"Input"+sid+".dat");
	 	}
	 	log.con.close();
	 	}
        catch (Exception e) {
        System.out.println("Error in DGEN.dumpInputFiles " + e);
        }



 	}

 	void getParseColumn()
 	{
 		inputTokens=inputSchema.split(",");
 		outputTokens=outputSchema.split(",");
 		System.out.println("Here is the output column");
 		for(int j=0;j<outputTokens.length;j++)
 		{
			System.out.println(j+"-->"+outputTokens[j]);
		}
 		for(int j=0;j<outputTokens.length;j++)
 		{
 			//not a timestamp and not a id
 			System.out.println("mapping "+outputTokens[j]);
 			if(outputTokens[j].indexOf("ts")==-1 && outputTokens[j].indexOf("id")==-1)
	 		for(int i=0;i<inputTokens.length;i++)
	 		{

	 			if(inputTokens[i].equals(outputTokens[j]))
	 			{
	 				System.out.println(i+" is mapped to output "+j);
	 				columnToInterp.add(new Integer(i));
	 			}

	 		}
 		}

 	}

 	/*
 	 * dumpInputInfo from InputParser
 	 * dataset txt, inputSamplePeriod, schema, etc..
 	 */
 	void dumpInputInfo()
 	{
 		for(int i=0;i<IP.schema.size();i++)
 		{
	 		schema.add(IP.schema.elementAt(i));
	 		types.add(IP.types.elementAt(i));
	 	}
 		//for(int i=0;i<schema.size();i++)
 		//	System.out.println(schema.elementAt(i)+","+types.elementAt(i));
 		String fN="";

 		for(int i=0;i<IP.fileName.length();i++)
 		if(Misc.isNameCh(IP.fileName.charAt(i)))
 		{
 			fN=fN+IP.fileName.charAt(i);
 		}
 		else
 		break;
 		dataSets=fN;
 		System.out.println(dataSets+"$");
 		//parse the query to get the schema, tablename and sample period;
 		int selectPos=IP.query.indexOf("SELECT");
 		int fromPos=IP.query.indexOf("FROM");
 		int wherePos=IP.query.indexOf("WHERE");
 		int spPos=IP.query.indexOf("SAMPLE PERIOD");
 		inputSchema=IP.query.substring(selectPos+(new String("SELECT")).length()+1,fromPos-2);
 		System.out.println(inputSchema+"$");
 		if(wherePos!=-1)
 		{
 			tableName=IP.query.substring(fromPos+(new String("FROM")).length()+1,wherePos-2);
 			inputCondition=IP.query.substring(wherePos+(new String("WHERE")).length()+1,spPos-2);
 		}
 		else
 		tableName=IP.query.substring(fromPos+(new String("FROM")).length()+1,spPos-2);
 		System.out.println(tableName+"$");


 		System.out.println(inputCondition+"&");
 		String sp="";
 		spPos=spPos+(new String("SAMPLE PERIOD")).length()+1;
 		for(int i=0;;i++)
 		if(IP.query.charAt(i+spPos)<='9' && IP.query.charAt(i+spPos)>='0')
 		{
 			sp=sp+IP.query.charAt(i+spPos);
 		}
 		else
 		break;
 		inputSamplePeriod=Integer.parseInt(sp);
 		
 		
 		System.out.println(inputSamplePeriod+"$");


 	}


 	/*
 	 * dumpInputInfo from InputParser
 	 * dataset txt, inputSamplePeriod, schema, etc..
 	 */
 	void dumpOutputInfo()
 	{
 		//parse the query to get the schema, tablename and sample period;
 		int selectPos=OP.query.indexOf("SELECT");
 		int fromPos=OP.query.indexOf("FROM");
 		int spPos=OP.query.indexOf("SAMPLE PERIOD");

 		outputSchema=OP.query.substring(selectPos+(new String("SELECT")).length()+1,fromPos-2);
 		System.out.println(outputSchema+"$");
 		String sp="";
 		spPos=spPos+(new String("SAMPLE PERIOD")).length()+1;
 		for(int i=0;;i++)
 		if(OP.query.charAt(i+spPos)<='9' && OP.query.charAt(i+spPos)>='0')
 		{
 			sp=sp+OP.query.charAt(i+spPos);
 		}
 		else
 		break;
 		outputSamplePeriod=Integer.parseInt(sp);
 		System.out.println(outputSamplePeriod+"$");
 		int ltPos=OP.query.indexOf("LIFETIME");
 		int ltEndPos=OP.query.indexOf('\n',ltPos);
 		if(ltPos!=-1)
 		{
	 		int lifeTime=Integer.parseInt(OP.query.substring(ltPos+(new String("LIFETIME")).length()+1,ltEndPos));
	 		totalSize=lifeTime/outputSamplePeriod;
	 		System.out.println("*********LIFETIME clause is enabled.");
	 		forVMNET=false;
	 	}
 	}

 	public void print()
 	{
 		System.out.println("we are here");
 		//IP.topo.printTable(2);
 		//IP.topo.printTable(8);
 		System.out.println("["+outputStart+","+outputEnd+"]");
 	}

 	public void GetBound()
 	{
 		try{
 		SDAnalyzer log=new SDAnalyzer();
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		 // set this to a MS Access DB you have on your machine
		String filename = "Bisque.mdb";
		String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
		database+= filename.trim() + ";DriverID=22}"; // add on to the end
		 // now we can get the connection from the DriverManager
		log.con = DriverManager.getConnection(database ,"","");

		String query="SELECT ";
 		query=query+"ts";
 		query=query+" FROM "+tableName;
 		query=query+" ORDER BY ts ASC";
 		System.out.println(query);
 		Statement s = log.con.createStatement();
		s.execute(query);
		ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query

		int numRec=0;
		if (rs != null) // if rs == null, then there is no ResultSet to view
		{
			rs.next();
			outputStart=Misc.getSeconds(rs.getString(1));
			while (rs.next())
			outputEnd=Misc.getSeconds(rs.getString(1));
		}
		System.out.println("GetBound, start="+outputStart+" , end="+outputEnd);
		s.close();
		log.con.close();
		if(forVMNET)
		{

			totalSize=1000;
			System.out.println("this is for VMNET"+totalSize);
		}
		else
		{
			//totalSize=(int)((this.outputEnd-this.outputStart)/outputSamplePeriod);
		}
		}
		catch(Exception e)
		{
			System.out.println("SDGEN: GetBound"+e);
		}

 	}
 	public void genSingleInterpedTable(int sensorid)
 	{
 		try{
 		DTable outputInterpedTable=new DTable();
 		SDAnalyzer log=new SDAnalyzer();
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		 // set this to a MS Access DB you have on your machine
		String filename = "Bisque.mdb";
		String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
		database+= filename.trim() + ";DriverID=22}"; // add on to the end
		 // now we can get the connection from the DriverManager
		log.con = DriverManager.getConnection(database ,"","");

		Node nn=(Node)(OP.topo.nodes.elementAt(OP.topo.getIndexFromID(sensorid)));
		System.out.println("get single interped table: "+nn.x+","+nn.y);
		Node inputnn=(Node)(IP.topo.nodes.elementAt(IP.topo.getIndexFromNode(nn)));
		String query="SELECT ";
 		query=query+inputSchema;
 		query=query+" FROM "+tableName;
 		if(inputCondition.length()>0)
 		query=query+" WHERE nodeid="+inputnn.id+" and "+inputCondition+" ORDER BY ts ASC";
 		else
 		query=query+" WHERE nodeid="+inputnn.id+" ORDER BY ts ASC";
 		System.out.println(query);
 		Statement s = log.con.createStatement();
		s.execute(query);
		ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query
		ResultSetMetaData mD=rs.getMetaData();
		int cN=mD.getColumnCount();

		int numRec=0;
		DTable curT=new DTable();

		//long cur=Misc.getSeconds(rs.getString(0));
		System.out.println("we are there");
		if (rs != null) // if rs == null, then there is no ResultSet to view
		while ( rs.next() ) // this will step through our data row-by-row
		{

			DTuple tuple=new DTuple();
			for(int i=1;i<=cN;i++)
				tuple.add(rs.getString(i));
			curT.add(tuple);
		}
		s.close();
		System.out.println("qqqqqqqqqqqqqqq------------"+IP.topo.tables.size());
		log.con.close();
		///
		///start to interpolate the values.
		if(curT.tuples.size()==0)
		{
			System.out.println("the table is empty: "+sensorid);
			return ;
		}
		else
		{
			float []x=new float[curT.tuples.size()];
			float []y=new float[curT.tuples.size()];
			System.out.println("tttttttttttt"+sensorid);

			for(int i=0;i<curT.tuples.size();i++)
			{
				//x[i]=(float)(Misc.getSeconds((String)(curT.tupleAt(i).elementAt(0))));
				x[i]=(float)(Misc.getSeconds((String)(curT.tupleAt(i).elementAt(0)))-outputStart);
				if(i>=1)
				if(x[i]==x[i-1])
				x[i]=x[i]+1;
			}
			for(int cc=0;cc< columnToInterp.size();cc++)
			{
				int columnIndex=((Integer)(columnToInterp.elementAt(cc))).intValue();
				for(int i=0;i<curT.tuples.size();i++)
				y[i]=Float.parseFloat(curT.tupleAt(i).elementAt(columnIndex).toString());
				MyInterp mi=new MyInterp(x,y);
				if(! forVMNET)
				//mi.dumpValues(0,outputEnd-outputStart,outputSamplePeriod);
				mi.dumpValues(0,totalSize*outputSamplePeriod,outputSamplePeriod);
				else
				{
					System.out.println("this is for VMNET, only 1000 records");
					mi.dumpValues(0,totalSize*outputSamplePeriod,outputSamplePeriod);

				}
				if(cc==0)
				{
					for(int i=0;i<totalSize;i++)
					{
						double cur=0.0;
						if(mi.y[i]>=0)
						cur=mi.y[i];
						DTuple tmpTuple=new DTuple();
						Double d=new Double(cur);
						tmpTuple.add(d);
						outputInterpedTable.add(tmpTuple);
					}
				}
				else
				{
					for(int i=0;i<totalSize;i++)
					{
						double cur=0.0;
						if(mi.y[i]>=0)
						cur=mi.y[i];
						outputInterpedTable.addValue(i,columnIndex-2,new Double(cur));
					}

				}
			}

			System.out.println("come to print table");
			outputInterpedTable.print();


			//write the values to the file.
			System.out.println("we are dumping to file 1: "+ sensorid+", "+"#"+outputInterpedTable.tuples.size());
		 	PrintWriter out= new PrintWriter(new BufferedWriter(new FileWriter("Sensor"+sensorid+".dat")));
		 	DTuple dt;
		 	int vvalue=0;
		 	for(int j=0;j<outputInterpedTable.tuples.size();j++)
		 	{
		 		int m=0;
		 		dt=outputInterpedTable.tupleAt(j);
		 		//edit by saven for whj's vmnet.
		 		for(m=0;m<(dt.values.size());m++)
		 		{

		 			//out.print(dt.elementAt(m).toString()+",");
		 			if(outputTokens[m+2].equals("light"))
		 			{
						if(j==0)
						System.out.println("light?????!!!!2");
		 				vvalue=MTS300.mts300_getraw_light((int)Double.parseDouble(dt.elementAt(m).toString()));
					}
		 			else
		 			if(outputTokens[m+2].equals("temperature"))
		 				vvalue=MTS300.mts300_getraw_temp((int)Double.parseDouble(dt.elementAt(m).toString()));
		 			else
		 			{
						if(j==0)
						System.out.println("othersothers!2");
		 				vvalue=(int)Double.parseDouble(dt.elementAt(m).toString());
					}
		 			if(m==dt.values.size()-1)
		 			out.println(vvalue);
		 			else
		 			out.print(vvalue+",");

				}

		 	}
		 	out.close();

	}

	 	}
        catch (Exception e) {
        System.out.println("Error in DGEN.dumpIntoIPTables " + e);
        }


 	}

 	void genMultipleInterpedTable(int sensorid)
 	{

 		DTable []inputInterpedTables=new DTable[4];
 		for(int i=0;i<4;i++)
 			inputInterpedTables[i]=new DTable();
 		DTable outputInterpedTable=new DTable();
 		Vector neighbor=new Vector();
 		Node n=(Node)(OP.topo.nodes.elementAt(OP.topo.getIndexFromID(sensorid)));
		neighbor=IP.topo.minimumFour(n);
		System.out.println("here is the neightbor for "+n.id);
		for(int j=0;j<4;j++)
			System.out.println(Integer.parseInt(neighbor.elementAt(j).toString())+1);
		double []dist=new double[4];
		int []nnid=new int[4];

		for(int j=0;j<4;j++)
		{
			nnid[j]=Integer.parseInt(neighbor.elementAt(j).toString());
			Node tmpN=(Node)(IP.topo.nodes.elementAt(nnid[j]));
			dist[j]=(tmpN.x-n.x)*(tmpN.x-n.x)+(tmpN.y-n.y)*(tmpN.y-n.y);
			dist[j]=Math.pow(dist[j],0.5);
		}
		double sumWeight=0;
		for(int j=0;j<4;j++)
			sumWeight=sumWeight+1.0/dist[j];
		double []weight=new double[4];
		for(int j=0;j<4;j++)
			weight[j]=(1.0/dist[j])/sumWeight;
		System.out.println("the weight is: ");
		for(int j=0;j<4;j++)
		System.out.print(weight[j]);
		System.out.println("");


		//compute the reading from nnid[i]-->inputInterpedTables[i]
		DTable []tmpTable=new DTable[4];
		for(int i=0;i<4;i++)
		tmpTable[i]=new DTable();
		try{
	 		SDAnalyzer log=new SDAnalyzer();
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			 // set this to a MS Access DB you have on your machine
			String filename = "Bisque.mdb";
			String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
			database+= filename.trim() + ";DriverID=22}"; // add on to the end
			 // now we can get the connection from the DriverManager
			log.con = DriverManager.getConnection(database ,"","");
			for(int ttt=0;ttt<4;ttt++)
			{
				String query="SELECT ";
		 		query=query+inputSchema;
		 		query=query+" FROM "+tableName;
		 		if(inputCondition.length()>0)
		 		query=query+" WHERE nodeid="+((Node)(IP.topo.nodes.elementAt(nnid[ttt]))).id+" and "+inputCondition+" ORDER BY ts ASC";
		 		else
		 		query=query+" WHERE nodeid="+((Node)(IP.topo.nodes.elementAt(nnid[ttt]))).id+" ORDER BY ts ASC";
		 		System.out.println(query);
		 		Statement s = log.con.createStatement();
				s.execute(query);
				ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query
				ResultSetMetaData mD=rs.getMetaData();
				int cN=mD.getColumnCount();

				int numRec=0;

				System.out.println("we are there");
				if (rs != null) // if rs == null, then there is no ResultSet to view
				while ( rs.next() ) // this will step through our data row-by-row
				{
					//System.out.println("we are there1 ;"+cN);
					DTuple tuple=new DTuple();
					for(int i=1;i<=cN;i++)
						tuple.add(rs.getString(i));
					tmpTable[ttt].add(tuple);

				}
				s.close();
				System.out.println("qqqqqqqqqqqqqqq------------#"+tmpTable[ttt].tuples.size());
			}

			log.con.close();

			//intepolate the tables...
			/*for(int ttt=0;ttt<4;ttt++)
			if(tmpTable[ttt].tuples.size()==0)
			{
				System.out.println("the table is empty: "+nnid[ttt]);
				return ;
			}
			else
			{
				float []x=new float[tmpTable[ttt].tuples.size()];
				float []y=new float[tmpTable[ttt].tuples.size()];
				System.out.println("tttttttttttt"+sensorid);

				//currently:)
				int columnIndex=2;
				for(int i=0;i<tmpTable[ttt].tuples.size();i++)
				{
					//x[i]=(float)(Misc.getSeconds((String)(curT.tupleAt(i).elementAt(0))));
					x[i]=(float)(Misc.getSeconds((String)(tmpTable[ttt].tupleAt(i).elementAt(0)))-outputStart);
					if(i>=1)
					if(x[i]==x[i-1])
					x[i]=x[i]+1;
					y[i]=Float.parseFloat(tmpTable[ttt].tupleAt(i).elementAt(columnIndex).toString());
				//	System.out.println(x[i]+","+y[i]);
				}
				System.out.println("eeeeeeeeeeeeee"+sensorid);
				MyInterp mi=new MyInterp(x,y);
				mi.dumpValues(0,outputEnd-outputStart,outputSamplePeriod);
				for(int i=0;i<totalSize;i++)
				{
					double cur=0.0;

					cur=mi.y[i];

					DTuple tmpTuple=new DTuple();
					//we only add the reading now, if we need ts, and other attrributes, we can add it here.
					Double d=new Double(cur);
					tmpTuple.add(d);
					//System.out.println("gogogo:"+cur+","+tmpTuple.elementAt(0).toString());
					inputInterpedTables[ttt].add(tmpTuple);
				}
				System.out.println("come to print table");
				//inputInterpedTables[ttt].print();
			}*/


			for(int ttt=0;ttt<4;ttt++)
			if(tmpTable[ttt].tuples.size()==0)
			{
				System.out.println("the table is empty: "+nnid[ttt]);
				return ;
			}
			else
			{
				float []x=new float[tmpTable[ttt].tuples.size()];
				float []y=new float[tmpTable[ttt].tuples.size()];
				for(int i=0;i<tmpTable[ttt].tuples.size();i++)
				{
					x[i]=(float)(Misc.getSeconds((String)(tmpTable[ttt].tupleAt(i).elementAt(0)))-outputStart);
					if(i>=1)
					if(x[i]==x[i-1])
					x[i]=x[i]+1;
				}
				for(int cc=0;cc< columnToInterp.size();cc++)
				{
					int columnIndex=((Integer)(columnToInterp.elementAt(cc))).intValue();
					for(int i=0;i<tmpTable[ttt].tuples.size();i++)
					y[i]=Float.parseFloat(tmpTable[ttt].tupleAt(i).elementAt(columnIndex).toString());

					MyInterp mi=new MyInterp(x,y);
					if(! forVMNET)
					//mi.dumpValues(0,outputEnd-outputStart,outputSamplePeriod);
					mi.dumpValues(0,totalSize*outputSamplePeriod,outputSamplePeriod);
					else
					{
						System.out.println("this is for VMNET, only 1000 records");
						mi.dumpValues(0,totalSize*outputSamplePeriod,outputSamplePeriod);

					}
					if(cc==0)
					{
						for(int i=0;i<totalSize;i++)
						{
							double cur=0.0;
							if(mi.y[i]>=0)
							cur=mi.y[i];
							DTuple tmpTuple=new DTuple();
							Double d=new Double(cur);
							tmpTuple.add(d);
							inputInterpedTables[ttt].add(tmpTuple);
						}
					}
					else
					{
						for(int i=0;i<totalSize;i++)
						{
							double cur=0.0;
							if(mi.y[i]>=0)
							cur=mi.y[i];
							inputInterpedTables[ttt].addValue(i,columnIndex-2,new Double(cur));
						}

					}
				}
			}

		}catch(Exception e)
		{
			System.out.println("SDGEN genMultipleInterpedTable 1, "+e);
		}

		System.out.println("size="+inputInterpedTables[0].tuples.size());
		double value=0;

		double tTT=0.0;
		for(int j=0;j<totalSize;j++)
		{

			DTuple tmpTuple=new DTuple();
			for(int cc=0;cc< columnToInterp.size();cc++)
			{
				value=0;
				for(int m=0;m<4;m++)
				{
					tTT=Double.parseDouble(inputInterpedTables[m].tupleAt(j).elementAt(cc).toString());
					value=value+tTT*weight[m];
				}
				tmpTuple.add(new Double(value));
			}

			outputInterpedTable.add(tmpTuple);

		}
		System.out.println("come on");
	//	outputInterpedTable.print();

		try
		{

			int vvalue=0;
			System.out.println("we are dumping to file 2: "+ sensorid+", "+"#"+outputInterpedTable.tuples.size());
		 	PrintWriter out= new PrintWriter(new BufferedWriter(new FileWriter("Sensor"+sensorid+".dat")));
		 	DTuple dt;
		 	for(int j=0;j<outputInterpedTable.tuples.size();j++)
		 	{
		 		int m=0;
		 		dt=outputInterpedTable.tupleAt(j);
		 		//edit by saven for whj's vmnet.
		 		//for(m=0;m<(dt.values.size()-1);m++)
		 		//	out.print(dt.elementAt(m).toString()+",");
		 		for(m=0;m<(dt.values.size());m++)
		 		{

		 			//out.print(dt.elementAt(m).toString()+",");
		 			if(outputTokens[m+2].equals("light"))
		 			{
						if(j==0)
						System.out.println("light???????????????");
		 				vvalue=MTS300.mts300_getraw_light((int)Double.parseDouble(dt.elementAt(m).toString()));
					}
		 			else
		 			if(outputTokens[m+2].equals("temperature"))
		 				vvalue=MTS300.mts300_getraw_temp((int)Double.parseDouble(dt.elementAt(m).toString()));
		 			else
		 			{
						if(j==0)
						System.out.println("othersothers!2");
		 				vvalue=(int)Double.parseDouble(dt.elementAt(m).toString());
					}
		 			if(m==dt.values.size()-1)
		 			out.println(vvalue);
		 			else
		 			out.print(vvalue+",");

				}
		 	}
		 	out.close();
		 }catch(Exception e)
		 {
		 	System.out.println("SDGEN genMultipleInterpedTable 2"+e);
		 }

 	}

 	public void HolisticGen(int sindex)
 	{


 		//get the near neibor:)
 		Node n=(Node)(OP.topo.nodes.elementAt(sindex));
 		System.out.println("************* dumpOutputTables for "+sindex);
 		System.out.println("here: "+n.id);
		if(IP.topo.isIn(n))
		{//(1)
			genSingleInterpedTable(n.id);
		}
		else
		{//(2), not in the input topology

			genMultipleInterpedTable(n.id);

		}



 	}

 	SDGEN(String iXML, String oXML)
 	{
 		inputSchema=new String();
 		outputSchema=new String();
 		types=new Vector();
 		schema=new Vector();

 		IP=new InputParser();
 		OP=new OutputParser();
 		dataSets="";
 		inputXML=iXML;
 		outputXML=oXML;
 		columnToInterp=new Vector();
 		System.out.println("parsing documents: "+iXML+", "+oXML);
 		IP.parseXML(inputXML);
 		System.out.println(IP.schema.size()+","+schema.size());
 		OP.parseXML(outputXML);

 		dumpInputInfo();
 		dumpOutputInfo();

 		System.out.println("here is the output topology before mapping");
 		OP.topo.print();
 		OP.topo.mapTo(IP.topo);
 		System.out.println("here is the output topology after mapping");
 		OP.topo.print();

 		//check the output topology and input topology
 		if(!OP.topo.isCoverBy(IP.topo))
 		{
 			System.out.println("the minimum cover of the output topology is larger than the input topology");
 			System.exit(0);
 		}
 		else
 		{
 			System.out.println("topology coverage check passed");
 		}

 		//dump values to table.
 		getParseColumn();
 		MTS300.create_map(0,1023,0,1023);

 		/*for(int i=0;i<columnToInterp.size();i++)
 		interpIPTables(((Integer)(columnToInterp.elementAt(i))).intValue());*/

 		GetBound();
 		for(int i=0;i<OP.topo.nodes.size();i++)
 		{

 			HolisticGen(i);
 			System.gc();
 		}

 	}

 	public static void main(String []argv)
 	{
 		System.out.println("Welcome to DGEN (part of Bisque project)");
 		String iXML="";
 		String oXML="";
 		//java DGEN -i Input.xml -o Output.xml
 		for(int i=0;i<argv.length;i++)
 		{
	        System.out.print(argv[i]+" ");
	        System.out.println("");
	        //dispatch the arguments
        	// -i <inputXML> -o <outputXML>
	        if(argv[i].equals("-i"))
	        {
	        	iXML=argv[i+1];
	        }

	        if(argv[i].equals("-o"))
	        {
	        	oXML=argv[i+1];
	        }
    	}

    	if(oXML.length()>0 && iXML.length()>0)
	    {
	    SDGEN dgen=new SDGEN(iXML,oXML);
		}
	    else
	    {
	    	System.out.println("Please run the SDGEN using command with parameters");
	    	System.out.println("-i <input.xml> -o <output.xml>");
	    }




 	}




 }

