# File structures/CellComplex.rb, line 134
  def add (lower,data = nil, inverted = false)
    begin
      ## make sure that the lower cells are in the complex
      lower.each do |lowCell|
        if (!lowCell.is_a?(Cell) || !member?(lowCell))
          raise "object #{lowCell} is not a cell" 
        end
      end
      
      ## make sure that the lower cells all have the same dimension
      if (lower != [])
        ld = lower[0].dim
        exit if ld >= @dim
        lower.each do |lowCell|
          if (lowCell.dim != ld) 
            raise "boundary cells have different dimension" 
          end
        end
      end
      
      ## create the new cell and add it to the complex
      cellDim = (lower.empty? ? 0 : lower[0].dim+1 )
      cell = @cellCreate.call(self, cellDim, data)
      @lower[cell] = lower
      @upper[cell] = Array.new
      @cells[cellDim][cell] = true
      @inverted[cell] = inverted
      
      ## update the incidence and switch structures
      ## for the lower dimensional faces
      
      lower.each do |lowCell|
        @lower[lowCell].each do |lowestCell|
          matches = @upper[lowestCell] & lower
          if (matches.length > 2)
            raise "diamond property violation"
          end
          if (matches.length == 2)
            @switchH[[lowestCell,matches[1],cell]] = matches[0]
            @switchH[[lowestCell,matches[0],cell]] = matches[1]
          end
        end
        @upper[lowCell].push(cell)
      end
      
      ## if the new cell is an edge add the switch triples
      ## that start with the -1 dimensional cell
      
      if (cellDim == 1)
        if lower.length > 2
          raise "diamond property violation" 
        end
        if (lower.length == 2) 
          @switchH[[nil,lower[0],cell]] = lower[1]
          @switchH[[nil,lower[1],cell]] = lower[0]
        else
          ## self-loop
          @switchH[[nil,lower[0],cell]] = lower[0]
        end
      end
      
      ## if the new cell is a d-dimensional cell
      ## add the switch tripes that end with the d+1
      ## cell
      
      if (cell.dim == @dim)
        lower.each do |lowCell|
          upper = @upper[lowCell]
          if upper.length > 2
            raise "diamond property violation"
          end
          if (upper.length == 2)
            @switchH[[lowCell,upper[0],nil]] = upper[1]
            @switchH[[lowCell,upper[1],nil]] = upper[0]
          end
        end
      end
    return cell

    rescue
      raise $!
      #print "CellComplex.add: ",$!
      #exit
    end

  end