Index: proiecte/ptvs/src/vnsim/core/Engine.java
===================================================================
--- proiecte/ptvs/src/vnsim/core/Engine.java	(revision 31)
+++ proiecte/ptvs/src/vnsim/core/Engine.java	(revision 38)
@@ -23,8 +23,4 @@
 import vnsim.applications.ezcab.EzcabClient;
 import vnsim.applications.trafficview.SimulatedCarInfo;
-import vnsim.applications.vitp.CarRunningVITP;
-import vnsim.applications.vitp.predefinedqueries.PredefinedQueries;
-import vnsim.applications.vitp.predefinedqueries.QueryByLocation;
-import vnsim.applications.vitp.predefinedqueries.QueryByVehicleId;
 import vnsim.core.events.CleanupEvent;
 import vnsim.core.events.Event;
@@ -106,7 +102,15 @@
 	DataInputStream dis = null;
 
-	public int fps;
-
-	ArrayList<Event> eventQueue = null;
+	public static int fps;
+
+	static ArrayList<Event> eventQueue = null;
+	
+	/**
+	 * Mihaela Teler
+	 * de fiecare data cand vreau sa fac o adaugare in eventQueue, intai verific punctul de unde vine evenimentul si astfel asignez
+	 * un thread pt procesarea ulterioara a acelui eveniment(cand va fi scos din coada..)
+	 * folosesc un singur eventQueue dar modific clasa Event sa contina si o referinta la un Thread
+	 */
+	
 
 	//Petroaca - the DSRC emergency channel
@@ -115,9 +119,11 @@
 	public boolean pauseFlag = true;
 
-	boolean doneFlag = false,doneFlagEmergency=false;
-
-	public ArrayList<SimulatedCarInfo> cars = null;
-
-	public int crtTime = 0;
+	static boolean doneFlag = false;
+
+	boolean doneFlagEmergency=false;
+
+	public static ArrayList<SimulatedCarInfo> cars = null;
+
+	public static int crtTime = 0;
 
 	public long t0 = 0L;
@@ -127,5 +133,5 @@
 	boolean runtimeMobility;
 
-	public boolean disableComm = false;
+	public static boolean disableComm = false;
 
 	File fText = null, fBin = null;
@@ -138,6 +144,14 @@
 	double lastSimSecond = 0.0;
 	
-	int eventsTime = 0, mobilityTime = 0, cleanupTime = 0, netTime = 0, codeTime = 0;
-	int schedTime = 0,  moveTime = 0, semTime = 0;
+	int eventsTime = 0, mobilityTime = 0;//, netTime = 0, codeTime = 0;
+
+	static int cleanupTime = 0;
+	static int netTime = 0;
+	static int codeTime = 0;
+	static int schedTime = 0;
+
+	int moveTime = 0;
+
+	static int semTime = 0;
 
 	public double maxControlDelay = 0;
@@ -194,35 +208,27 @@
 	public void init() {
 
-//		try{
-//			File f=new File(".//maps//map//apaca.map");
-//			if(!f.exists()) {
-//				System.out.println("NOT EXIST!");
-//				Globals.map = new trafficview.object.Map(".//maps\\rt\\apaca.RT1",".\\maps\\rt\\apaca.RT2");
-//				
-////				Globals.map = new trafficview.object.Map(".\\maps\\rt\\Intersectie.RT1","Intersectie.RT2");
-//				// Globals.map = new trafficview.object.Map("Autostrada.RT1","Autostrada.RT2");
-//				
-////				Globals.map = new trafficview.object.Map("TGR34023_2.RT1","TGR34023_2.RT2");
-//				ObjectOutputStream oos=new ObjectOutputStream(new
-//						FileOutputStream(".\\maps\\map\\apaca.map"));
-//				oos.writeObject(Globals.map);
-//			} else {
-//				System.out.println("EXIST!");
-//				ObjectInputStream ois=new ObjectInputStream(new
-//						FileInputStream(".\\maps\\map\\apaca.map"));
-//				Globals.map=(trafficview.object.Map)ois.readObject();
-//			}
-//		}catch(Exception e){
-//			System.err.println("Error reading map;");
-//			e.printStackTrace();
-//			System.exit(0);
-//		}
-//		 MapLoader.loadMap();
-		
-
 		Map map = Globals.map;
+		
+		//System.out.println("roads.size: "+map.roads.size()+" : "+map.roads.get(0).getName());
+		
+		//Road road = (Road)map.roads.get(0);
+		
+		//System.out.println("road.points: "+road.points);
+		
+		//System.out.println("strada:"+road.getName()+":"+" road.crosses.size(): "+road.crosses.size());
+		
+			
+		ArrayList<Intersection> intersectii = map.allIntersections;
+		for(int q=0;q<intersectii.size();q++){
+			System.out.println("intersectia "+q+": "+" nume: "+intersectii.get(q).toString()+" "+intersectii.get(q).getMapPoint());
+		}
+		
+		System.out.println(".........................aici4.........");
+		
+		//***************************************************************
+		
 		if (map.roads.get(0).getName().startsWith("Iuliu") || map.roads.get(0).getName().startsWith("Dr"))
 		{
-	
+			
 			Globals.monitorWTL = (WirelessTrafficLight)map.allIntersections.get(1);
 		}
@@ -271,5 +277,6 @@
 		// init cars and events
 		eventQueue = new ArrayList<Event>();
-	
+		
+		
 		cars = new ArrayList<SimulatedCarInfo>();
 		
@@ -277,5 +284,5 @@
 
 		//Petroaca - if DSRC simulation then initialize the emergency event queue
-		if(this.simulationProtocol==Globals.PROTOCOL_DSRC)
+		if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
 			eventQueueEmergency = new ArrayList<Event>();
 		
@@ -290,31 +297,37 @@
 		}
 
-		synchronized (eventQueue) 
-		{
-			eventQueue.add(new GPSEvent(0));
-			
-			eventQueue.add(new CleanupEvent(1));
-			Iterator<SimulatedCarInfo> it = cars.iterator();
-			while (it.hasNext()) 
-			{
-				SimulatedCarInfo r = it.next();
-				int t = 4 + random.nextInt(Globals.executionFPS / 3);
-				schedEvent(new SendEvent(4, r,
-						SimulatedCarInfo.STANDARD_MESSAGE_ID));
-			}
-			
-			/* Szekeres A. START_MODIFY - add broadcast event for each traffic light*/
-			for(int i=0;i<Globals.map.allIntersections.size();i++) {
-				Intersection sender = Globals.map.allIntersections.get(i);
-				if (sender instanceof EmissionsTrafficLight)
+		/**
+		 * Mihaela Teler
+		 * inainte sa adaug evenimentul aflu pozitia de unde vine..
+		 */
+		synchronized (eventQueue) {
+			
+				// exceptie pt evenimentele GPS si Cleanup.. pe acestea le proceseaza threadul main
+				eventQueue.add(new GPSEvent(0));
+								
+				eventQueue.add(new CleanupEvent(1));
+				
+				Iterator<SimulatedCarInfo> it = cars.iterator();
+				while (it.hasNext()) 
 				{
-					((EmissionsTrafficLight)sender).init();
-					schedEvent(new SendEvent(4, (EmissionsTrafficLight)sender, (int)Globals.PROT_TL_FEEDBACK));
-				}
-			}			
-			/* Szekeres A. STOP_MODIFY */
-			
-		}
-
+					System.out.println("nu ai cum sa intri pe aici!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! cars este vida");
+					SimulatedCarInfo r = it.next();
+					schedEvent(new SendEvent(4, r, SimulatedCarInfo.STANDARD_MESSAGE_ID));
+					System.out.println("add in the queue..");
+				}
+				
+				/* Szekeres A. START_MODIFY - add broadcast event for each traffic light*/
+				for(int i=0;i<Globals.map.allIntersections.size();i++) {
+					Intersection sender = Globals.map.allIntersections.get(i);
+					if (sender instanceof EmissionsTrafficLight)
+					{
+						((EmissionsTrafficLight)sender).init();
+						schedEvent(new SendEvent(4, (EmissionsTrafficLight)sender, (int)Globals.PROT_TL_FEEDBACK));
+					}
+				}			
+				/* Szekeres A. STOP_MODIFY */
+		}
+		
+		
 		try 
 		{
@@ -341,5 +354,5 @@
 		}
 
