# File lib/vpim/date.rb, line 83
  def Date.bywday(year, mon, wday, n = 1, sg=Date::ITALY)
    # Normalize mon to 1-12.
    if mon
      if mon > 12 ||  mon == 0 || mon < -12
         raise ArgumentError, "mon #{mon} must be 1-12 or negative 1-12"
      end
      if mon < 0
        mon = 13 + mon
      end
    end
    if wday < 0 || wday > 6
      raise ArgumentError, 'wday must be in range 0-6, or a weekday name'
    end

    # Determine direction of indexing.
    inc = n <=> 0
    if inc == 0
      raise ArgumentError, 'n must be greater or less than zero'
    end

    # if !mon, n is index into year, but direction of search is determined by
    # sign of n
    d = Date.new(year, mon ? mon : inc, inc, sg)

    while d.wday != wday
      d += inc
    end

    # Now we have found the first/last day with the correct wday, search
    # for nth occurrence, by jumping by n.abs-1 weeks forward or backward.
    d += 7 * (n.abs - 1) * inc

    if d.year != year
      raise ArgumentError, 'n is out of bounds of year'
    end
    if mon && d.mon != mon
      raise ArgumentError, 'n is out of bounds of month'
    end
    d
  end