def computeTTC(databaseFilename,homography,framePerSecond,videoX,videoY,collisionDistanceThreshold,bikAreaOri,bikAreaDes,carAreaOri,carAreaDes):

    import numpy as np
    import sys
    sys.path.append('/home/sohail/trafficintelligence/python/')
    import moving, cvutils, storage
    import timeToCollision

    print 'Loading database...'
    objects = storage.loadTrajectoriesFromSqlite(databaseFilename, 'object')

    bikCount=0
    carCount=0
    bik=[]
    car=[]
    bikSpeed=[]
    carSpeed=[]

    for obj in objects:
	    inCarAreaOri = False
	    inBikAreaOri = False
	    for time in obj.getTimeInterval():
		x=int(obj.getPositionAtInstant(time).project(homography).x)
		y=int(obj.getPositionAtInstant(time).project(homography).y)
		x=min(videoX-1,x)
		y=min(videoY-1,y)
		if bikAreaOri[y,x] == 1 and obj.userType == moving.userType2Num['bicycle']:
		    inBikAreaOri = True
		if bikAreaDes[y,x] == 1 and inBikAreaOri == True:
		    bikCount += 1
		    bik.append(obj)
		    bikSpeed.append(framePerSecond*3.6*np.median(obj.getSpeeds()))
		    break
		if carAreaOri[y,x] == 1 and obj.userType == moving.userType2Num['car']:
		    inCarAreaOri = True
		if carAreaDes[y,x] == 1 and inCarAreaOri == True:
		    carCount += 1
		    car.append(obj)
		    carSpeed.append(framePerSecond*3.6*np.median(obj.getSpeeds()))
		    break

    print 'Computing TTC...'
    TTC=[]
    potCollision=0
    for obj1 in bik:
	for obj2 in car:
	    ti1=obj1.getTimeInterval()
	    ti2=obj2.getTimeInterval()
	    if ti1.first < ti2.last and ti2.first < ti1.last:
		potCollision += 1
		ttc=[]
		for frameNum in range(max(ti1.first,ti2.first),min(ti1.last,ti2.last)):
		    ttcp=timeToCollision.timeToCollision(obj1,obj2,collisionDistanceThreshold,frameNum,framePerSecond)
		    if ttcp < 100:
			ttc.append(ttcp)
		if ttc != []:
		    ttc.sort()
	            TTC.append(ttc[int(.15*len(ttc))])

    return bikCount,carCount,bikSpeed,carSpeed,TTC,potCollision

