New db import method
New db import method

file:b/.box (new)
--- /dev/null
+++ b/.box
@@ -1,1 +1,5 @@
+shared_writable_dirs:
+    - /labs/tiles
+    - /lib/staticmaplite/cache
+php_extensions: [pgsql, pdo, pdo_pgsql, curl]
 

--- a/include/common-template.inc.php
+++ b/include/common-template.inc.php
@@ -34,17 +34,18 @@
 <meta name="viewport" content="width=device-width, initial-scale=1"> 	
 <title>' . $pageTitle . '</title>
         <meta name="google-site-verification" content="-53T5Qn4TB_de1NyfR_ZZkEVdUNcNFSaYKSFkWKx-sY" />
-	<link rel="stylesheet"  href="' . $labsPath . 'css/jquery-ui-1.8.12.custom.css" />
-	<script src="' . $labsPath . 'js/LAB.min.js"></script> ';
+<link rel="dns-prefetch" href="//code.jquery.com">
+<link rel="dns-prefetch" href="//ajax.googleapis.com">
+	<link rel="stylesheet"  href="' . $labsPath . 'css/jquery-ui-1.8.12.custom.css" />';
 	if (isDebugServer()) {
 		$jqmcss = $labsPath . 'css/jquery.mobile-1.0b1.css';
 		$jqjs = $labsPath . 'js/jquery-1.6.1.min.js';
 		$jqmjs = $labsPath . 'js/jquery.mobile-1.0b1.js';
 	}
 	else {
-		$jqmcss = "http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css";
-		$jqjs = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js";
-		$jqmjs = "http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js";
+		$jqmcss = "//code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.css";
+		$jqjs = "//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js";
+		$jqmjs = "//code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js";
 	}
 	echo '<link rel="stylesheet"  href="' . $jqmcss . '" />
 	<script src="'.$jqjs.'"></script>
@@ -53,16 +54,12 @@
 });
 </script> 
 	<script src="'.$jqmjs.'"></script>
-	
-	 <script>
-	  $LAB.setOptions({AlwaysPreserveOrder:true})
-  .script("' . $jqjs . '").wait()
-
-.script("' . $labsPath . 'js/jquery.ui.core.min.js")
-.script("' . $labsPath . 'js/jquery.ui.position.min.js")
-.script("' . $labsPath . 'js/jquery.ui.widget.min.js").wait()
-  .script("' . $labsPath . 'js/jquery.ui.autocomplete.min.js")
- .wait(function() {
+
+<script src="' . $labsPath . 'js/jquery.ui.core.min.js"></script>
+<script src="' . $labsPath . 'js/jquery.ui.position.min.js"></script>
+<script src="' . $labsPath . 'js/jquery.ui.widget.min.js"></script>
+  <script src="' . $labsPath . 'js/jquery.ui.autocomplete.min.js"></script>
+  <script>
 	$(function() {
 		$( "#geolocate" ).autocomplete({
 			source: "lib/autocomplete.php",
@@ -77,7 +74,6 @@
 			minLength: 2
 		});
 	});
-});
 	</script>';
 	echo '<style type="text/css">';
 	if (strstr($_SERVER['HTTP_USER_AGENT'], 'Android')) echo '.ui-shadow,.ui-btn-up-a,.ui-btn-hover-a,.ui-btn-down-a,.ui-body-b,.ui-btn-up-b,.ui-btn-hover-b,
@@ -181,13 +177,12 @@
 	}
 	echo "\n</div></div></body></html>";
 }
