code: def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None,
              method='average'):
      if ref_to_avg and ref_chan is not None:
          raise TypeError('You cannot specify reference to the average and '
                          'the channels to use as reference')
      if ref_chan is not None:
          if (not isinstance(ref_chan, (list, tuple)) or
              not all(isinstance(x, str) for x in ref_chan)):
                  raise TypeError('chan should be a list of strings')
      if ref_chan is None:
          ref_chan = []
      if bipolar:
          if not data.attr['chan']:
              raise ValueError('Data should have Chan information in attr')
          _assert_equal_channels(data.axis['chan'])
          chan_in_data = data.axis['chan'][0]
          chan = data.attr['chan']
          chan = chan(lambda x: x.label in chan_in_data)
          chan, trans = create_bipolar_chan(chan, bipolar)
          data.attr['chan'] = chan
      if ref_to_avg or ref_chan or bipolar:
          mdata = data._copy()
          idx_chan = mdata.index_of('chan')
          for i in range(mdata.number_of('trial')):
              if ref_to_avg or ref_chan:
                  if ref_to_avg:
                      ref_chan = data.axis['chan'][i]
                  ref_data = data(trial=i, chan=ref_chan)
                  if method == 'average':
                      mdata.data[i] = (data(trial=i) - mean(ref_data, axis=idx_chan))
                  elif method == 'regression':
                      mdata.data[i] = compute_average_regress(data(trial=i), idx_chan)
              elif bipolar:
                  if not data.index_of('chan') == 0:
                      raise ValueError('For matrix multiplication to work, '
                                       'the first dimension should be chan')
                  mdata.data[i] = dot(trans, data(trial=i))
                  mdata.axis['chan'][i] = asarray(chan.return_label(),
                                                  dtype='U')
      else:
          mdata = data
      return mdata