-		if (this.simulationType == Globals.routePlanConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
+		if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
 			DelayRecord.initDelays();
 			this.infrastructure=new ArrayList<SimulatedCarInfo>();
@@ -347,10 +360,4 @@
 			InfrastructureNode.createInfrastructureNodes();
 		}
-		/*if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
-			RoadSegmentCost.initRoadSegmentsCost();
-			this.infrastructure=new ArrayList<SimulatedCarInfo>();
-			//create a fixed node for every intersection
-			IntersectionNode.createIntersectionNodes();
-		}*/
 
 		//Petroaca - instantiate the ricean propagation module
@@ -358,24 +365,28 @@
 		{
 		  if(Engine.propagationModel==Globals.RICEAN)
-			this.riceanModule=new Ricean(Globals.RICEAN_FILE_NAME,true);
+			Engine.riceanModule=new Ricean(Globals.RICEAN_FILE_NAME,true);
 		}
 		catch(IOException ioe){System.out.println("Ricean file io error:"+ioe.getMessage());System.exit(1);}
-		// System.out.println("Engine initialized - "+eventQueue.size()+"
-		// events");
-		// System.out.println("CARS:");
-		// System.out.println(cars);
-		// System.out.println("Events:");
-		// System.out.println(eventQueue);
-		
-//		Road r = Globals.map.roads.get(5);
-//		Point p = r.points.get(10900);
-//		int i = 10899;
-//		while (true){
-//			Point px = r.points.get(i);
-//			i--;
-//			if (p.getDistance() - px.getDistance() > 10)
-//				break;
-//		}
-//		System.out.println(i + " " +(p.getDistance() - r.points.get(i).getDistance()));
+		
+		System.out.println(">>> Engine initialized - "+eventQueue.size()+" events in the queue");
+		System.out.println("CARS:"+cars);
+		System.out.println("Events:"+eventQueue);
+		 
+		
+		System.out.println();
+		
+		Road r = Globals.map.roads.get(1);
+		System.out.print("road:"+r.getName());
+		System.out.println("  r.points.size():"+r.points.size());
+		
+		Point p1 = r.points.get(r.points.size()-1);
+		System.out.println(p1);
+		Point p2 = r.points.get(r.points.size()-2);
+		System.out.println(p2);
+		
+		System.out.println("distanta: " +(p1.getDistance() - p2.getDistance()));
+		System.out.println("distanta: " +GPSutil.distance(p1, p2));
+		System.out.println("__________________end init____________________________\n");
+				
 
 	}
@@ -390,5 +401,5 @@
 
 		//Petroaca - if DSRC simulation also reset the emergency channel
-		if(this.simulationProtocol==Globals.PROTOCOL_DSRC)
+		if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
 			eventQueueEmergency = new ArrayList<Event>();
 		
@@ -413,6 +424,5 @@
 				while (it.hasNext()) {
 					SimulatedCarInfo r = it.next();
-					schedEvent(new SendEvent(crtTime + 2, r,
-							SimulatedCarInfo.STANDARD_MESSAGE_ID));
+					schedEvent(new SendEvent(crtTime + 2, r, SimulatedCarInfo.STANDARD_MESSAGE_ID));
 				}
 			}
@@ -420,5 +430,5 @@
 		
 //		Petroaca - if DSRC simulation also reset the emergency channel
-		if(this.simulationProtocol==Globals.PROTOCOL_DSRC)
+		if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
 			eventQueueEmergency = new ArrayList<Event>();
 	}
@@ -428,9 +438,9 @@
 	 * 
 	 */