-function timePlaceSettings($geolocate = false)
+function placeSettings()
 {
 	global $service_periods;
 	$geoerror = false;
-	if ($geolocate == true) {
 		$geoerror = !isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "";
-	}
+
 	echo '<div id="error">';
 	if ($geoerror) {
 		echo 'Sorry, but your location could not currently be detected.
@@ -196,27 +191,13 @@
 	}
 	echo '</div>';
 	echo '<div id="settings" data-role="collapsible" data-collapsed="' . !$geoerror . '">
-        <h3>Change Time/Place (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3>
+        <h3>Change Location...</h3>
         <form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post">
         <div class="ui-body"> 
 		<div data-role="fieldcontain">
 	            <label for="geolocate"> Current Location: </label>
 			<input type="text" id="geolocate" name="geolocate" value="' . (isset($_SESSION['lat']) && isset($_SESSION['lon']) ? $_SESSION['lat'] . "," . $_SESSION['lon'] : "Enter co-ordinates or address here") . '"/> <a href="#" style="display:none" name="here" id="here">Here?</a>
 	        </div>
-    		<div data-role="fieldcontain">
-		        <label for="time"> Time: </label>
-		    	<input type="time" name="time" id="time" value="' . (isset($_SESSION['time']) ? $_SESSION['time'] : date("H:i")) . '"/>
-			<a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();' . "$('#time').val(d.getHours() +':'+ (d.getMinutes().toString().length == 1 ? '0'+ d.getMinutes():  d.getMinutes()));" . '">Current Time?</a>
-	        </div>
-		<div data-role="fieldcontain">
-		    <label for="service_period"> Service Period:  </label>
-			<select name="service_period" id="service_period">';
-	foreach ($service_periods as $service_period) {
-		echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>';
-	}
-	echo '</select>
-			<a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a>
-		</div>
 		
 		<input type="submit" value="Update"/>
                 </div></form>

--- a/include/common.inc.php
+++ b/include/common.inc.php
@@ -31,7 +31,8 @@
 
 function isDebugServer()
 {
-	return !isset($_SERVER['SERVER_NAME']) || $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "10.1.0.4" || $_SERVER['SERVER_NAME'] == "localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1" ;
+	return php_sapi_name() == "cli" || isset($_SERVER['SERVER_NAME']) && ( $_SERVER['SERVER_NAME'] == "10.0.1.154" || $_SERVER['SERVER_NAME'] == "10.1.0.4" || $_SERVER['SERVER_NAME'] == 
+"localhost" || $_SERVER['SERVER_NAME'] == "127.0.0.1") ;
 }
 
 include_once ("common-geo.inc.php");

--- a/include/db/trip-dao.inc.php
+++ b/include/db/trip-dao.inc.php
@@ -173,6 +173,22 @@
 	$r = $query->fetch(PDO::FETCH_ASSOC);
 	return $r['arrival_time'];
 }
+function getTripEndTime($tripID)
+{
+	global $conn;
+	$query = "SELECT trip_id,max(arrival_time) as arrival_time from stop_times
+	WHERE stop_times.arrival_time IS NOT NULL and trip_id = :tripID group by trip_id";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":tripID", $tripID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	$r = $query->fetch(PDO::FETCH_ASSOC);
+	return $r['arrival_time'];
+}
 function getActiveTrips($time)
 {
 	global $conn;

file:a/index.php -> file:b/index.php
--- a/index.php
+++ b/index.php
@@ -24,7 +24,6 @@
 		<li><a class="nearby" href="routeList.php?nearby=yes">Nearby Routes</a></li>
             </ul>
 <?php
-echo timePlaceSettings();
 echo ' <a href="labs/index.php" data-role="button" data-icon="beaker">Busness R&amp;D</a>';
 include_footer(true)
 ?>

--- a/labs/myway_timeliness_calculate.php
+++ b/labs/myway_timeliness_calculate.php
@@ -1,6 +1,8 @@
 <?php
 include ('../include/common.inc.php');
 include_header("MyWay Delta Calculate", "mywayDeltaCalc");
+flush();
+ob_flush();
 function abssort($a, $b)
 {
 	if ($a['timeDiff'] == $b['timeDiff']) {
@@ -40,8 +42,10 @@
 		echo "error, route '{$obsv['myway_route']}' unknown";
 		continue;
 	}
-	//		:convert timestamp into time of day and date
+	// convert timestamp into time of day and date
+// timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html
 	$time = date("H:i:s", strtotime($obsv['time']));
+    $time_tz = date("H:i:s", strtotime($obsv['time']))." AESST";
         $search_time = date("H:i:s", strtotime($obsv['time'])-(30*60)); // 30 minutes margin
 	$date = date("c", strtotime($obsv['time']));
 	$timing_period = service_period(strtotime($date));
@@ -102,6 +106,8 @@
 			//print out that stops/does not stop
 			echo "No matching routes found at {$potentialStop['stop_code']}<br>";
                         var_dump($stopRoutes);
+                        			flush();
+
 		}
 	}
 	//   lowest delta is recorded delta
@@ -119,7 +125,7 @@
 		$stmt->bindParam(':route_full_name', $route_full_name);
 		$stmt->bindParam(':stop_code', $stop_code);
 		$stmt->bindParam(':timing_delta', $lowestDelta);
-		$stmt->bindParam(':time', $time);
+		$stmt->bindParam(':time', $time_tz);
 		$stmt->bindParam(':date', $date);
 		$stmt->bindParam(':timing_period', $timing_period);
                 $stmt->bindParam(':stop_sequence', $stop_sequence);
@@ -129,6 +135,7 @@
 			echo "Recorded.<br>";
 		}
 		var_dump($conn->errorInfo());
