def should_stop(floor):
  for key in shared.order_map:
    order = shared.order_map[key]
    if (order.completed): #if the order already completed, continue
      continue
    if (orderlist.should_complete(order,floor)):  #if orderlist.should_complete(,) returns True we shall stop
      return True
  
  return False
def controller(floor, direction):
  shared.target_floor = -1
  
  best_cost = 999999999
  best_order = None
  for key in shared.order_map:  #goes through the dictionary with all the orders
    order = shared.order_map[key]
    if (order.completed): #if order completed, continue
      continue
    if not (order.assigned) or (order.assigned_to_id != shared.get_local_elevator_ID()):  #if the order is not assigned or the local elevator id is not equal to the assigned id, continue
      continue
    
    if (order.floor == floor) and not (orderlist.should_complete(order, floor)):  #if the floor is correct but the orderlist.should_complete(,) returns False, then continue
      continue
      
    cost = orderlist.cost_func(order, shared.local_elevator)  #set cost by calling the cost function with right order and local elevator
    
    if (cost < best_cost):  #if the cost is smallers then best_cost we set both best_cost and best_order
      best_cost = cost
      best_order = order
      
  if (best_order == None):  #if best_order equals to None then retruns False
    return False
  
  shared.target_floor = best_order.floor  #set target floor to the best_order's floor

  if (shared.target_floor < 0) or (shared.target_floor >= shared.N_FLOORS): #checking for something that should not happen, target floor < 0 or target floor > 4, elevator out of reach
    print "Should not be reached"
    set_speed(0)
    shared.target_dir = shared.NODIR
    return False
  
  if (shared.target_floor > floor): #checks if we have reached target floor, if not we set the target direction in the right direction
    set_speed(300)
    shared.target_dir = shared.UP
    return True
    
  
  elif (shared.target_floor < floor): #checks if we have reached target floor, if not we set the target direction in the right direction
    set_speed(-300)
    shared.target_dir = shared.DOWN
    return True
    
  elif (shared.target_floor == floor):  #target floor equals to floor
    if (driver.elev.elev_get_floor_sensor_signal() == -1):  #if jet not reached floor drive down to floor
      set_speed(-300)
      shared.target_dir = shared.NODIR  #sets target direction to no direction
      return True
    else: #in right floor
      set_speed(0)  #shall stop
      shared.target_dir = shared.NODIR  #sets target direction to no direction
      return True
  
  print "Should never reach this"
  return False