module Chronic::Handlers

def dealias_and_disambiguate_times(tokens, options) #:nodoc:

:nodoc:
def dealias_and_disambiguate_times(tokens, options) #:nodoc:
  # handle aliases of am/pm
  # 5:00 in the morning -> 5:00 am
  # 7:00 in the evening -> 7:00 pm
  day_portion_index = nil
  tokens.each_with_index do |t, i|
    if t.get_tag(RepeaterDayPortion)
      day_portion_index = i
      break
    end
  end
  time_index = nil
  tokens.each_with_index do |t, i|
    if t.get_tag(RepeaterTime)
      time_index = i
      break
    end
  end
  if (day_portion_index && time_index)
    t1 = tokens[day_portion_index]
    t1tag = t1.get_tag(RepeaterDayPortion)
    if [:morning].include?(t1tag.type)
      puts '--morning->am' if Chronic.debug
      t1.untag(RepeaterDayPortion)
      t1.tag(RepeaterDayPortion.new(:am))
    elsif [:afternoon, :evening, :night].include?(t1tag.type)
      puts "--#{t1tag.type}->pm" if Chronic.debug
      t1.untag(RepeaterDayPortion)
      t1.tag(RepeaterDayPortion.new(:pm))
    end
  end
  # handle ambiguous times if :ambiguous_time_range is specified
  if options[:ambiguous_time_range] != :none
    ttokens = []
    tokens.each_with_index do |t0, i|
      ttokens << t0
      t1 = tokens[i + 1]
      if t0.get_tag(RepeaterTime) && t0.get_tag(RepeaterTime).type.ambiguous? && (!t1 || !t1.get_tag(RepeaterDayPortion))
        distoken = Token.new('disambiguator')
        distoken.tag(RepeaterDayPortion.new(options[:ambiguous_time_range]))
        ttokens << distoken
      end
    end
    tokens = ttokens
  end
  tokens
end