# Path: mta_data/utils.py
# def st_line_locate_point(linestring, p):
# 
#     coords = linestring.coords
#     before_length = after_length = seg_length = 0
#     best_dist = 1000000000
# 
#     found = None
#     for i in range(len(coords) - 1):
#         p0, p1 = coords[i:i+2]
#         this_length = sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) **2)
#         # next four lines from comp.graphics.algorithms Frequently
#         # Asked Questions  via GEOS
# 
#         dx=p1[0]-p0[0]
#         dy=p1[1]-p0[1]
#         len2=dx*dx+dy*dy
#         r=((p[0]-p0[0])*dx+(p[1]-p0[1])*dy)/len2
# 
#         if r < 0:
#             r = 0
#             dist = (p0[0] - p[0]) ** 2 + (p0[1] - p[1]) ** 2
#         elif r > 1:
#             r = 1
#             dist = (p1[0] - p[0]) ** 2 + (p1[1] - p[1]) ** 2
# 
#         else:
#             dist = dist_line_point(p0, p1, p)
#             
#         if dist < best_dist:
#             best_dist = dist
# 
#             found = r
#             before_length += after_length + seg_length
#             after_length = 0
#             seg_length = this_length
#         else:
#             if found is None:
#                 before_length += this_length
#             else:
#                 after_length += this_length
# 
#     total_length = before_length + seg_length + after_length
#     before_r = before_length / total_length
#     seg_r = seg_length / total_length
# 
#     return before_r + found * seg_r


from django.contrib.gis.geos import LineString, Point
from django.core.management.base import BaseCommand
from mta_data_parser import parse_schedule_dir
from mta_data.models import *
from mta_data.utils import st_line_locate_point
from subway_stop_to_gid import stop_id_to_gid, end_of_line
from zipfile import ZipFile
import os
import re
import transitfeed
import zipfile
                import pdb;pdb.set_trace()
            import traceback
            import pdb;pdb.set_trace()
    #add back extra files
    z = zipfile.ZipFile('mta_data/subway.zip', 'a', zipfile.ZIP_DEFLATED)
    z.write('mta_data/subway-gtfs/entrances.txt', 'entrances.txt')
    z.write('mta_data/subway-gtfs/stop_entrances.txt', 'stop_entrances.txt')
    z.close()

def handle_buses(dirname):

    feed = transitfeed.Loader("mta_data/bus-gtfs.zip", memory_db=False).Load() #base data
    current_borough = None

    #capture multiple stops with different box ids
    stop_name_to_stop = {}

    last_route = None
    for route_rec in parse_schedule_dir(os.path.join(dirname, 'surface-bus'), 'stif'):
        #gtfs files are organized by borough (not bus prefix)
        if current_borough != route_rec['borough']:
            if current_borough:
                feed.Validate()
                feed.WriteGoogleTransitFeed('mta_data/bus-%s.zip' % current_borough)
                feed = transitfeed.Loader("mta_data/gtfs.zip", memory_db=False).Load()
                stop_name_to_stop = {}
            current_borough = route_rec['borough']

        if route_rec['route_name_flag'] == 'X':
            #express buses
            borough = 'X'
        else:
            borough = route_rec['borough'].title()

# Path: mta_data/utils.py
# def st_line_locate_point(linestring, p):
# 
#     coords = linestring.coords
#     before_length = after_length = seg_length = 0
#     best_dist = 1000000000
# 
#     found = None
#     for i in range(len(coords) - 1):
#         p0, p1 = coords[i:i+2]
#         this_length = sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) **2)
#         # next four lines from comp.graphics.algorithms Frequently
#         # Asked Questions  via GEOS
# 
#         dx=p1[0]-p0[0]
#         dy=p1[1]-p0[1]
#         len2=dx*dx+dy*dy
#         r=((p[0]-p0[0])*dx+(p[1]-p0[1])*dy)/len2
# 
#         if r < 0:
#             r = 0
#             dist = (p0[0] - p[0]) ** 2 + (p0[1] - p[1]) ** 2
#         elif r > 1:
#             r = 1
#             dist = (p1[0] - p[0]) ** 2 + (p1[1] - p[1]) ** 2
# 
#         else:
#             dist = dist_line_point(p0, p1, p)
#             
#         if dist < best_dist:
#             best_dist = dist
# 
#             found = r
#             before_length += after_length + seg_length
#             after_length = 0
#             seg_length = this_length
#         else:
#             if found is None:
#                 before_length += this_length
#             else:
#                 after_length += this_length
# 
#     total_length = before_length + seg_length + after_length
#     before_r = before_length / total_length
#     seg_r = seg_length / total_length
# 
#     return before_r + found * seg_r


# Path: mta_data/management/commands/mta_to_gtfs.py
from django.contrib.gis.geos import LineString, Point
from django.core.management.base import BaseCommand
from mta_data_parser import parse_schedule_dir
from mta_data.models import *
from mta_data.utils import st_line_locate_point
from subway_stop_to_gid import stop_id_to_gid, end_of_line
from zipfile import ZipFile
import os
import re
import transitfeed
import zipfile
                import pdb;pdb.set_trace()
            import traceback
            import pdb;pdb.set_trace()

    #add back extra files
    z = zipfile.ZipFile('mta_data/subway.zip', 'a', zipfile.ZIP_DEFLATED)
    z.write('mta_data/subway-gtfs/entrances.txt', 'entrances.txt')
    z.write('mta_data/subway-gtfs/stop_entrances.txt', 'stop_entrances.txt')
    z.close()

def handle_buses(dirname):

    feed = transitfeed.Loader("mta_data/bus-gtfs.zip", memory_db=False).Load() #base data
    current_borough = None

    #capture multiple stops with different box ids
    stop_name_to_stop = {}

    last_route = None
    for route_rec in parse_schedule_dir(os.path.join(dirname, 'surface-bus'), 'stif'):
        #gtfs files are organized by borough (not bus prefix)
        if current_borough != route_rec['borough']:
            if current_borough:
                feed.Validate()
                feed.WriteGoogleTransitFeed('mta_data/bus-%s.zip' % current_borough)
                feed = transitfeed.Loader("mta_data/gtfs.zip", memory_db=False).Load()
                stop_name_to_stop = {}
            current_borough = route_rec['borough']

        if route_rec['route_name_flag'] == 'X':
            #express buses
            borough = 'X'
        else:
            borough = route_rec['borough'].title()

        name = "%s%s" % (borough, 