+			flush();
 	}
 	flush();
 }

--- a/labs/myway_timeliness_freqdist.php
+++ b/labs/myway_timeliness_freqdist.php
@@ -38,41 +38,8 @@
 
             grid: { hoverable: true, clickable: true, labelMargin: 17  },
     });
- /*       var o;
-    o = plot.pointOffset({ x: midnight+ (9*60*60*1000), y: -1.2});
-    placeholder.append('<div style="position:absolute;left:' + (o.left + 4) + 'px;top:' + o.top + 'px;color:#666;font-size:smaller">9am</div>');
-    o = plot.pointOffset({ x: midnight+ (16*60*60*1000), y: -1.2});
-    placeholder.append('<div style="position:absolute;left:' + (o.left + 4) + 'px;top:' + o.top + 'px;color:#666;font-size:smaller">4pm</div>');
- */
+
  });
 
-  /*
-    var previousPoint = null;
-    $("#placeholder").bind("plothover", function (event, pos, item) {
-        $("#x").text(pos.x.toFixed(2));
-        $("#y").text(pos.y.toFixed(2));
  
-            if (item) {
-                if (previousPoint != item.dataIndex) {
-                    previousPoint = item.dataIndex;
-                    
-                    $("#tooltip").remove();
-                    var x = item.datapoint[0].toFixed(2),
-                        y = item.datapoint[1].toFixed(2);
-                    
-                    var d = new Date();
-d.setTime(x);
-var time = d.getUTCHours() +':'+ (d.getUTCMinutes().toString().length == 1 ? '0'+ d.getMinutes():  d.getUTCMinutes())
-
-                    
-                    showTooltip(item.pageX, item.pageY,
-                                item.series.label + " at "+ time +" = " + Math.abs(new Number(y/60).toFixed(2))+" minutes "+(y >0 ? "early":"late"));
-                }
-            }
-            else {
-                $("#tooltip").remove();
-                previousPoint = null;            
-            }
-    });
-  */
 </script> 

--- /dev/null
+++ b/labs/myway_timeliness_overview.php
@@ -1,1 +1,97 @@
+<?php
+include ('../include/common.inc.php');
+include_header("MyWay Deltas", "mywayDelta");
+?>
+<table>
+    <tr><td></td><td>Mean</td><td>Standard<br>Deviation</td><td>Sample Size</td></tr>
+<th> Overall </th>
+<?php
+$query = "select '', avg(timing_delta), stddev(timing_delta), count(*)  from myway_timingdeltas ";
+$query = $conn->prepare($query);
+$query->execute();
+if (!$query) {
+	databaseError($conn->errorInfo());
+	return Array();
+}
+foreach ($query->fetchAll() as $row) {
+	echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>";
+};
+?>
 
