+See the commentary section of this file for more details."
+ :group 'bbdb-csv-import
+ :type 'symbol)
+
+
+(defun bbdb-csv-import-expand-repeats (csv-fields list)
+ "Return new list where elements from LIST in form (repeat elem1
+...) become ((elem1 ...) [(elem2 ...)] ...) for as many fields
+exist in the csv fields. elem can be a string or a tree (a list
+with lists inside it). We use the first element as a template,
+and increase its number by one, and check if it exists, and then
+increment any other elements from the repeat list which have
+numbers in them."
+ (cl-flet ((replace-num (num string)
+ ;; in STRING, replace all groups of numbers with NUM
+ (replace-regexp-in-string "[0-9]+"
+ (number-to-string num)
+ string)))
+ (--reduce-from
+ (if (not (and (consp it) (eq (car it) 'repeat)))
+ (cons it acc)
+ (setq it (cdr it))
+ (let* ((i 1)
+ (first-field (car (-flatten it))))
+ (setq acc (cons it acc))
+ ;; use first-field to test if there is another repetition.
+ (while (member
+ (replace-num (setq i (1+ i)) first-field)
+ csv-fields)
+ (cl-labels ((fun (cell)
+ (if (consp cell)
+ (mapcar #'fun cell)
+ (replace-num i cell))))
+ (setq acc (cons (fun it) acc))))
+ acc))
+ nil list)))
+
+(defun bbdb-csv-import-map-bbdb (csv-fields root)
+ "ROOT is a root element from bbdb-csv-import-mapping-table. Get
+the csv-fields for root in the mapping format, including variably
+repeated ones. Flatten by one because repeated fields are put in
+sub-lists, but after expanding them, that extra depth is no
+longer useful. Small trade off: address mappings without 'repeat need
+to be grouped in a list because they contain sublists that we
+don't want flattened."
+ (bbdb-csv-import-flatten1
+ (bbdb-csv-import-expand-repeats
+ csv-fields
+ (cdr (assoc root bbdb-csv-import-mapping-table)))))