-	public void play() 
-	{
+	public void play() {
 		// supposed to be in the init()
 		// between init and play() Globals.map.allIntersections is changing
 		// need to find a fix
+		
 		if (Engine.simulationType == RoutingConstants.DYNAMIC_CITY_ROUTE) {
 			CityTrafficLight.upgradeToCityTL();
@@ -441,5 +451,5 @@
 			server.init();
 		}
-		//
+		
 		prevRealSec = t0 = System.currentTimeMillis();
 		pauseFlag = false;
@@ -480,26 +490,20 @@
 	long lastTime = -1;
 	
+	////////////////////////////////////// step ///////////////////////////////////////////////////////////
 	/**
 	 * Process the events for the current step of the simulation
 	 *
 	 */
+	
+	static int cnt = 0;
+	
 	public void step() {
-		int cnt = 0;
+		
 		
 		if(Globals.SOCIALNETWORK == 1){
 			double sec = vnsim.socialNet.GlobalNetwork.nextReconfigurationTime*Globals.SECOND;
-//			if(crtTime == sec){
-//				int ret=JOptionPane.showConfirmDialog(null, "au trecut "+sec+" secunde");
-//				//vnsim.vehicular.generator.Mobility.events = new SortedEventsVector();
-//				Scenario s = vnsim.socialNet.Main.recofigurare();
-//				try {
-//					vnsim.socialNet.Main.addCarEvents(s,crtTime);
-//				} catch (Exception ex) {
-//					JOptionPane.showMessageDialog(null, "<html>ERROR! Map structure has been modified<br> Try rebuilding the map " + s.mapFileName +"!</html>");
-//				}
-//			}
-		}
-		
-		if (crtTime >  3.5 * Globals.HOUR){
+		}
+			
+		if (crtTime >  3.5 * Globals.HOUR){	//nu rulez mai mult de 3 ore juma
 			doneFlag = true;
 			System.exit(0);
@@ -533,44 +537,19 @@
 		
 		if (crtTime % Globals.MINUTE == 0){
-			System.out.println((crtTime / Globals.MINUTE) + " sim min;\t" +
-			"packets: "+ Globals.packets +"\t" +
-			" collided: "+Globals.collided + 
-			" lost: " + Globals.lost+
-			" interfered: " + Globals.interfered+
-			" max range: " + Globals.maxRange);
-			
-			Globals.pw.println((crtTime / Globals.MINUTE) + " sim min;\t" +
-					"packets: "+ Globals.packets +"\t" +
-					" collided: "+Globals.collided + 
-					" lost: " + Globals.lost+
-					" interfered: " + Globals.interfered+
-					" max range: " + Globals.maxRange);
+
 			Globals.packets = 0;
 			Globals.collided = 0;
 			Globals.lost = 0;
 			
-//			System.out.println((crtTime / Globals.MINUTE) + " sim min;\t" +
-//					"simulation time: "+ (System.currentTimeMillis() - t0) +"\t" +
-//					" cars: "+cars.size() + 
-//					" created " + created);
-			Globals.pw.println((crtTime / Globals.MINUTE) + 
-					" global volume: " + Globals.volume * 60+ 
-					" global demand: " + Globals.demand * 60);
+			System.out.println((crtTime / Globals.MINUTE) + " sim min;\t" +
+					"simulation time: "+ (System.currentTimeMillis() - t0) +"\t" +
+					" cars: "+cars.size() + " created " + created);
+
 			Globals.volume = 0;
 			Globals.demand = 0;
 			
 			//Petroaca
-			if(this.simulationProtocol==Globals.PROTOCOL_DSRC)
+			if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
 			{
-				/*System.out.print("\n");
-				System.out.println("DSRC DATA------------------------------");
-				System.out.println((crtTime / Globals.MINUTE)+ " min\t" + "weak :"+Globals.DSRC_PACKETS_LOST_WEAK+
-						" collided :"+Globals.DSRC_PACKETS_LOST_COLLISION+" ok: "+Globals.DSRC_PACKETS_RECEIVED_OK+
-						" lost Tx :"+Globals.DSRC_PACKETS_LOST_TX+" lost Rx :"+Globals.DSRC_PACKETS_LOST_RX+
-						"lost per :"+Globals.DSRC_PACKETS_LOST_PER+" lost corrupted :"+Globals.DSRC_PACKETS_LOST_CORRUPTED
-						+" total packets: "+Globals.DSRC_PACKETS_TOTAL);
-				System.out.println("send faliure Rx:"+Globals.DSRC_PACKETS_SEND_FALIURE_RX+" send faliure noise:"+Globals.DSRC_PACKETS_SEND_FALIURE_NOISE
-						);
-				*/
 				DSRCStatistics.addStatistic(new DSRCStatisticComponent(0,Globals.DSRC_PACKETS_LOST_WEAK,Globals.DSRC_PACKETS_TOTAL,Globals.DSRC_PACKETS_LOST_CORRUPTED,Globals.DSRC_PACKETS_LOST_COLLISION,Globals.DSRC_PACKETS_LOST_TX,Globals.DSRC_PACKETS_LOST_RX,Globals.DSRC_PACKETS_LOST_PER,Globals.DSRC_PACKETS_RECEIVED_OK
 						,0,0,Globals.CUMMULATIVE_PACKETS_FV,Globals.CUMMULATIVE_PACKETS_NFV,Globals.CUMMULATIVE_PACKETS_LAV,Globals.CUMMULATIVE_PACKETS_RAV,Globals.IRT_FV,Globals.IRT_NFV,Globals.IRT_LAV,Globals.IRT_RAV,0,0,0,0,this.cars.size(),Globals.EMERGENCY_RECEIVED,Globals.EMERGENCY_SENT));
@@ -589,5 +568,5 @@
 				Globals.DSRC_SEND=0;
 				
-				System.out.println((crtTime / Globals.MINUTE)+ " min\t"+"FV:"+Globals.CUMMULATIVE_PACKETS_FV+" NFV:"+Globals.CUMMULATIVE_PACKETS_NFV+" LAV:"+Globals.CUMMULATIVE_PACKETS_LAV+" RAV:"+Globals.CUMMULATIVE_PACKETS_RAV+" EMERGENCY_RECV:"+Globals.EMERGENCY_RECEIVED+" EMERGENCY_SENT:"+Globals.EMERGENCY_SENT);
+				//System.out.println((crtTime / Globals.MINUTE)+ " min\t"+"FV:"+Globals.CUMMULATIVE_PACKETS_FV+" NFV:"+Globals.CUMMULATIVE_PACKETS_NFV+" LAV:"+Globals.CUMMULATIVE_PACKETS_LAV+" RAV:"+Globals.CUMMULATIVE_PACKETS_RAV+" EMERGENCY_RECV:"+Globals.EMERGENCY_RECEIVED+" EMERGENCY_SENT:"+Globals.EMERGENCY_SENT);
 				
 				Globals.CUMMULATIVE_PACKETS_RAV=0;
@@ -608,15 +587,5 @@
 			if (lastTime == -1)
 				lastTime = t0;
-			long realTime = t1 - lastTime;
 			lastTime = t1;
-//			Globals.pw.println("\n-----");
-//			Globals.pw.println("5 virtual minutes = " + (double)realTime/1000);
-//			Globals.pw.println("density [veh/km] = " + (double) cars.size()/10);
-//			Globals.pw.println("events: " + (double) (100 * (eventsTime - codeTime - cleanupTime))
-//					/ realTime);
-//			Globals.pw.println("mobility: " + (double) (100 * mobilityTime)
-//					/ realTime);
-//			Globals.pw.println("code: " + (double) (100 * codeTime + cleanupTime) / realTime);
-//			Globals.pw.println("-----");
 
 			eventsTime = 0;
@@ -625,15 +594,4 @@
 			mobilityTime = 0;
 			
-			Globals.pw.println( "\n" + (crtTime / Globals.MINUTE) + " " +
-					" " + fincars + 
-					" "+ (totalControlDelay/fincars) +
-					" "+ (maxControlDelay) +
-					" "+ ( ( totalEM.fc * 100) / (1000 * totalkm)) +
-					" "+ (totalEM.fc / fincars) +
- 					" "+ (totalEM.co2 / fincars) +
-					" "+ (totalEM.co / fincars) +
-					" "+ (totalEM.hc / fincars) +
-					" "+ (totalEM.nox / fincars)
-					);
 			Globals.pw.flush();
 			
@@ -647,19 +605,5 @@
 			Globals.demo.st.addInfo("NOx: " + dec1((totalEM.nox * 20 )/ 1000)+" kg/h");
 			
-			
-
-			Globals.pwxc.println( (crtTime / Globals.MINUTE) + " " +
-					" " + fincars + 
-					" "+ (totalControlDelay/fincars) +
-					" "+ (maxControlDelay) +
-					" "+ ( (totalEM.fc * 100) / ( 1000 * totalkm)) +
-					" "+ (totalEM.fc / crossedCars) +
- 					" "+ (totalEM.co2 / crossedCars) +
-					" "+ (totalEM.co / crossedCars) +
-					" "+ (totalEM.hc / crossedCars) +
-					" "+ (totalEM.nox / crossedCars) +
-					" "+ crossedCars
-					);
-			Globals.pwxc.flush();
+
 			if (fincars>0) {
 				Globals.pwxc.println( "min " + (crtTime / Globals.MINUTE) +
@@ -677,16 +621,7 @@
 				Globals.pwxc.flush();
 			}
-			//fincars = 0;
-			//crossedCars = 0;
-			//totalkm = 0;
-			//totalEM = new EmissionsResults();
-			//totalControlDelay = 0;
-			//maxControlDelay = 0;
 		}		
 		
 		
-//		if (crtTime % Globals.SECOND == 0)
-//			
-//			if (crtTime % (Globals.executionFPS / Globals.FPS) == 0)
 		if (startedWithGUI) {
 			Globals.demo.st.setCount(crtTime);
@@ -695,5 +630,5 @@
 			//Globals.demo.st.setSemTime(mycnt);
 			Globals.demo.st.setNrEvents(eventQueue.size());
-			Globals.demo.st.setCarsNo(cars.size());
+			Globals.demo.st.setCarsNo(cars.size());			
 		}
 		
@@ -702,5 +637,5 @@
 //		Petroaca - if DSRC simualtion play the events in emergency channel as well
 		
-		if(this.simulationProtocol==Globals.PROTOCOL_DSRC && Globals.MULTI_CHANNEL)
+		if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && Globals.MULTI_CHANNEL)
 		{
 			while (true) {
@@ -719,5 +654,18 @@
 		}
 		
+		/**
+		 * Mihaela Teler
+		 * vreau sa aflu cate intersectii am
+		 * voi avea tot atatea threaduri
+		 */
+		Map map = Globals.map;
+		ArrayList<Intersection> intersectii = map.allIntersections;
+		int numThreads=intersectii.size();
+		
+		EventProcessingThread processingThreads[] = new EventProcessingThread[numThreads];
+		
+		
 		while (true) {
+			
 			if (eventQueue.size() == 0) {
 				doneFlag = true;
@@ -725,10 +673,84 @@
 			}
 			
+			// extrag un eveniment din coada !!!!! acum doar il extrag.. cand intru in playEvent il si scot cu remove(0)
 			Event e = (Event) eventQueue.get(0);
-			if (e.getTime() == crtTime) {
+			System.out.println("--- no of events in the queue:"+eventQueue.size() );
+			
+			/**
+			 * Mihaela Teler
+			 * vector de threaduri pt procesare evenimente in functie de locatie
+			 * procesez folosind threaduri doar evenimentele send si receive
+			 */
+			
+		
+			if((e instanceof SendEvent) || (e instanceof ReceiveEvent)){
+				
+				/**
+				 * Mihaela Teler
+				 * aflu locatia evenimentului
+				 */			
+				Road r = null;
+				Point p = null;
+				if(e instanceof SendEvent){
+					SendEvent se=(SendEvent)e;
+					r = (Road) Globals.map.roads.get(se.sender.getRoadIdx());	//aflu strada pe care se afla senderul
+					p = (Point) r.points.get(se.sender.getPointIdx());			//aflu punctul unde se afla senderul
+				}
+				if(e instanceof ReceiveEvent){
+					ReceiveEvent re=(ReceiveEvent)e;
+					r = (Road) Globals.map.roads.get(re.sender.getRoadIdx());
+					p = (Point) r.points.get(re.sender.getPointIdx());
+				}
+				
+				//System.out.println("p:"+p);
+				
+				/**
+				 * Mihaela Teler
+				 * parcurg toate intersectiile si o gasesc pe cea mai apropiata
+				 */
+				double MIN_DIST=Double.MAX_VALUE;
+				int indexClosestIntersection=0;
+				double distanta;
+				for(int i=0;i<intersectii.size();i++){ 
+					Intersection intersectie = intersectii.get(i);
+					if(r.getPoints().contains(intersectie.getMapPoint())){ //iau in calcul doar intersectiile aflate pe strada pe care sunt
+						distanta=GPSutil.distance(p, intersectie.getMapPoint());
+						if (distanta < MIN_DIST){
+							MIN_DIST=distanta;
+							indexClosestIntersection=i;						
+						}
+					}
+						
+				}
+				/**
+				 * Mihaela Teler
+				 * acum trebuie sa asignez un thread sa proceseze
+				 */
+				
+				if(e instanceof SendEvent){
+					processingThreads[indexClosestIntersection] = new SendEventProcessingThread(e,crtTime);
+				}
+				else processingThreads[indexClosestIntersection] = new ReceiveEventProcessingThread(e,crtTime);
+				
+				// nu e bine cu apelul lui run pt ca practic nu se porneste un thread nou ci 
+				// se apeleaza metoda run ca orice alta metoda dintr-o clasa, executia este secventiala..
+				
+				if (e.getTime() == crtTime) {
+					System.out.println("Processing thread "+indexClosestIntersection+" from intersection "+intersectii.get(indexClosestIntersection));
+					//processingThreads[indexClosestIntersection].start();// cu start nu merge ... why????
+					processingThreads[indexClosestIntersection].run();
+					cnt++;
+				}
+				else
+					break;
+			}
+			
+			else if (e.getTime() == crtTime) {
 				playEvent();
 				cnt++;
 			} else
 				break;
+			
+			
 		}
 		
@@ -743,4 +765,5 @@
 			else
 				generateScenarioPhase();
+		
 		checkCreateNewCars();
 		
@@ -749,10 +772,9 @@
 		mobilityTime += t4 - t3;
 
-		if (this.simulationType == Globals.routePlanConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
+		if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
 			if (crtTime % 100 == 0) {
 				for (int i = 0; i < this.infrastructure.size(); i++) {
 					
-					((InfrastructureNode) this.infrastructure.get(i))
-							.updateDelays();
+					((InfrastructureNode) this.infrastructure.get(i)).updateDelays();
 				}
 			}
@@ -764,99 +786,6 @@
 			server.step(crtTime);
 		}
-
-//		if (crtTime % Globals.MINUTE == 0){
-//			System.out.println("[Engine - step()] ");
-//			System.out.println("\ntotal: " + (double)(t4 - t0)/1000);
-//			System.out.println("events: " + (double) (100 * eventsTime)
-//					/ (t4 - t0));
-//			System.out.println("mobility: " + (double) (100 * mobilityTime)
-//					/ (t4 - t0));
-//			System.out.println("code: " + (double) (100 * codeTime)
-//					/ (t4 - t0));
-//			
-//		}
-		// System.out.println();
-		// System.out.println("crtTime "+crtTime);
-		// System.out.println("CARS:");
-		// System.out.println(cars);
-		// System.out.println("Events:");
-		// System.out.println(eventQueue);
-
-		//checkInjectQueries();
-
-//		if (crtTime % Globals.SECOND == 0){
-//			
-//			if (crtTime % (Globals.executionFPS / Globals.FPS) == 0)
-//				if (withGUI) {
-//					synchronized (Globals.mutex){
-//						Globals.flag = 1;
-//						Globals.mutex.notify();
-//					}
-//				}
-//		}else
-//			synchronized (Globals.mutex){
-//				Globals.mutex.notify();
-//			}
-
-	}
-
-	/**
-	 * VITP.
-	 *
-	 */
-	private void checkInjectQueries() {
-//		should inject some queries?
-		vnsim.applications.vitp.predefinedqueries.Query q=PredefinedQueries.queries.get(crtTime);
-		if(q!=null) 
-		{
-			if(q instanceof QueryByVehicleId) {
-				//look for the vehicle with the specified id
-				Iterator<SimulatedCarInfo> it = cars.iterator();
-				while (it.hasNext()) {
-					SimulatedCarInfo r = it.next();
-					if(r.getVehicleId()==((QueryByVehicleId)q).vehicleId) 
-					{
-						//inject the query
-						CarRunningVITP x = (CarRunningVITP)r;
-						if(!x.isEquipped)
-							continue; //look for an equipped vehicle
-						x.p.postMessageFromAbove(q.req);
-						System.out.println("QUERY INJECTED; CRTTIME="+crtTime);
-						break;
-					}	
-				}
-			} else if(q instanceof QueryByLocation) {
-				//look for a vehicle in the specified location
-				int roadIdx=((QueryByLocation)q).roadIdx;
-				int pointIdx=((QueryByLocation)q).pointIdx;
-
-				Iterator<SimulatedCarInfo> it = cars.iterator();
-				while (it.hasNext()) {
-					SimulatedCarInfo r = it.next();
-					if(r.getRoadIdx()==roadIdx && r.getPointIdx()<pointIdx+5 && r.getPointIdx()>pointIdx-5) {					
-						CarRunningVITP x = (CarRunningVITP)r;
-						if(!x.isEquipped)
-							continue; //look for an equipped vehicle
-						x.p.postMessageFromAbove(q.req);
-						System.out.println("QUERY INJECTED; CRTTIME="+crtTime);
-						
-//						Road road=Globals.map.roads.get(r.getRoadIdx());
-//
-//						Point p1=road.points.get(r.getPointIdx());
-//						Point p2=road.points.get(q.req.getDest().pt1);
-//
-//	//					System.out.println("P1="+r.getPointIdx());
-//	//					System.out.println("P2="+q.req.getDest().pt1);
-//	//
-//	//					System.out.println("AWAY="+(p1.getDistance()-p2.getDistance()));
-//	
-//						Statistics.setQueryDistance(MessageIndexModule.index, (p1.getDistance()-p2.getDistance()));
-//						Statistics.setInitialTime(MessageIndexModule.index, crtTime);
-						break;
-					}
-				}
-			}
-		}
-	}
+	}
+	//////////////////////////////////////////////end metoda step////////////////////////////////////
 
 	static Random random = new Random();
@@ -868,6 +797,5 @@
 	 *
 	 */
-	private void checkCreateNewCars() 
-	{
+	private void checkCreateNewCars(){
 
 		int percent;
@@ -929,7 +857,4 @@
 				//one vehicle on each lane
 
-//				double offset=4*random.nextDouble();
-//				System.out.println("OFFSET="+offset);
-
 				Personality personality;
 				rand=(random.nextDouble())*100;
@@ -950,5 +875,6 @@
 							roadIndexDst, pointIndexDst, r.route);
 					
-					System.out.println("Finished creating new car");
+					System.out.println("Finished creating new car "+car);
+					
 					double d =0;
 					if(car!=null)
@@ -957,11 +883,10 @@
 						// closer than 5 meters --> do not create
 						// System.out.println("Skipping creation...");
-						Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
-								.remove(car.ID);
+						Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);
 						continue;
 					}
 				}
 
-				if (this.simulationType == Globals.routePlanConstants.DYNAMIC_SELF_ROUTE) {
+				if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
 					System.out.println("Dynamic; we are here");
 					percent = random.nextInt(100);
@@ -983,11 +908,10 @@
 						// closer than 10 meters --> do not create
 						
-						Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad
-								.remove(car.ID);						
+						Globals.map.roads.get(car.getRoadIdx()).carsOnThisRoad.remove(car.ID);						
 						continue;
 					}
 
 				}
-				if (this.simulationType == Globals.routePlanConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
+				if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
 
 					car = Mobility.createNewCarCommunicatingWithInfrastucture(
@@ -1060,13 +984,16 @@
 	}
 
-	
-
-	long messagesSize = 0;
-	long carInfosSize = 0;
+////////////////////////////////////////// playEvent ////////////////////////////////////////////////////////////////	
+
+	static long messagesSize = 0;
+	static long carInfosSize = 0;
 	/**
 	 * Execute the following event in the eventQueue
 	 * 
 	 */
-	public void playEvent() {
+	public static void playEvent() {
+		
+		//System.out.println(">> Thread:"+Thread.currentThread().getName());
+		
 		if (eventQueue.size() == 0) {
 			doneFlag = true;
@@ -1078,8 +1005,9 @@
 			e = eventQueue.remove(0);
 		}
-		// System.out.print(e.toString()+", ");
-		// System.out.flush();
-		//		
-		if (e instanceof GPSEvent) {
+		//System.out.print(e.toString()+", ");
+		//System.out.flush();
+				
+		if (e instanceof GPSEvent) {	//////////// eveniment GPS
+			
 			Iterator<SimulatedCarInfo> it = cars.iterator();
 			while (it.hasNext()) {
@@ -1090,5 +1018,5 @@
 			schedEvent(newEvent);
 		}
-		if (e instanceof CleanupEvent) {
+		if (e instanceof CleanupEvent) {	//////////// eveniment CLEANUP
 
 			long t1 = System.currentTimeMillis();
@@ -1097,15 +1025,11 @@
 			while (it.hasNext()) {
 				SimulatedCarInfo r = it.next();
-//				if (r.isPromiscuousMode() && r.pointIdx < 256 && r.pointIdx > 50){
-//					r.getDirection();
-//				}
+
 				Iterator<CarInfo> j = r.trafficDB.iterator();
 				while (j.hasNext()) {
 					CarInfo neighbor = j.next();
-					if ( (crtTime - neighbor.getTimestamp() > Globals.NEIGHBOR_EXPIRES 
-							&& neighbor.state != 3) ||
+					if ( (crtTime - neighbor.getTimestamp() > Globals.NEIGHBOR_EXPIRES && neighbor.state != 3) ||
 							(neighbor.state == 3 && crtTime - neighbor.getTimestamp() > Globals.PROMISCUOUS_NEIGHBOR_EXPIRES)){
 						j.remove();
-//						deleted++;
 					}
 				}
@@ -1139,14 +1063,28 @@
 				schedEvent(newCleanupEvent);
 			}
-//			if (deleted != 0)
-//				System.out.println(crtTime+")\n\ttotal cars - "+carInfosSize+"\n\ttotal cars deleted- "+deleted+"\n\ttotal bytes transfered - "+messagesSize);
 			messagesSize = 0;
 		}
-		if (e instanceof SendEvent) {
+		
+		if (e instanceof SendEvent) {	/////////////////////////////// eveniment SEND
+			
+			/**
+			 * cod mutat in metoda run a lui SendEventProcessingThread - intre timp m-am razgandit.. am pornit threaduri in metoda step 
+			 */
+			
+			/*SendEventProcessingThread thread=new SendEventProcessingThread(e, crtTime, disableComm, messagesSize);
+			synchronized (eventQueue) {
+				if(!thread.isAlive()) {
+					thread.start();
+					System.out.println(".........................thread started");
+				}
+			}*/
+			
+			
 			SendEvent se = (SendEvent) e;
 			Communicator sender = se.getSender();
-
+			
 			long t1 = System.currentTimeMillis();	
 			
+			// senderul e un SimulatedCarInfo
 			
 			if (se.getMessage() == null){
@@ -1154,10 +1092,8 @@
 				se.setMessage(message);
 				if (se.getMessage() == null){
-	//				System.out.println("null message"+se.sender + " "+se.sender.getClass());
 					if (sender.isPromiscuousMode() && sender.isPeriodicalMessage(se.getMessageType()) && !disableComm) {
 						int eventPeriod = sender.getPeriod(se.getMessageType());
 						if (eventPeriod != -1)
-							schedEvent(new SendEvent(crtTime + eventPeriod, sender, se
-								.getMessageType()));
+							schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
 					}
 					return;
@@ -1170,6 +1106,5 @@
 					int eventPeriod = sender.getPeriod(se.getMessageType());
 					if (eventPeriod != -1)
-						schedEvent(new SendEvent(crtTime + eventPeriod, sender, se
-							.getMessageType()));
+						schedEvent(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
 				}
 			}
@@ -1178,5 +1113,5 @@
 			if(Engine.simulationProtocol==Globals.PROTOCOL_80211)
 			{
-				//			 TODO To be replaced with a real MAC layer
+				
 				if (!sender.mediumAvailable(crtTime)) {
 					e.setTime(crtTime + 1);
@@ -1227,46 +1162,21 @@
 					simulateCommunication(se);
 				}
-				
-				
-			}
-			
-
-			
-			
-			
-		}
-		if (e instanceof ReceiveEvent) {
+			}
+		}
+		
+		if (e instanceof ReceiveEvent) {	//////////////////////// eveniment RECEIVE
 			ReceiveEvent re = (ReceiveEvent) e;
-			
-//			long tmp = 0;
-//			long t3 = System.currentTimeMillis();
-//			long t4;
-//			if (re.isUnicast()) {
-//				long t1 = System.currentTimeMillis();
-//				re.receiver.onReceive(re.getMessage(), re.sender);
-//				long t2 = System.currentTimeMillis();
-//				codeTime += t2 - t1;
-//			} else {
+
 				long t1 = System.currentTimeMillis();
+				
 				//Petroaca - the DSRC impl
-				if(Engine.simulationProtocol==Globals.PROTOCOL_80211)
-				{
+				if(Engine.simulationProtocol==Globals.PROTOCOL_80211){
 					RadioDev rxradio = re.receiver.getRadio();
 					ReceiveEvent goodSignal = rxradio.receive(re.signals);
 					re.receiver.removeReceiveEventForTime(re.getTime());
 				
-//				for (ReceiveEvent goodSignal : re.signals){
-//					Road r1 = (Road) Globals.map.roads.get(re.sender.getRoadIdx());
-//					Point p1 = (Point) r1.points.get(re.sender.getPointIdx());
-//					Road r2 = (Road) Globals.map.roads.get(re.receiver.getRoadIdx());
-//					Point p2 = (Point) r2.points.get(re.receiver.getPointIdx());
-//					double distance = GPSutil.distance(p1, p2);
-//					if (distance <= WIRELESS_RANGE){
-						if (goodSignal != null){
+					if (goodSignal != null){
 							re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
 						}
-//					}
-//				}
-				
 				}
 				else
@@ -1298,11 +1208,6 @@
 								//appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
 								re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
-								
 							}
-						
-							
 						}
-						
-						
 					}
 					else
@@ -1312,206 +1217,16 @@
 						re.receiver.removeReceiveEventForTime(re.getTime());
 					
-
-							if (goodSignal != null){
+						if (goodSignal != null){
 								re.receiver.onReceive(goodSignal.getMessage(), goodSignal.getMessageObject(), goodSignal.sender);
 							}
-						
-
-					}
-					
-					
+					}
 				}	
 				
 				long t2 = System.currentTimeMillis();
 				codeTime += t2 - t1;
-/*				if (!re.sender.mediumAvailable(crtTime)) {
-					re.setTime(crtTime + 1);
-					schedEvent(re);
-					return;
-				}
-
-				Road r1 = null;
-				Point p1 = null;
-				if (re.sender instanceof SimulatedCarInfo){
-					SimulatedCarInfo sender = (SimulatedCarInfo)re.sender;
-					r1 = (Road) Globals.map.roads.get(sender.getRealPos()
-							.getRoadIdx());
-					p1 = (Point) r1.points.get(sender.getRealPos().getPointIdx());
-				}else{
-					WirelessTrafficLight wtl = (WirelessTrafficLight)re.sender;
-					r1 = (Road) Globals.map.roads.get(wtl.segments.get(0).roadIndex);
-					p1 = (Point) r1.points.get(wtl.segments.get(0).pointIndex);
-				}
-//				recvEventsCnt++;
-
-				long comp = 0;
-				// peanoKeys
-				int cnt2 = 0;
-				int cnt3 = 0;
-				int cnt4 = 0;
-				int pkcnt = 0;
-				PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
-
-				ListIterator<PeanoKey> pkit = Globals.map.peanoKeys
-						.listIterator(p1.getPeanoKeyIdx());
-				PeanoKey maxpk = null;
-				
-				double wifirange;
-				if (re.sender instanceof WirelessTrafficLight){
-					maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
-					wifirange = EXTENDED_WIRELESS_RANGE;
-				}else{
-					wifirange = WIRELESS_RANGE;
-					maxpk = pk.getMaxpk();
-				}
-				PeanoKey pkx = null;
-				for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
-					pkcnt++;
-					// long tc1 = System.currentTimeMillis();
-					// PeanoKey pkx = Globals.map.peanoKeys.get(idx);
-					if (pkx.compareTo(maxpk) > 0)
-						break;
-					// long tc2 = System.currentTimeMillis();
-					// comp += (tc2-tc1);
-
-					if (pkx.getCars() != null) {
-						Road r2 = (Road) Globals.map.roads.get(pkx
-								.getRoadIndex());
-						Point p2 = (Point) r2.points.get(pkx.getPointIndex());
-						if (GPSutil.distance(p1, p2) < wifirange) {
-							cnt3 += pkx.getCars().size();
-							Iterator<SimulatedCarInfo> it = pkx.getCars()
-									.iterator();
-							while (it.hasNext()) {
-								SimulatedCarInfo r = it.next();
-								if (re.sender instanceof SimulatedCarInfo)
-									if (r.getVehicleId() == ((SimulatedCarInfo)re.sender)
-										.getVehicleId())
-										continue;
-								r.setLastMediumTransmition(crtTime);
-								t4 = System.currentTimeMillis();
-								tmp += t4 - t3;
-								long t1 = System.currentTimeMillis();
-								r.onReceive(re.getMessage(), re.sender);
-								long t2 = System.currentTimeMillis();
-								codeTime += t2 - t1;
-								cnt2++;
-								t3 = System.currentTimeMillis();
-							}
-						}
-					}
-				}
-				PeanoKey minpk = null;
-				if (re.sender instanceof WirelessTrafficLight)
-					minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
-				else
-					minpk = pk.getMinpk();
-				
-				pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
-
-				if (pkit.hasPrevious()){
-					pkx = pkit.previous();
-				}
-				for (; pkit.hasPrevious(); pkx = pkit
-						.previous()) {
-					pkcnt++;
-					// long tc1 = System.currentTimeMillis();
-					// PeanoKey pkx = Globals.map.peanoKeys.get(idx);
-					if (pkx.compareTo(minpk) < 0) {
-						break;
-					}
-					// long tc2 = System.currentTimeMillis();
-					// comp += (tc2-tc1);
-
-					if (pkx.getCars() != null) {
-						Road r2 = (Road) Globals.map.roads.get(pkx
-								.getRoadIndex());
-						Point p2 = (Point) r2.points.get(pkx.getPointIndex());
-						if (GPSutil.distance(p1, p2) < wifirange) {
-							Iterator<SimulatedCarInfo> it = pkx.getCars()
-									.iterator();
-							cnt3 += pkx.getCars().size();
-							while (it.hasNext()) {
-								SimulatedCarInfo r = it.next();
-								r.setLastMediumTransmition(crtTime);
-								
-								if (re.sender instanceof SimulatedCarInfo)
-									if (r.getVehicleId() == ((SimulatedCarInfo)re.sender)
-										.getVehicleId())
-										continue;
-								
-								t4 = System.currentTimeMillis();
-								tmp += t4 - t3;
-								long t1 = System.currentTimeMillis();
-								r.onReceive(re.getMessage(), re.sender);
-								long t2 = System.currentTimeMillis();
-								codeTime += t2 - t1;
-								cnt4++;
-								t3 = System.currentTimeMillis();
-							}
-						}
-					}
-				}
-				
-				for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
-					WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
-							.get(Globals.map.lightsIndices.get(j));
-					long t1sem = System.currentTimeMillis();
-
-					if (GPSutil.distance(p1, wtl.getMapPoint()) < WIRELESS_RANGE) {
-						wtl.setLastMediumTransmition(crtTime);
-						wtl.onReceive(re.getMessage(), re.sender);
-					}
-					long t2sem = System.currentTimeMillis();
-					semTime += (t2sem - t1sem);
-				}
-				
-				t4 = System.currentTimeMillis();
-				tmp += t4 - t3;
-				netTime += tmp;
-				long t5 = System.currentTimeMillis();
-*/
-//				if (tmp > 0)
-//					avgTime += (double) (100 * comp) / tmp;
-//				if (pkcnt > pkmax)
-//					pkmax = pkcnt;
-//				avgi++;
-//				pkavg += cnt2;
-
-				// long t5 = System.currentTimeMillis();
-				//				
-				// if (cnt1 != cnt2 + cnt4){
-				// System.out.println("==== "+crtTime+" car: "+re.sender+ "
-				// ======\n"+
-				// "Count FAILED old:" + cnt1 +" - new: "+cnt2 +" +
-				// "+cnt4+"/"+pkcnt
-				// +" --- "+minpk+" - "+maxpk);
-				// }
-				// if (t5 - t4 > tmp){
-				// System.out.println("==== "+crtTime+" car: "+re.sender+ "
-				// ======\n"+
-				// "Time FAILED old:" + tmp+"/"+cnt1 +" - new: "+
-				// (t5-t4)+"/"+cnt2 +"/"+ cnt3+" / "+pkcnt +" - "+comp);
-				// }
-
-			}
-
-			// if (Globals.demo.mv.currentCar != null &&
-			// Globals.demo.mv.currentCar == re.getReceiver().car)
-			// System.out.println(i+" cars nearby");
-
-//		} // end if else isUnicast
-	}
-
-//	static int recvEventsCnt = 0;
-//
-//	static int pkmax;
-//
-//	static long pkavg = 0;
-//
-//	static double avgTime = 0;
-//
-//	static int avgi = 0;
-//
+			}
+	}
+
+
 	public void playEventEmergency()
 	{
@@ -1529,5 +1244,5 @@
 			SendEvent se = (SendEvent) e;
 			Communicator sender = se.getSender();
-
+			
 			long t1 = System.currentTimeMillis();	
 			
@@ -1541,6 +1256,5 @@
 						int eventPeriod = sender.getPeriod(se.getMessageType());
 						if (eventPeriod != -1)
-							schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se
-								.getMessageType()));
+							schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
 					}
 					return;
@@ -1553,6 +1267,5 @@
 					int eventPeriod = sender.getPeriod(se.getMessageType());
 					if (eventPeriod != -1)
-						schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se
-							.getMessageType()));
+						schedEventEmergency(new SendEvent(crtTime + eventPeriod, sender, se.getMessageType()));
 				}
 			}
