class Distribution
  ##
  # Distribute a section of width w and height h in a length and a width scale
  # that makes n tables fit.
  #   distribute_lattice 10, 10, 3 #=> [5.0, 5.0]
  #   distribute_lattice 10, 10, 4 #=> [5.0, 5.0]
  ##
  distribute_lattice: (w, h, n)->
    epsilon = 1e-10
    w = parseFloat(w)
    h = parseFloat(h)
    n = parseInt(n)
    area = w*h
    l = Math.sqrt(area/n)
    nx = w/l
    ny = h/l
    while Math.floor(w/l + epsilon) * Math.floor(h/l + epsilon) < n
      tx = w/l
      ty = h/l
      # The biggest remainder is closest to a fitting option
      # Just add one if no remainder wins and it still is not enough
      if (tx % 1) < epsilon and (ty % 1) < epsilon
        # Both divide, but there is no solution yet. Just add one
        l = Math.max(Math.round(w/(tx + 1)), Math.round(h/(ty + 1)))
        nx = Math.ceil(tx)
        ny = Math.ceil(ny)
      else if (tx % 1) > (ty % 1)
        nx = Math.ceil(tx)
        ny = Math.ceil(n/nx)
        l = w/nx
      else
        ny = Math.ceil(ty)
        nx = Math.ceil(n/ny)
        l = h/ny
    [w/nx, h/ny]
App.Distribution = new Distribution()
