 
 (comment
 
+  (do
   (def test1
-    [{:a "A" :b "B" :c "C"}
-     {:a "D" :c "D"}
-     {:a "A" :d "D"}])
+    [{:a "A1" :b "B1" :c "C1"}
+     {:a "A2" :c "C2"}
+     {:a "A1" :d "D1"}])
+
+  (def test2
+    [{:a "A1" :b "B1"}])
+
+  (def test3
+    [{:a "A1" :c "C1"}]) )
 
   (get-subfields-for-keyword [:b :c :d] test1 :a "A")
+  {:a (parse-hierarchical-keywords [:a :b :c :d] test1)}
+
+  {:a [{:value "A1"
+        :subfields ["b" "d"]
+        :b [{:value "B1"
+             :subfields ["c"]
+             :c [{:value "C1"}]}]
+        :d [{:value "D1"}]}
+       {:value "A2"
+        :subfields ["c"]
+        :c [{:value "C2"}]}]}
+
+  (get-subfields-for-keyword [:b :c :d] test1 :a "A1")
+  (get-subfields-for-keyword [:b :c :d] test1 :a "A2")
+
+  {:a (parse-hierarchical-keywords [:a :b :c :d] test1)}
+
+  (= {:a (parse-hierarchical-keywords [:a :b :c :d] test1)}
+     {:a [{:value "A1"
+        :subfields ["b" "d"]
+        :b [{:value "B1"
+             :subfields ["c"]
+             :c [{:value "C1"}]}]
+        :d [{:value "D1"}]}
+       {:value "A2"
+        :subfields ["c"]
+        :c [{:value "C2"}]}]})
 
   )
 (defn- get-subfields-for-keyword
   "Figure out which subfield is directly below the current keyword. It is possible the next field
-  field in the hierarchy is nil, but further down the chain there is a non-nil field."
+  in the hierarchy is nil, but further down the chain there is a non-nil field."
   [remaining-hierarchy keywords field value]
   (loop [remaining-fields remaining-hierarchy
          matching-keywords (filter #(= value (field %)) keywords)
          all-subfields nil]
           (let [next-field (first remaining-fields)
-                keywords-below-with-next-field (keep next-field matching-keywords)
+                keywords-below-with-next-field (when next-field (keep next-field matching-keywords))
                 keywords-with-nil-next-field (filter #(nil? (next-field %)) matching-keywords)
                 all-subfields (if (seq keywords-below-with-next-field)
                                 (conj all-subfields next-field)

  (def keywords
   (vals (kms/get-keywords-for-keyword-scheme
           {:system (cmr.indexer.system/create-system)} :instruments)))

  )


                                :variable-level-1 [{:value "MOBILE GEOGRAPHIC INFORMATION SYSTEMS"
                                                    :uuid "0dd83b2a-e83f-4a0c-a1ff-2fbdbbcce62d"
                                                    }]}]}]}]}

  (def keywords
    [{:uuid "0dd83b2a-e83f-4a0c-a1ff-2fbdbbcce62d",