@@ -1591,26 +1304,12 @@
 					return;
 				}
-				
-				
-				
-				
-			}
-			
-			
-		
+			}
+			
 		if (e instanceof ReceiveEvent) {
 			ReceiveEvent re = (ReceiveEvent) e;
 			
-//			long tmp = 0;
-//			long t3 = System.currentTimeMillis();
-//			long t4;
-//			if (re.isUnicast()) {
-//				long t1 = System.currentTimeMillis();
-//				re.receiver.onReceive(re.getMessage(), re.sender);
-//				long t2 = System.currentTimeMillis();
-//				codeTime += t2 - t1;
-//			} else {
-				long t1 = System.currentTimeMillis();
-				//Petroaca - the DSRC impl
+			long t1 = System.currentTimeMillis();
+			
+			//Petroaca - the DSRC impl
 				
 					if(re.receiver instanceof CarRunningDSRC)
@@ -1640,18 +1339,10 @@
 								//appr.LaneChangeAssistance(best.getMessage(),((CarInfo)re.receiver));
 								re.receiver.onReceive(best.getMessage(), best.getMessageObject(), best.sender);
-								
 							}
-						
-							
 						}
-						
-						
 					}
 					long t2 = System.currentTimeMillis();
 					codeTime += t2 - t1;
-					
 				}	