+
+<th> Hour of Day </th>
+<?php
+$query = "select extract(hour from time), avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas group by extract(hour from time) order by extract(hour from time)";
+$query = $conn->prepare($query);
+$query->execute();
+if (!$query) {
+	databaseError($conn->errorInfo());
+	return Array();
+}
+foreach ($query->fetchAll() as $row) {
+	echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>";
+};
+?>
+
+<th> Day of Week </th>
+<?php
+$query = "select to_char(date, 'Day'), avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas group by to_char(date, 'Day') order by to_char(date, 'Day')";
+$query = $conn->prepare($query);
+$query->execute();
+if (!$query) {
+	databaseError($conn->errorInfo());
+	return Array();
+}
+foreach ($query->fetchAll() as $row) {
+	echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>";
+};
+?>
+<th>Month </th>
+<?php
+$query = "select to_char(date, 'Month'), avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas group by to_char(date, 'Month') order by to_char(date, 'Month')";
+$query = $conn->prepare($query);
+$query->execute();
+if (!$query) {
+	databaseError($conn->errorInfo());
+	return Array();
+}
+foreach ($query->fetchAll() as $row) {
+	echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>";
+};
+?>
+
+<th>Stop </th>
+<?php
+$query = "select myway_stop, avg(timing_delta), stddev(timing_delta), count(*)  from myway_timingdeltas INNER JOIN myway_observations
+ON myway_observations.observation_id=myway_timingdeltas.observation_id group by myway_stop having  count(*) > 1 order by myway_stop";
+$query = $conn->prepare($query);
+$query->execute();
+if (!$query) {
+	databaseError($conn->errorInfo());
+	return Array();
+}
+foreach ($query->fetchAll() as $row) {
+	echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>";
+};
+?>
+<th>Route </th>
+<?php
+$query = "select route_full_name, avg(timing_delta), stddev(timing_delta), count(*) from myway_timingdeltas  group by route_full_name having  count(*) > 1 order by route_full_name";
+$query = $conn->prepare($query);
+$query->execute();
+if (!$query) {
+	databaseError($conn->errorInfo());
+	return Array();
+}
+foreach ($query->fetchAll() as $row) {
+	echo "<tr><td>{$row[0]}</td><td>" . floor($row[1]) . "</td><td>" . floor($row[2]) . "</td><td>{$row[3]}</td></tr>";
+};
+?>
+
+
+</table>
+
+<?php
+include_footer();
+?>
+

--- a/labs/myway_timeliness_route.php
+++ b/labs/myway_timeliness_route.php
@@ -34,6 +34,10 @@
                 tickFormatter: yformatter
             },
             grid: { hoverable: true, clickable: true, labelMargin: 32   },
+series: {
+      lines: { show: false },
+      points: { show: true }
+    }
     };
     
     var plot = $.plot(placeholder, data, options);
@@ -118,3 +122,4 @@
     });
 
 </script> 
+

--- a/labs/myway_timeliness_stop.json.php
+++ b/labs/myway_timeliness_stop.json.php
@@ -29,3 +29,4 @@
     else echo "[".implode(",",$points)."]";
 ?>
 }
+

--- a/labs/myway_timeliness_stop.php
+++ b/labs/myway_timeliness_stop.php
@@ -40,6 +40,10 @@
                 tickFormatter: yformatter
             },
             grid: { hoverable: true, clickable: true, labelMargin: 32   },
+ series: {
+      lines: { show: false },
+      points: { show: true }
+    }
     };
 
     var plot = $.plot(placeholder, data, options);
@@ -129,3 +133,4 @@
     });
 
 </script> 
+

--- a/labs/mywaybalance.php
+++ b/labs/mywaybalance.php
@@ -113,6 +113,10 @@
         <label for="contribute_myway">Contribute MyWay records to timeliness study? </label>
         <input type="checkbox" name="contribute_myway" id="contribute_myway" defaultChecked="no"  />
     </div>
