WITH exceptions AS (
	SELECT service, NOT (type - 1) as added
	FROM calendar_dates
	WHERE
		calendar_dates.date = date(:time)
)
SELECT
	unixepoch(stop_times.departure) -
	unixepoch(time(:time)) as wait,
	routes.*,
	trips.headsign,
	trips.short_name as trip_name,
	stop_times.arrival,
	stop_times.departure
FROM
	stop_times
JOIN trips
ON stop_times.trip_id = trips.id
JOIN routes
ON trips.route_id = routes.id
JOIN calendar
ON calendar.service = trips.service_id
LEFT JOIN exceptions
ON exceptions.service = calendar.service
WHERE
	stop_times.stop_id = :stop
AND
	stop_times.departure > time(:time)
AND (
	1 << (strftime('%w', :time) - 1) & calendar.days <> 0
AND
	calendar.start_date < date(:time)
AND
	calendar.end_date > date(:time)
AND
	added IS NULL
OR
	added)
ORDER BY
	stop_times.departure
LIMIT :limit;