-				
-				
 	}
 	
@@ -1662,5 +1353,5 @@
 	 * @param e Event to schedule
 	 */
-	public void schedEvent(Event e) {
+	public static void schedEvent(Event e) {
 
 		long t1 = System.currentTimeMillis();
@@ -1728,5 +1419,165 @@
 	 * 
 	 */
-	public void simulateCommunication(SendEvent e) {
+	public static void simulateCommunication(SendEvent e) {
+		
+		Road r1 = null;
+		Point p1 = null;
+		r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
+		p1 = (Point) r1.points.get(e.sender.getPointIdx());
+		
+		if (e instanceof UnicastSendEvent) {
+			long t1 = System.currentTimeMillis();
+			Iterator<SimulatedCarInfo> it = cars.iterator();
+			ReceiveEvent re = null;
+			while (it.hasNext()) {
+				SimulatedCarInfo r = it.next();
+				if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
+					Road r2 = (Road) Globals.map.roads.get(r.getRealPos().getRoadIdx());
+					Point p2 = (Point) r2.points.get(r.getRealPos().getPointIdx());
+
+					// MODIFIED BY CRISTI!!!
+					// ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r, e.getMessage());
+
+					re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
+					re.setUnicast(true);
+
+					schedEvent(re);
+					if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
+					} else {
+						System.out.println("EROARE! DISTANCE="+ GPSutil.distance(p1, p2));
+					}
+					// END MODIFIED!!!
+					return;
+				}
+			}
+			
+			
+			re.setSender(e.getSender());
+			
+			schedEvent(re);
+
+			long t2 = System.currentTimeMillis();
+			netTime += t2 - t1;
+
+		} else {
+			
+			long tmp = 0;
+			long t3 = System.currentTimeMillis();
+			long t4;
+
+//			re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e.getMessage());
+			
+
+			int cnt3 = 0;
+			int pkcnt = 0;
+			PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
+
+			ListIterator<PeanoKey> pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
+			PeanoKey maxpk = null;
+			
+			double wifirange;
+			if (e.sender instanceof WirelessTrafficLight){
+				maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
+				wifirange = EXTENDED_WIRELESS_RANGE;
+			}else{
+				wifirange = WIRELESS_RANGE;
+				maxpk = pk.getMaxpk();
+			}
+			
+			PeanoKey pkx = null;
+			for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
+				pkcnt++;
+				// long tc1 = System.currentTimeMillis();
+				if (pkx.compareTo(maxpk) > 0)
+					break;
+				// long tc2 = System.currentTimeMillis();
+				// comp += (tc2-tc1);
+
+				if (pkx.getCars() != null) {
+					Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
+					Point p2 = (Point) r2.points.get(pkx.getPointIndex());
+					if (GPSutil.distance(p1, p2) < 5 * wifirange) {
+						cnt3 += pkx.getCars().size();
+						Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
+						while (it.hasNext()) {
+							SimulatedCarInfo r = it.next();
+							if (e.sender instanceof SimulatedCarInfo)
+								if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
+									continue;
+							r.setLastMediumTransmition(crtTime);
+							
+							ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
+							re.setSender(e.getSender());
+							schedEvent(re);
+						}
+					}
+				}
+			}
+			PeanoKey minpk = null;
+			if (e.sender instanceof WirelessTrafficLight)
+				minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
+			else
+				minpk = pk.getMinpk();
+			
+			pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
+
+			if (pkit.hasPrevious()){
+				pkx = pkit.previous();
+			}
+			for (; pkit.hasPrevious(); pkx = pkit.previous()) {
+				pkcnt++;
+				// long tc1 = System.currentTimeMillis();
+				if (pkx.compareTo(minpk) < 0) {
+					break;
+				}
+				// long tc2 = System.currentTimeMillis();
+				// comp += (tc2-tc1);
+
+				if (pkx.getCars() != null) {
+					Road r2 = (Road) Globals.map.roads.get(pkx.getRoadIndex());
+					Point p2 = (Point) r2.points.get(pkx.getPointIndex());
+					double distance = GPSutil.distance(p1, p2);
+					if (distance < 5 * wifirange) {
+						Iterator<SimulatedCarInfo> it = pkx.getCars().iterator();
+						cnt3 += pkx.getCars().size();
+						while (it.hasNext()) {
+							SimulatedCarInfo r = it.next();
+							
+							r.setLastMediumTransmition(crtTime);
+						
+							if (e.sender instanceof SimulatedCarInfo)
+								if (r.getVehicleId() == ((SimulatedCarInfo)e.sender).getVehicleId())
+									continue;
+							ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
+							re.setSender(e.getSender());
+							schedEvent(re);
+						}
+					}
+				}
+			}
+			
+			for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
+				WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
+						.get(Globals.map.lightsIndices.get(j));
+				long t1sem = System.currentTimeMillis();
+
+				if (GPSutil.distance(p1, wtl.getMapPoint()) < 5 * WIRELESS_RANGE) {
+					wtl.setLastMediumTransmition(crtTime);
+					ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, wtl, e.getMessage(), e.getMessageObject(), e.getMessageType());
+					re.setSender(e.getSender());
+					schedEvent(re);
+				}
+				long t2sem = System.currentTimeMillis();
+				semTime += (t2sem - t1sem);
+			}
+			
+			t4 = System.currentTimeMillis();
+			tmp += t4 - t3;
+			netTime += tmp;
+		}
+	}
+
+	//Petroaca - the communication simulation for the emergency channel
+	public void simulateCommunicationEmergency(SendEvent e) {
 
 		Road r1 = null;
@@ -1754,177 +1605,4 @@
 					re.setUnicast(true);
 
-					schedEvent(re);
-					if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
-					} else {
-						System.out.println("EROARE! DISTANCE="
-								+ GPSutil.distance(p1, p2));
-					}
-					// END MODIFIED!!!
-					return;
-				}
-			}
-			
-			re.setSender(e.getSender());
-			schedEvent(re);
-
-			long t2 = System.currentTimeMillis();
-			netTime += t2 - t1;
-
-		} else {
-			
-			long tmp = 0;
-			long t3 = System.currentTimeMillis();
-			long t4;
-
-//			re = new ReceiveEvent(e.getTime() + 1, e.getSender(), e
-//					.getMessage());
-			
-
-			long comp = 0;
-			// peanoKeys
-			int cnt2 = 0;
-			int cnt3 = 0;
-			int cnt4 = 0;
-			int pkcnt = 0;
-			PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
-
-			ListIterator<PeanoKey> pkit = Globals.map.peanoKeys
-					.listIterator(p1.getPeanoKeyIdx());
-			PeanoKey maxpk = null;
-			
-			double wifirange;
-			if (e.sender instanceof WirelessTrafficLight){
-				maxpk = GPSutil.getMaxSearchBoundPK(p1,Engine.EXTENDED_WIRELESS_RANGE);
-				wifirange = EXTENDED_WIRELESS_RANGE;
-			}else{
-				wifirange = WIRELESS_RANGE;
-				maxpk = pk.getMaxpk();
-			}
-			PeanoKey pkx = null;
-			for (pkx = pkit.next(); pkit.hasNext(); pkx = pkit.next()) {
-				pkcnt++;
-				// long tc1 = System.currentTimeMillis();
-				if (pkx.compareTo(maxpk) > 0)
-					break;
-				// long tc2 = System.currentTimeMillis();
-				// comp += (tc2-tc1);
-
-				if (pkx.getCars() != null) {
-					Road r2 = (Road) Globals.map.roads.get(pkx
-							.getRoadIndex());
-					Point p2 = (Point) r2.points.get(pkx.getPointIndex());
-					if (GPSutil.distance(p1, p2) < 5 * wifirange) {
-						cnt3 += pkx.getCars().size();
-						Iterator<SimulatedCarInfo> it = pkx.getCars()
-								.iterator();
-						while (it.hasNext()) {
-							SimulatedCarInfo r = it.next();
-							if (e.sender instanceof SimulatedCarInfo)
-								if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
-									.getVehicleId())
-									continue;
-							r.setLastMediumTransmition(crtTime);
-							
-							ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
-							re.setSender(e.getSender());
-							schedEvent(re);
-						}
-					}
-				}
-			}
-			PeanoKey minpk = null;
-			if (e.sender instanceof WirelessTrafficLight)
-				minpk = GPSutil.getMaxSearchBoundPK(p1,-Engine.EXTENDED_WIRELESS_RANGE);
-			else
-				minpk = pk.getMinpk();
-			
-			pkit = Globals.map.peanoKeys.listIterator(p1.getPeanoKeyIdx());
-
-			if (pkit.hasPrevious()){
-				pkx = pkit.previous();
-			}
-			for (; pkit.hasPrevious(); pkx = pkit
-					.previous()) {
-				pkcnt++;
-				// long tc1 = System.currentTimeMillis();
-				if (pkx.compareTo(minpk) < 0) {
-					break;
-				}
-				// long tc2 = System.currentTimeMillis();
-				// comp += (tc2-tc1);
-
-				if (pkx.getCars() != null) {
-					Road r2 = (Road) Globals.map.roads.get(pkx
-							.getRoadIndex());
-					Point p2 = (Point) r2.points.get(pkx.getPointIndex());
-					double distance = GPSutil.distance(p1, p2);
-					if (distance < 5 * wifirange) {
-						Iterator<SimulatedCarInfo> it = pkx.getCars()
-								.iterator();
-						cnt3 += pkx.getCars().size();
-						while (it.hasNext()) {
-							SimulatedCarInfo r = it.next();
-							r.setLastMediumTransmition(crtTime);
-						
-							if (e.sender instanceof SimulatedCarInfo)
-								if (r.getVehicleId() == ((SimulatedCarInfo)e.sender)
-									.getVehicleId())
-									continue;
-							ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
-							re.setSender(e.getSender());
-							schedEvent(re);
-						}
-					}
-				}
-			}
-			
-			for (int j = 0; j < Globals.map.lightsIndices.size(); j++) {
-				WirelessTrafficLight wtl = (WirelessTrafficLight) Globals.map.allIntersections
-						.get(Globals.map.lightsIndices.get(j));
-				long t1sem = System.currentTimeMillis();
-
-				if (GPSutil.distance(p1, wtl.getMapPoint()) < 5 * WIRELESS_RANGE) {
-					wtl.setLastMediumTransmition(crtTime);
-					ReceiveEvent re = new ReceiveEvent(e.getTime() + 1, wtl, e.getMessage(), e.getMessageObject(), e.getMessageType());
-					re.setSender(e.getSender());
-					schedEvent(re);
-				}
-				long t2sem = System.currentTimeMillis();
-				semTime += (t2sem - t1sem);
-			}
-			
-			t4 = System.currentTimeMillis();
-			tmp += t4 - t3;
-			netTime += tmp;
-		}
-	}
-
-	//Petroaca - the communication simulation for the emergency channel
-	public void simulateCommunicationEmergency(SendEvent e) {
-
-		Road r1 = null;
-		Point p1 = null;
-		r1 = (Road) Globals.map.roads.get(e.sender.getRoadIdx());
-		p1 = (Point) r1.points.get(e.sender.getPointIdx());
-		
-		if (e instanceof UnicastSendEvent) {
-			long t1 = System.currentTimeMillis();
-			Iterator<SimulatedCarInfo> it = cars.iterator();
-			ReceiveEvent re = null;
-			while (it.hasNext()) {
-				SimulatedCarInfo r = it.next();
-				if (r.vehicleId == ((UnicastSendEvent) e).getReceiverId()) {
-					Road r2 = (Road) Globals.map.roads.get(r.getRealPos()
-							.getRoadIdx());
-					Point p2 = (Point) r2.points.get(r.getRealPos()
-							.getPointIdx());
-
-					// MODIFIED BY CRISTI!!!
-					// ReceiveEvent er = new ReceiveEvent(e.getTime() + 1, r,
-					// e.getMessage());
-
-					re = new ReceiveEvent(e.getTime() + 1, r, e.getMessage(), e.getMessageObject(), e.getMessageType());
-					re.setUnicast(true);
-
 					schedEventEmergency(re);
 					if (GPSutil.distance(p1, p2) < WIRELESS_RANGE) {
@@ -1954,9 +1632,5 @@
 			
 
-			long comp = 0;
-			// peanoKeys
-			int cnt2 = 0;
 			int cnt3 = 0;
-			int cnt4 = 0;
 			int pkcnt = 0;
 			PeanoKey pk = Globals.map.peanoKeys.get(p1.getPeanoKeyIdx());
@@ -2151,8 +1825,7 @@
 					dc.setRealPos(car);
 					int t = 1 + random.nextInt(fps / 2 - 5);
-					schedEvent(new SendEvent(crtTime + t, dc,
-							SimulatedCarInfo.STANDARD_MESSAGE_ID));
+					schedEvent(new SendEvent(crtTime + t, dc,SimulatedCarInfo.STANDARD_MESSAGE_ID));
 					cars.add(dc);
-					dc.init();
+					dc.init();					
 				} 
 				else 
@@ -2294,5 +1967,5 @@
 			Random r;
 			int randId=0;
-			if(this.simulationProtocol==Globals.PROTOCOL_DSRC)
+			if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC)
 			{
 				r=new Random();
@@ -2333,9 +2006,9 @@
 						car.move();
 
-						if (this.simulationType == Globals.routePlanConstants.DYNAMIC_SELF_ROUTE) {
+						if (Engine.simulationType == RoutingConstants.DYNAMIC_SELF_ROUTE) {
 							QueryGeneration.generateQueryForCar(car);
 						}
 
-						if (this.simulationType == Globals.routePlanConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
+						if (Engine.simulationType == RoutingConstants.DYNAMIC_INFRASTRUCTURE_ROUTE) {
 							GuidanceRequest.generateRequestToInfrastructure(car);
 						}
@@ -2347,5 +2020,5 @@
 //						Petroaca - emergency messages schedule
 						
-						if(this.simulationProtocol==Globals.PROTOCOL_DSRC && car.ID==randId && crtTime%50==0)
+						if(Engine.simulationProtocol==Globals.PROTOCOL_DSRC && car.ID==randId && crtTime%50==0)
 						{
 							EmergencyRequest.generateEmergencyMessage(car);
@@ -2364,13 +2037,5 @@
 							car.startMonitor = false;
 						}
-						// 2 hardcoded exits for manhatan
-//						if (car.roadIdx == 2 && car.pointIdx < 7)
-//							car.finished = true;
-//						if (car.roadIdx == 13 && car.pointIdx < 95)
-//							car.finished = true;
-//						if (car.totalDistance > 10){
-//							System.out.println("Fuel: "+ car.em.fc / 1000);
-//							car.finished = true;
-//						}
+
 						car.updateCarToPointMapping();
 						 
@@ -2392,7 +2057,5 @@
 				} else {
 					// it's still on the same road
-					newVector
-							.addCarInstance(Globals.map.roads.get(j).carsOnThisRoad
-									.get(k));
+					newVector.addCarInstance(Globals.map.roads.get(j).carsOnThisRoad.get(k));
 				}
 				NCARS++;
@@ -2405,16 +2068,5 @@
 			Globals.map.roads.get(j).carsOnThisRoad = newVector;
 		}
-
-//		Iterator it2=cars.iterator();
-//		int countt2=0;
-//		
-//		while(it2.hasNext()) {
-//			SimulatedCarInfo sci=(SimulatedCarInfo)it2.next();
-//			
-//			if(sci.pulseMessage)
-//				countt2++;
-//		}
-//		System.out.println(" -- "+countt2+" / "+cars.size());
-		
+	
 		
 		if (!outputToFile)
@@ -2505,5 +2157,4 @@
 				Engine e = Globals.engine = new Engine(false, true);
 				e.init();
-//				Thread t = new Thread ( new Runnable(){
 //						public void run(){
 //							Globals.demo = new Display();