+    <div data-role="fieldcontain">
+        <label for="accept_warning">I accept that Transport for Canberra <a href="http://transport.act.gov.au/myway/protect.html">advise against the use of third party MyWay applications</a> </label>
+        <input type="checkbox" name="accept_warning" id="accept_warning" defaultChecked="no"  />
+    </div>
         <input type="submit" value="Go!"></form>';
 }
 include_footer();

--- /dev/null
+++ b/labs/travelAllRoutes.php
@@ -1,1 +1,23 @@
+<?php
+include ('../include/common.inc.php');
+	$query = "Select route_short_name,max(route_id) as route_id from routes where route_short_name NOT LIKE '7__'  AND route_short_name != '170' AND route_short_name NOT LIKE '9__' group by route_short_name order by route_short_name ;";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->execute();
+echo "<table><tr><th>Route Number</th><th>First Trip Start</th><th>First Trip End</th><th>Length</th>";
+$total = 0;
+$count = 0;
+foreach($query->fetchAll() as $r) {
+        $trips = getRouteTrips($r['route_id']);
+    $startTime = $trips[0]['arrival_time'];
+    $endTime = getTripEndTime($trips[0]['trip_id']);
+    $timeDiff = strtotime($endTime) - strtotime($startTime);
+    $total += $timeDiff;
+    $count ++;
+    echo "<tr><td>{$r['route_short_name']}</td><td>$startTime</td><td>$endTime</td><td>$timeDiff seconds ie. ". ($timeDiff/60). " minutes</td></tr>";
 
+}
+echo "</table>";
+echo "Total time: $total seconds ie. " .($total/60/60). " hours<br>";
+echo "$count Routes";
+?>

--- a/routeList.php
+++ b/routeList.php
@@ -44,7 +44,7 @@
 		include_header("Routes Nearby", "routeList", true, true);
 		trackEvent("Route Lists", "Routes Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']);
 		navbar();
-		timePlaceSettings(true);
+		placeSettings();
 		if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") {
 			include_footer();
 			die();

file:a/stop.php -> file:b/stop.php
--- a/stop.php
+++ b/stop.php
@@ -61,6 +61,7 @@
 	}
 }
 include_header($stop['stop_name'], "stop");
+
 /*$serviceAlerts = json_decode(getPage(curPageURL() . "/servicealerts_api.php?filter_class=stop&filter_id=".$stopid) , true);
 
 foreach($serviceAlerts['entities'] as $serviceAlert) {
@@ -82,7 +83,31 @@
 		)
 	)) ;
 }
-timePlaceSettings();
+
+// time settings
+echo '<div id="settings" data-role="collapsible" data-collapsed="true">
+<h3>Change Time (' . (isset($_SESSION['time']) ? $_SESSION['time'] : "Current Time,") . ' ' . ucwords(service_period()) . ')...</h3>
+        <form action="' . basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'] . '" method="post">
+        <div class="ui-body"> 
+    		<div data-role="fieldcontain">
+		        <label for="time"> Time: </label>
+		    	<input type="time" name="time" id="time" value="' . (isset($_SESSION['time']) ? $_SESSION['time'] : date("H:i")) . '"/>
+			<a href="#" name="currentTime" id="currentTime" onClick="var d = new Date();' . "$('#time').val(d.getHours() +':'+ (d.getMinutes().toString().length == 1 ? '0'+ d.getMinutes():  d.getMinutes()));" . '">Current Time?</a>
+	        </div>
+		<div data-role="fieldcontain">
+		    <label for="service_period"> Service Period:  </label>
+			<select name="service_period" id="service_period">';
+	foreach ($service_periods as $service_period) {
+		echo "<option value=\"$service_period\"" . (service_period() === $service_period ? " SELECTED" : "") . '>' . ucwords($service_period) . '</option>';
+	}
+	echo '</select>
+			<a href="#" style="display:none" name="currentPeriod" id="currentPeriod">Current Period?</a>
+		</div>
+		
+		<input type="submit" value="Update"/>
+                </div></form>
+            </div>';
+
 echo '</span><span class="content-primary">';
 echo '  <ul data-role="listview"  data-inset="true">';
 if (sizeof($allStopsTrips) > 0) {

--- a/stopList.php
+++ b/stopList.php
@@ -40,7 +40,6 @@
 		$stops = getStops();
 		include_header("All Stops", "stopList");
 		navbar();
-		timePlaceSettings();
 	}
 	else if (isset($nearby)) {
 		$listType = 'nearby=yes';
@@ -48,7 +47,7 @@
 		trackEvent("Stop Lists", "Stops Nearby", $_SESSION['lat'] . "," . $_SESSION['lon']);
 		navbar();
 		if (!isset($_SESSION['lat']) || !isset($_SESSION['lat']) || $_SESSION['lat'] == "" || $_SESSION['lon'] == "") {
-			timePlaceSettings(true);
+			placeSettings();
 			include_footer();
 			die();
 		}
@@ -65,7 +64,7 @@
 			);
 		}
 		echo staticmap($stopPositions, 0, "iconb", true, true);
-		timePlaceSettings(true);
+		placeSettings();
 		echo '</span><span class="content-primary">';
 	}
 	else if (isset($suburb)) {
@@ -78,7 +77,6 @@
 		$stops = getStops(true, $firstLetter);
 		include_header("Timing Points / Major Stops", "stopList");
 		navbar();
-		timePlaceSettings();
 	}
 	echo '  <ul data-role="listview" data-filter="true" data-inset="true" >';
 	if (!isset($firstLetter) && !isset($suburb) && !isset($nearby)) {

--- a/updatedb.php
+++ b/updatedb.php
@@ -2,6 +2,9 @@
 if ( php_sapi_name() == "cli") {
 include ('include/common.inc.php');
 $conn = pg_connect("dbname=transitdata user=postgres password=snmc host=localhost") or die('connection failed');
+$pdconn = new PDO("pgsql:dbname=transitdata;user=postgres;password=snmc;host=localhost");
+
+
 // Unzip cbrfeed.zip, import all csv files to database
 $unzip = true;
 $zip = zip_open(dirname(__FILE__) . "/cbrfeed.zip");
@@ -31,8 +34,18 @@
 		echo "Opening $file \n";
 		$line = 0;
 		$handle = fopen($tmpdir . $file, "r");
+		 if ($tablename =="stop_times") {
+			 $stmt = $pdconn->prepare("insert into stop_times (trip_id,stop_id,stop_sequence) values(:trip_id, :stop_id, :stop_sequence);");
+		$stmt->bindParam(':trip_id',$trip_id);
+				$stmt->bindParam(':stop_id',$stop_id);
+						$stmt->bindParam(':stop_sequence',$stop_sequence);
+	}
+
+
 		while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
-			if ($line > 0) {
+			if ($line == 0) {
+			
+			} else { 
 				$query = "insert into $tablename values(";
                                 $valueCount = 0;
                                 foreach ($data as $value) {
@@ -44,14 +57,22 @@
 				} else {
                                   $query.= "');";
                                 }
-                                if ($tablename =="stop_times" && $data[1] == "") {
-                                  $query = "insert into $tablename (trip_id,stop_id,stop_sequence) values('{$data[0]}','{$data[3]}','{$data[4]}');";
-                                }
+               if ($tablename =="stop_times" && $data[1] == "") {
+                //                  $query = "insert into $tablename (trip_id,stop_id,stop_sequence) values('{$data[0]}','{$data[3]}','{$data[4]}');";
+                $trip_id=$data[0];
+                $stop_id=$data[3];
+                $stop_sequence=$data[4];
+               }
                                  
 			}
-                        $result = pg_query($conn, $query);
+              if ($tablename =="stop_times") {
+	              $stmt->execute();
+	          }
+              else {
+	              $result = pg_query($conn, $query);
+	          }
 			$line++;
-                        if ($line % 10000 == 0) echo "$line records... \n";
+                        if ($line % 10000 == 0) echo "$line records... ".date('c')."\n";
 		}
 		fclose($handle);
 		echo "Found a total of $line records in $file.\n";