diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -23,10 +23,6 @@
 [lpdf]: http://lierdakil.github.io/pandoc-crossref/output-listings.pdf
 
 
-Tested with Pandoc 1.16.0.
-
-**NOTE**: pandoc-crossref versions 0.2.0 and up only support pandoc v1.16. You can still file issues with older versions, but please don't expect more than an occasional bugfix. Thank you for understanding.
-
 This work is inspired by [pandoc-fignos][1] and [pandoc-eqnos][2] by @tomduck.
 
 [1]: https://github.com/tomduck/pandoc-fignos
@@ -48,6 +44,18 @@
 pandoc -F pandoc-crossref -F pandoc-citeproc file.md -o file.html
 ```
 
+### Note on leading/trailing spaces in metadata options
+
+Leading and trailing spaces in YAML metadata will most likely be stripped by either YAML parser or Pandoc itself. If you need leading and/or trailing spaces in pandoc-crossref metadata variables, use html entity for space instead, i.e. `&#32;`. For example, if you want reference ranges to be delimited by a dash with spaces (e.g. `2 - 5`), include the following in YAML metadata:
+
+```yaml
+rangeDelim: '&#32;-&#32;'
+```
+
+or pass `-MrangeDelim='&#32;-&#32;'` to pandoc on command line.
+
+You can use other html entites of course, like `&nbsp;` etc.
+
 ## Syntax
 
 Syntax is loosely based on discussion in <https://github.com/jgm/pandoc/issues/813>
@@ -68,7 +76,7 @@
 
 It's possible to group figures as subfigures. Basic syntax is as follows:
 
-```
+```markdown
 <div id="fig:figureRef">
 ![subfigure 1 caption](image1.png){#fig:figureRefA}
 
@@ -80,11 +88,13 @@
 
 To sum up, subfigures are made with a div having a figure `id`. Contents of said div consist of several paragraphs. All but last paragraphs contain one subfigure each, with captions, images and (optionally) reference attributes. Last paragraph contains figure caption.
 
+If you put more than one figure in the paragraph, those will still be rendered, but Pandoc will omit subfigure caption in most outputs (but it will work as expected with LaTeX). You can use output-specific hacks to work around that, or use `subfigGrid` (see below).
+
 Output is customizable, with metadata fields. See [Customization](#customization) for more information.
 
 Default settings will produce the following equivalent Markdown from example above:
 
-```
+```markdown
 <div id="fig:figureRef" class="subfigures">
 
 ![a](image1.png){#fig:figureRefA}
@@ -101,6 +111,44 @@
 
 You can add `nocaption` class to an image to suppress subfigure caption altogether. Note that it will still be counted.
 
+##### Subfigure grid
+
+If you need to align subfigures in a grid, and using output format styles is not an option, you can use `subfigGrid` option. That will typeset subfigures inside a table.
+
+Rows are formed by different paragraphs, with each image in a separate column.
+
+Column widths will be taken from `width` attributes of corresponding images, e.g.
+
+```markdown
+<div id="fig:coolFig">
+![caption a](coolfiga.png){#fig:cfa width=30%}
+![caption b](coolfigb.png){#fig:cfb width=60%}
+![caption c](coolfigb.png){#fig:cfc width=10%}
+
+![caption d](coolfigd.png){#fig:cfd}
+![caption e](coolfige.png){#fig:cfe}
+![caption f](coolfigf.png){#fig:cff}
+
+Cool figure!
+</div>
+```
+
+will produce a table with columns of 30%, 60% and 10% respectively.
+
+Only first row of images is considered for table width computation, other rows are completely ignored.
+
+*Anything* except images is silently ignored. So any text, spaces, soft line breaks etc will silently disappear from output. That doesn't apply to caption paragraph, obviously.
+
+All images will have width attribute automatically set to `100%` in order to fill whole column.
+
+Specifying width in anything but `%` will throw an error.
+
+If width for some images in first row is not specified, those will span equally in the remaining space.
+
+If width isn't specified for any image in first row, those will span equally on 99% of page width (due to Pandoc otherwise omitting width attribute for table).
+
+This option is ignored with LaTeX output, but paragraph breaks should produce similar effect, so images should be typeset correctly. TL;DR you don't need `subfigGrid` enabled for it to work with LaTeX, but you can still enable it.
+
 ### Equation labels
 
 ```markdown
@@ -111,6 +159,10 @@
 
 Math block and label *can* be separated by one or more spaces.
 
+You can also number all display equations with `autoEqnLabels` metadata setting (see below). Note, however, that you won't be able to reference equations without explicit labels.
+
+Equations numbers will be typeset inside math with `\qquad` before them. If you want to use tables instead, use `tableEqns` option.  Depending on output format, tables might work better or worse than `\qquad`.
+
 ### Table labels
 
 ```markdown
@@ -276,6 +328,8 @@
 * `listings`: if True, generate code blocks for `listings` package. Only relevant for LaTeX output. `\usepackage{listings}` will be automatically added to `header-includes`. You need to specify `--listings` option as well.
 * `codeBlockCaptions`: if True, parse table-style code block captions.
 * `autoSectionLabels`, default `false`: Automatically prefix all section labels with `sec:`. Note that this messes with pandoc's automatic header references.
+* `autoEqnLabels`, default `false`: Automatically number all display equations (i.e. ones defined using `$$...$$`/`\[...\]`). Note that you won't be able to reference equations without explicit labels.
+* `tableEqns`, default `false`: Typeset equations and equation numbers in tables instead of embedding numbers into equations themselves. Depending on output format, this might work better or worse.
 
 #### Item title format
 
@@ -290,6 +344,7 @@
 
 * `ccsDelim`, default `,&nbsp;`: delimiter for collected subfigure captions. See [Subfigures](#subfigures) and [Templates](#templates)
 * `ccsLabelSep`, default `&nbsp;—&nbsp;`: delimiter used between subfigure label and subfigure caption in collected captions. See [Subfigures](#subfigures) and [Templates](#templates)
+* `subfigGrid`, default `false`. If true, typeset subfigures inside a table. Ignored with LaTeX output. See [Subfigures](#subfigures)
 
 #### List titles
 
diff --git a/lib/Text/Pandoc/CrossRef/References/Blocks.hs b/lib/Text/Pandoc/CrossRef/References/Blocks.hs
--- a/lib/Text/Pandoc/CrossRef/References/Blocks.hs
+++ b/lib/Text/Pandoc/CrossRef/References/Blocks.hs
@@ -22,21 +22,19 @@
 import Prelude
 import Data.Default
 
-replaceAll :: Data a => Options -> a -> WS a
+replaceAll :: (Data a) => Options -> a -> WS a
 replaceAll opts =
-    everywhereMBut' (mkQ False isSubfig `extQ` isSubfig') (mkM (replaceBlocks opts) `extM` replaceInlines opts)
-  . everywhere' (mkT divBlocks `extT` spanInlines)
+    runReplace (mkM (replaceBlock opts) `extM` replaceInline opts)
+  . runSplitMath
+  . everywhere (mkT divBlocks `extT` spanInlines opts)
   where
-    isSubfig (Div (label,cls,_) _)
-      | "fig:" `isPrefixOf` label = True
-      | "crossref-stop" `elem` cls = True
-    isSubfig _ = False
-    isSubfig' (Span (_,cls,_) _)
-      | "crossref-stop" `elem` cls = True
-    isSubfig' _ = False
+    runSplitMath | tableEqns opts
+                 , not $ isFormat "latex" (outFormat opts)
+                 = everywhere (mkT splitMath)
+                 | otherwise = id
 
-replaceBlocks :: Options -> Block -> WS Block
-replaceBlocks opts (Header n (label, cls, attrs) text')
+replaceBlock :: Options -> Block -> WS Block
+replaceBlock opts (Header n (label, cls, attrs) text')
   = do
     let label' = if autoSectionLabels opts && not ("sec:" `isPrefixOf` label)
                  then "sec:"++label
@@ -50,20 +48,28 @@
                 | ln == n = inc cc
                 | otherwise = cc ++ take (n-ln-1) (zip [1,1..] $ repeat Nothing) ++ [(1,cl)]
         in cc'
-      when ("sec:" `isPrefixOf` label') $ replaceAttrSec label' text' secRefs
+      when ("sec:" `isPrefixOf` label') $ do
+        index  <- get curChap
+        modify secRefs $ M.insert label' RefRec {
+          refIndex=index
+        , refTitle=normalizeSpaces text'
+        , refSubfigure = Nothing
+        }
+        return ()
     return $ Header n (label', cls, attrs) text'
 -- subfigures
-replaceBlocks opts (Div (label,cls,attrs) images)
+replaceBlock opts (Div (label,cls,attrs) images)
   | "fig:" `isPrefixOf` label
   , Para caption <- last images
   = do
-    idxStr <- replaceAttr opts label (lookup "label" attrs) caption imgRefs
-    let (cont, st) = runState (replaceAll opts' $ init images) (subFig ^= True $ def)
+    idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) caption imgRefs
+    let (cont, st) = runState (runReplace (mkM $ replaceSubfigs opts') $ init images) def
         collectedCaptions =
             intercalate (ccsDelim opts)
-          $ map snd
+          $ map (collectCaps . snd)
+          $ sortOn (refIndex . snd)
+          $ filter (not . null . refTitle . snd)
           $ M.toList
-          $ M.map collectCaps
           $ imgRefs_ st
         collectCaps v =
               applyTemplate
@@ -84,31 +90,64 @@
           $ imgRefs_ st)
     case outFormat opts of
           f | isFormat "latex" f ->
-            return $ Div stopAttr $
+            return $ Div nullAttr $
               [ RawBlock (Format "tex") "\\begin{figure}" ]
               ++ cont ++
               [ Para [RawInline (Format "tex") "\\caption"
-                       , Span stopAttr caption]
+                       , Span nullAttr caption]
               , RawBlock (Format "tex") $ mkLaTeXLabel label
               , RawBlock (Format "tex") "\\end{figure}"]
-          _  -> return $ Div (label, "subfigures":cls, attrs) $ cont ++ [Para capt]
+          _  -> return $ Div (label, "subfigures":cls, attrs) $ toTable cont capt
   where
     opts' = opts
               { figureTemplate = subfigureChildTemplate opts
               , customLabel = \r i -> customLabel opts ("sub"++r) i
               }
-replaceBlocks opts (Div (label,_,attrs) [Table title align widths header cells])
+    toTable :: [Block] -> [Inline] -> [Block]
+    toTable blks capt
+      | subfigGrid opts = [Table [] align widths [] $ map blkToRow blks, Para capt]
+      | otherwise = blks ++ [Para capt]
+      where
+        align | Para ils:_ <- blks = replicate (length $ mapMaybe getWidth ils) AlignCenter
+              | otherwise = error "Misformatted subfigures block"
+        widths | Para ils:_ <- blks
+               = fixZeros $ mapMaybe getWidth ils
+               | otherwise = error "Misformatted subfigures block"
+        getWidth (Image (_id, _class, as) _ _)
+          = Just $ maybe 0 percToDouble $ lookup "width" as
+        getWidth _ = Nothing
+        fixZeros :: [Double] -> [Double]
+        fixZeros ws
+          = let nz = length $ filter (== 0) ws
+                rzw = (0.99 - sum ws) / fromIntegral nz
+            in if nz>0
+               then map (\x -> if x == 0 then rzw else x) ws
+               else ws
+        percToDouble :: String -> Double
+        percToDouble percs
+          | '%' <- last percs
+          , perc <- read $ init percs
+          = perc/100.0
+          | otherwise = error "Only percent allowed in subfigure width!"
+        blkToRow :: Block -> [[Block]]
+        blkToRow (Para inls) = mapMaybe inlToCell inls
+        blkToRow x = [[x]]
+        inlToCell :: Inline -> Maybe [Block]
+        inlToCell (Image (id', cs, as) txt tgt)  = Just [Para [Image (id', cs, setW as) txt tgt]]
+        inlToCell _ = Nothing
+        setW as = ("width", "100%"):filter ((/="width") . fst) as
+replaceBlock opts (Div (label,_,attrs) [Table title align widths header cells])
   | not $ null title
   , "tbl:" `isPrefixOf` label
   = do
-    idxStr <- replaceAttr opts label (lookup "label" attrs) title tblRefs
+    idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) title tblRefs
     let title' =
           case outFormat opts of
               f | isFormat "latex" f ->
                 RawInline (Format "tex") (mkLaTeXLabel label) : title
               _  -> applyTemplate idxStr title $ tableTemplate opts
     return $ Table title' align widths header cells
-replaceBlocks opts cb@(CodeBlock (label, classes, attrs) code)
+replaceBlock opts cb@(CodeBlock (label, classes, attrs) code)
   | not $ null label
   , "lst:" `isPrefixOf` label
   , Just caption <- lookup "caption" attrs
@@ -118,7 +157,7 @@
         | isFormat "latex" f, listings opts -> return cb
         --if not using listings, however, wrap it in a codelisting environment
         | isFormat "latex" f ->
-          return $ Div stopAttr [
+          return $ Div nullAttr [
               RawBlock (Format "tex")
                 $ "\\begin{codelisting}\n\\caption{"++caption++"}"
             , cb
@@ -126,13 +165,13 @@
             ]
       _ -> do
         let cap = toList $ text caption
-        idxStr <- replaceAttr opts label (lookup "label" attrs) cap lstRefs
+        idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) cap lstRefs
         let caption' = applyTemplate idxStr cap $ listingTemplate opts
         return $ Div (label, "listing":classes, []) [
             Para caption'
           , CodeBlock ([], classes, attrs \\ [("caption", caption)]) code
           ]
-replaceBlocks opts
+replaceBlock opts
   (Div (label,"listing":_, [])
     [Para caption, CodeBlock ([],classes,attrs) code])
   | not $ null label
@@ -144,67 +183,80 @@
           return $ CodeBlock (label,classes,("caption",stringify caption):attrs) code
         --if not using listings, however, wrap it in a codelisting environment
         | isFormat "latex" f ->
-          return $ Div stopAttr [
+          return $ Div nullAttr [
               RawBlock (Format "tex") "\\begin{codelisting}"
             , Para [
                 RawInline (Format "tex") "\\caption"
-              , Span stopAttr caption
+              , Span nullAttr caption
               ]
             , CodeBlock (label,classes,attrs) code
             , RawBlock (Format "tex") "\\end{codelisting}"
             ]
       _ -> do
-        idxStr <- replaceAttr opts label (lookup "label" attrs) caption lstRefs
+        idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) caption lstRefs
         let caption' = applyTemplate idxStr caption $ listingTemplate opts
         return $ Div (label, "listing":classes, []) [
             Para caption'
           , CodeBlock ([], classes, attrs) code
           ]
-replaceBlocks opts (Para [Span (label, _, attrs) [Math DisplayMath eq]])
+replaceBlock opts (Para [Span attrs [Math DisplayMath eq]])
   | not $ isFormat "latex" (outFormat opts)
   , tableEqns opts
   = do
-    idxStr <- replaceAttr opts label (lookup "label" attrs) [] eqnRefs
-    return $ Table [] [AlignCenter, AlignRight] [0.9, 0.1] [] [[[Plain [Math DisplayMath eq]], [Plain [Math DisplayMath $ "(" ++ stringify idxStr ++ ")"]]]]
-replaceBlocks _ x = return x
+    (eq', idx) <- replaceEqn opts attrs eq
+    return $ Table [] [AlignCenter, AlignRight] [0.9, 0.09] [] [[[Plain [Math DisplayMath eq']], [Plain [Math DisplayMath $ "(" ++ idx ++ ")"]]]]
+replaceBlock _ x = return x
 
-replaceInlines :: Options -> Inline -> WS Inline
-replaceInlines opts (Span (label,_,attrs) [Math DisplayMath eq])
-  | "eq:" `isPrefixOf` label
+replaceEqn :: Options -> Attr -> String -> WS (String, String)
+replaceEqn opts (label, _, attrs) eq = do
+  let label' | null label = Left "eq"
+             | otherwise = Right label
+  idxStr <- replaceAttr opts label' (lookup "label" attrs) [] eqnRefs
+  let eq' | tableEqns opts = eq
+          | otherwise = eq++"\\qquad("++stringify idxStr++")"
+  return (eq', stringify idxStr)
+
+replaceInline :: Options -> Inline -> WS Inline
+replaceInline opts (Span attrs@(label,_,_) [Math DisplayMath eq])
+  | "eq:" `isPrefixOf` label || null label && autoEqnLabels opts
   = case outFormat opts of
       f | isFormat "latex" f ->
         let eqn = "\\begin{equation}"++eq++mkLaTeXLabel label++"\\end{equation}"
         in return $ RawInline (Format "tex") eqn
       _ -> do
-        idxStr <- replaceAttr opts label (lookup "label" attrs) [] eqnRefs
-        let eq' = eq++"\\qquad("++stringify idxStr++")"
+        (eq', _) <- replaceEqn opts attrs eq
         return $ Math DisplayMath eq'
-replaceInlines opts x@(Image attr@(label,cls,attrs) alt img@(src, tit))
-  | "fig:" `isPrefixOf` snd img
+replaceInline opts (Image attr@(label,_,attrs) alt img@(_, tit))
+  | "fig:" `isPrefixOf` label && "fig:" `isPrefixOf` tit
   = do
-    sf <- get subFig
-    if | sf -> do
-        let label' | "fig:" `isPrefixOf` label = label
-                   | otherwise  = "fig:" ++ label
-        idxStr <- replaceAttr opts label' (lookup "label" attrs) alt imgRefs
-        case outFormat opts of
-          f | isFormat "latex" f ->
-            return $ latexSubFigure x label
-          _  ->
-            let alt' = applyTemplate idxStr alt $ figureTemplate opts
-                tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit
-                     | otherwise = tit
-            in return $ Image (label, cls, attrs) alt' (src, tit')
-       | "fig:" `isPrefixOf` label -> do
-        idxStr <- replaceAttr opts label (lookup "label" attrs) alt imgRefs
-        let alt' = case outFormat opts of
-              f | isFormat "latex" f -> alt
-              _  -> applyTemplate idxStr alt $ figureTemplate opts
-        return $ Image attr alt' img
-       | otherwise ->
-        return x
-replaceInlines _ x = return x
+    idxStr <- replaceAttr opts (Right label) (lookup "label" attrs) alt imgRefs
+    let alt' = case outFormat opts of
+          f | isFormat "latex" f -> alt
+          _  -> applyTemplate idxStr alt $ figureTemplate opts
+    return $ Image attr alt' img
+replaceInline _ x = return x
 
+replaceSubfigs :: Options -> [Inline] -> WS [Inline]
+replaceSubfigs opts = fmap concat . mapM (replaceSubfig opts)
+
+replaceSubfig :: Options -> Inline -> WS [Inline]
+replaceSubfig opts x@(Image (label,cls,attrs) alt (src, tit))
+  = do
+      let label' | "fig:" `isPrefixOf` label = Right label
+                 | null label = Left "fig"
+                 | otherwise  = Right $ "fig:" ++ label
+      idxStr <- replaceAttr opts label' (lookup "label" attrs) alt imgRefs
+      case outFormat opts of
+        f | isFormat "latex" f ->
+          return $ latexSubFigure x label
+        _  ->
+          let alt' = applyTemplate idxStr alt $ figureTemplate opts
+              tit' | "nocaption" `elem` cls = fromMaybe tit $ stripPrefix "fig:" tit
+                   | "fig:" `isPrefixOf` tit = tit
+                   | otherwise = "fig:" ++ tit
+          in return [Image (label, cls, attrs) alt' (src, tit')]
+replaceSubfig _ x = return [x]
+
 divBlocks :: Block -> Block
 divBlocks (Table title align widths header cells)
   | not $ null title
@@ -212,12 +264,26 @@
   = Div (label,[],[]) [Table (init title) align widths header cells]
 divBlocks x = x
 
-spanInlines :: [Inline] -> [Inline]
-spanInlines (math@(Math DisplayMath _eq):ils)
+splitMath :: [Block] -> [Block]
+splitMath (Para ils:xs)
+  | length ils > 1 = map Para (split [] [] ils) ++ xs
+  where
+    split res acc [] = reverse (reverse acc : res)
+    split res acc (x@(Span _ [Math DisplayMath _]):ys) =
+      split ([x] : reverse (dropSpaces acc) : res)
+            [] (dropSpaces ys)
+    split res acc (y:ys) = split res (y:acc) ys
+    dropSpaces = dropWhile (\x -> x == Space || x == SoftBreak)
+splitMath xs = xs
+
+spanInlines :: Options -> [Inline] -> [Inline]
+spanInlines opts (math@(Math DisplayMath _eq):ils)
   | c:ils' <- dropWhile (==Space) ils
   , Just label <- getRefLabel "eq" [c]
   = Span (label,[],[]) [math]:ils'
-spanInlines x = x
+  | autoEqnLabels opts
+  = Span nullAttr [math]:ils
+spanInlines _ x = x
 
 getRefLabel :: String -> [Inline] -> Maybe String
 getRefLabel _ [] = Nothing
@@ -229,46 +295,39 @@
   = init `fmap` stripPrefix "{#" attr
 getRefLabel _ _ = Nothing
 
-replaceAttr :: Options -> String -> Maybe String -> [Inline] -> Accessor References RefMap -> WS [Inline]
+replaceAttr :: Options -> Either String String -> Maybe String -> [Inline] -> Accessor References RefMap -> WS [Inline]
 replaceAttr o label refLabel title prop
   = do
     chap  <- take (chaptersDepth o) `fmap` get curChap
     i     <- (1+) `fmap` (M.size . M.filter (ap ((&&) . (chap ==) . init . refIndex) (isNothing . refSubfigure)) <$> get prop)
-    let index = chap ++ [(i, refLabel <> customLabel o label i)]
-    modify prop $ M.insert label RefRec {
+    let index = chap ++ [(i, refLabel <> customLabel o label' i)]
+        label' = either (++ ':':show index) id label
+    hasLabel <- M.member label' <$> get prop
+    when hasLabel $
+      error $ "Duplicate label: " ++ label'
+    modify prop $ M.insert label' RefRec {
       refIndex= index
     , refTitle=normalizeSpaces title
     , refSubfigure = Nothing
     }
     return $ chapPrefix (chapDelim o) index
 
-replaceAttrSec :: String -> [Inline] -> Accessor References RefMap -> WS ()
-replaceAttrSec label title prop
-  = do
-    index  <- get curChap
-    modify prop $ M.insert label RefRec {
-      refIndex=index
-    , refTitle=normalizeSpaces title
-    , refSubfigure = Nothing
-    }
-    return ()
-
-latexSubFigure :: Inline -> String -> Inline
+latexSubFigure :: Inline -> String -> [Inline]
 latexSubFigure (Image (_, cls, attrs) alt (src, title)) label =
   let
     title' = fromMaybe title $ stripPrefix "fig:" title
     texlabel | null label = []
-             | otherwise = mkLaTeXLabel label
+             | otherwise = [RawInline (Format "tex") $ mkLaTeXLabel label]
     texalt | "nocaption" `elem` cls  = []
-           | otherwise =
-              [ RawInline (Format "tex") "["] ++ alt ++ [ RawInline (Format "tex") "]"]
+           | otherwise = concat
+              [ [ RawInline (Format "tex") "["]
+              , alt
+              , [ RawInline (Format "tex") "]"]
+              ]
     img = Image (label, cls, attrs) alt (src, title')
-  in Span stopAttr $
-      [ RawInline (Format "tex") "\\subfloat" ] ++ texalt ++
-      [ RawInline (Format "tex") "{" ] ++
-      [img] ++
-      [ RawInline (Format "tex") $ texlabel ++ "}"]
-latexSubFigure x _ = x
-
-stopAttr :: Attr
-stopAttr = ([], ["crossref-stop"], [])
+  in concat [
+      [ RawInline (Format "tex") "\\subfloat" ]
+      , texalt
+      , [Span nullAttr $ img:texlabel]
+      ]
+latexSubFigure x _ = [x]
diff --git a/lib/Text/Pandoc/CrossRef/References/Types.hs b/lib/Text/Pandoc/CrossRef/References/Types.hs
--- a/lib/Text/Pandoc/CrossRef/References/Types.hs
+++ b/lib/Text/Pandoc/CrossRef/References/Types.hs
@@ -23,14 +23,13 @@
                              , lstRefs_ :: RefMap
                              , secRefs_ :: RefMap
                              , curChap_ :: Index
-                             , subFig_  :: Bool
                              } deriving (Show, Eq)
 
 --state monad
 type WS a = State References a
 
 instance Default References where
-  def = References n n n n n [] False
+  def = References n n n n n []
     where n = M.empty
 
 deriveAccessors ''References
diff --git a/lib/Text/Pandoc/CrossRef/Util/Options.hs b/lib/Text/Pandoc/CrossRef/Util/Options.hs
--- a/lib/Text/Pandoc/CrossRef/Util/Options.hs
+++ b/lib/Text/Pandoc/CrossRef/Util/Options.hs
@@ -33,4 +33,6 @@
                        , ccsDelim :: [Inline]
                        , ccsLabelSep :: [Inline]
                        , tableEqns :: Bool
+                       , autoEqnLabels :: Bool
+                       , subfigGrid :: Bool
                        }
diff --git a/lib/Text/Pandoc/CrossRef/Util/PandocOrphans.hs b/lib/Text/Pandoc/CrossRef/Util/PandocOrphans.hs
new file mode 100644
--- /dev/null
+++ b/lib/Text/Pandoc/CrossRef/Util/PandocOrphans.hs
@@ -0,0 +1,8 @@
+{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+module Text.Pandoc.CrossRef.Util.PandocOrphans where
+
+import Text.Pandoc.Builder
+
+instance {-# OVERLAPPING #-} ToMetaValue String where
+  toMetaValue = MetaString
diff --git a/lib/Text/Pandoc/CrossRef/Util/Settings.hs b/lib/Text/Pandoc/CrossRef/Util/Settings.hs
--- a/lib/Text/Pandoc/CrossRef/Util/Settings.hs
+++ b/lib/Text/Pandoc/CrossRef/Util/Settings.hs
@@ -7,6 +7,7 @@
 
 import Text.Pandoc.CrossRef.Util.Settings.Gen
 import Text.Pandoc.CrossRef.Util.Meta
+import Text.Pandoc.CrossRef.Util.PandocOrphans()
 
 getSettings :: Meta -> IO Meta
 getSettings meta = do
@@ -18,17 +19,17 @@
 
 defaultMeta :: Meta
 defaultMeta =
-     cref (MetaBool False)
-  <> chapters (MetaBool False)
-  <> chaptersDepth (MetaString "1")
-  <> listings (MetaBool False)
-  <> codeBlockCaptions (MetaBool False)
-  <> autoSectionLabels (MetaBool False)
-  <> figLabels (MetaString "arabic")
-  <> eqnLabels (MetaString "arabic")
-  <> tblLabels (MetaString "arabic")
-  <> lstLabels (MetaString "arabic")
-  <> secLabels (MetaString "arabic")
+     cref False
+  <> chapters False
+  <> chaptersDepth "1"
+  <> listings False
+  <> codeBlockCaptions False
+  <> autoSectionLabels False
+  <> figLabels "arabic"
+  <> eqnLabels "arabic"
+  <> tblLabels "arabic"
+  <> lstLabels "arabic"
+  <> secLabels "arabic"
   <> figureTitle (str "Figure")
   <> tableTitle (str "Table")
   <> listingTitle (str "Listing")
@@ -51,13 +52,15 @@
   <> figureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t")
   <> tableTemplate (var "tableTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t")
   <> listingTemplate (var "listingTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t")
-  <> crossrefYaml (MetaString "pandoc-crossref.yaml")
-  <> chaptersDepth (MetaString "1")
+  <> crossrefYaml "pandoc-crossref.yaml"
+  <> chaptersDepth "1"
   <> subfigureChildTemplate (var "i")
   <> subfigureTemplate (var "figureTitle" <> space <> var "i" <> var "titleDelim" <> space <> var "t" <> str "." <> space <> var "ccs")
-  <> subfigLabels (MetaString "alpha a")
+  <> subfigLabels "alpha a"
   <> ccsDelim (str "," <> space)
   <> ccsLabelSep (space <> str "—" <> space)
   <> ccsTemplate (var "i" <> var "ccsLabelSep" <> var "t")
-  <> tableEqns (MetaBool False)
+  <> tableEqns False
+  <> autoEqnLabels False
+  <> subfigGrid False
   where var = displayMath
diff --git a/lib/Text/Pandoc/CrossRef/Util/Util.hs b/lib/Text/Pandoc/CrossRef/Util/Util.hs
--- a/lib/Text/Pandoc/CrossRef/Util/Util.hs
+++ b/lib/Text/Pandoc/CrossRef/Util/Util.hs
@@ -32,20 +32,17 @@
 chapPrefix :: [Inline] -> Index -> [Inline]
 chapPrefix delim index = intercalate delim (map (return . Str . uncurry (fromMaybe . show)) index)
 
--- | Monadic variation on everywhere'
-everywhereMBut' :: Monad m => GenericQ Bool -> GenericM m -> GenericM m
-
--- Top-down order is also reflected in order of do-actions
-everywhereMBut' q f x
-  | q x = f x
-  | otherwise = do
-    x' <- f x
-    if q x'
-    then return x'
-    else gmapM (everywhereMBut' q f) x'
+runReplace :: (Monad m) => GenericM m -> GenericM m
+runReplace f x = do
+  x' <- f x
+  if x' `geq` x
+  then gmapM (runReplace f) x'
+  else return x'
 
 mkLaTeXLabel :: String -> String
-mkLaTeXLabel l = "\\label{" ++ mkLaTeXLabel' l ++ "}"
+mkLaTeXLabel l
+ | null l = []
+ | otherwise = "\\label{" ++ mkLaTeXLabel' l ++ "}"
 
 mkLaTeXLabel' :: String -> String
 mkLaTeXLabel' l =
diff --git a/pandoc-crossref.cabal b/pandoc-crossref.cabal
--- a/pandoc-crossref.cabal
+++ b/pandoc-crossref.cabal
@@ -2,7 +2,7 @@
 -- documentation, see http://haskell.org/cabal/users-guide/
 
 name:                pandoc-crossref
-version:             0.2.2.1
+version:             0.2.3.0
 synopsis:            Pandoc filter for cross-references
 description:         pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them.
 license:             GPL-2
@@ -17,7 +17,22 @@
 cabal-version:       >=1.10
 data-files:          demo.md
 extra-source-files:  test/*.inc
+                     test/m2m/equations/*.md
+                     test/m2m/equations-auto/*.md
+                     test/m2m/equations-tables/*.md
+                     test/m2m/equations-tables-auto/*.md
+                     test/m2m/subfigures/*.md
+                     test/m2m/subfigures-grid/*.md
+                     test/m2m/subfigures-ccsDelim/*.md
+                     test/m2m/equations/*.tex
+                     test/m2m/equations-auto/*.tex
+                     test/m2m/equations-tables/*.tex
+                     test/m2m/equations-tables-auto/*.tex
+                     test/m2m/subfigures/*.tex
+                     test/m2m/subfigures-grid/*.tex
+                     test/m2m/subfigures-ccsDelim/*.tex
 
+
 source-repository head
   type: git
   location: https://github.com/lierdakil/pandoc-crossref
@@ -25,26 +40,27 @@
 source-repository this
   type: git
   location: https://github.com/lierdakil/pandoc-crossref
-  tag: v0.2.2.1
+  tag: v0.2.3.0
 
 library
   exposed-modules:     Text.Pandoc.CrossRef
   other-modules:       Text.Pandoc.CrossRef.References
-                     , Text.Pandoc.CrossRef.References.Blocks
-                     , Text.Pandoc.CrossRef.References.List
-                     , Text.Pandoc.CrossRef.References.Refs
-                     , Text.Pandoc.CrossRef.References.Types
-                     , Text.Pandoc.CrossRef.Util.Settings
-                     , Text.Pandoc.CrossRef.Util.Meta
-                     , Text.Pandoc.CrossRef.Util.Options
-                     , Text.Pandoc.CrossRef.Util.Template
-                     , Text.Pandoc.CrossRef.Util.Util
-                     , Text.Pandoc.CrossRef.Util.CustomLabels
-                     , Text.Pandoc.CrossRef.Util.CodeBlockCaptions
-                     , Text.Pandoc.CrossRef.Util.ModifyMeta
-                     , Text.Pandoc.CrossRef.Util.Settings.Gen
-                     , Text.Pandoc.CrossRef.Util.Settings.Template
-                     , Text.Pandoc.CrossRef.Util.Gap
+                       Text.Pandoc.CrossRef.References.Blocks
+                       Text.Pandoc.CrossRef.References.List
+                       Text.Pandoc.CrossRef.References.Refs
+                       Text.Pandoc.CrossRef.References.Types
+                       Text.Pandoc.CrossRef.Util.Settings
+                       Text.Pandoc.CrossRef.Util.Meta
+                       Text.Pandoc.CrossRef.Util.Options
+                       Text.Pandoc.CrossRef.Util.Template
+                       Text.Pandoc.CrossRef.Util.Util
+                       Text.Pandoc.CrossRef.Util.CustomLabels
+                       Text.Pandoc.CrossRef.Util.CodeBlockCaptions
+                       Text.Pandoc.CrossRef.Util.ModifyMeta
+                       Text.Pandoc.CrossRef.Util.Settings.Gen
+                       Text.Pandoc.CrossRef.Util.Settings.Template
+                       Text.Pandoc.CrossRef.Util.Gap
+                       Text.Pandoc.CrossRef.Util.PandocOrphans
   build-depends:       base >=4.2 && <5
                      , pandoc >= 1.17.1 && <1.18
                      , mtl >= 1.1 && <2.3
@@ -127,5 +143,19 @@
                 Text.Pandoc.CrossRef.Util.Settings.Template
                 Text.Pandoc.CrossRef.Util.Template
                 Text.Pandoc.CrossRef.Util.Util
+                Text.Pandoc.CrossRef.Util.PandocOrphans
+  Ghc-Options:  -rtsopts -Wall -fno-warn-unused-do-bind -threaded
+  Default-Language: Haskell2010
+
+Test-Suite test-integrative
+  Type:           exitcode-stdio-1.0
+  Main-Is:        test-integrative.hs
+  hs-source-dirs: test
+  Build-Depends:   base >=4.2 && <5
+                 , hspec
+                 , pandoc
+                 , filepath
+                 , directory
+                 , pandoc-crossref
   Ghc-Options:  -rtsopts -Wall -fno-warn-unused-do-bind -threaded
   Default-Language: Haskell2010
diff --git a/src/pandoc-crossref.hs b/src/pandoc-crossref.hs
--- a/src/pandoc-crossref.hs
+++ b/src/pandoc-crossref.hs
@@ -6,9 +6,4 @@
 main :: IO ()
 main = toJSONFilter go
   where
-    go fmt p@(Pandoc meta _) = runCrossRefIO meta fmt action p
-      where
-        action (Pandoc _ bs) = do
-          meta' <- crossRefMeta
-          bs' <- crossRefBlocks bs
-          return $ Pandoc meta' bs'
+    go fmt p@(Pandoc meta _) = runCrossRefIO meta fmt defaultCrossRefAction p
diff --git a/test/m2m/equations-auto/expect.md b/test/m2m/equations-auto/expect.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-auto/expect.md
@@ -0,0 +1,37 @@
+This is a test file with some referenced equations, line
+$$ this \qquad(1)$$
+
+Some equations might be inside of text, $$ for example \qquad(2)$$ this
+one.
+
+Some equations might be on start of paragraphs:
+
+$$ start \qquad(3)$$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate \qquad(4)$$
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+$$ this \qquad(5)$$
+
+Some equations might be inside of text, $$ for example \qquad(6)$$ this
+one.
+
+Some equations might be on start of paragraphs:
+
+$$ start \qquad(7)$$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate \qquad(8)$$
+
+Then they can be referenced:
+
+Individually eq. 5, eq. 6, eq. 7, eq. 8
+
+Or in groups eqns. 5, 6, 8
+
+Groups will be compacted eqns. 5-8
diff --git a/test/m2m/equations-auto/expect.tex b/test/m2m/equations-auto/expect.tex
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-auto/expect.tex
@@ -0,0 +1,39 @@
+This is a test file with some referenced equations, line
+\begin{equation} this \end{equation}
+
+Some equations might be inside of text,
+\begin{equation} for example \end{equation} this one.
+
+Some equations might be on start of paragraphs:
+
+\begin{equation} start \end{equation} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\begin{equation} separate \end{equation}
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+\begin{equation} this \label{eq:0}\end{equation}
+
+Some equations might be inside of text,
+\begin{equation} for example \label{eq:1}\end{equation} this one.
+
+Some equations might be on start of paragraphs:
+
+\begin{equation} start \label{eq:2}\end{equation} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\begin{equation} separate \label{eq:3}\end{equation}
+
+Then they can be referenced:
+
+Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2},
+eq.~\ref{eq:3}
+
+Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}
+
+Groups will be compacted
+eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2}
diff --git a/test/m2m/equations-auto/input.md b/test/m2m/equations-auto/input.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-auto/input.md
@@ -0,0 +1,37 @@
+---
+autoEqnLabels: true
+...
+
+This is a test file with some referenced equations, line $$ this $$
+
+Some equations might be inside of text, $$ for example $$ this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $$
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line $$ this $${#eq:0}
+
+Some equations might be inside of text, $$ for example $${#eq:1} this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $${#eq:2} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $${#eq:3}
+
+Then they can be referenced:
+
+Individually @eq:0, @eq:1, @eq:2, @eq:3
+
+Or in groups [@eq:0; @eq:1; @eq:3]
+
+Groups will be compacted [@eq:0; @eq:1; @eq:3; @eq:2]
diff --git a/test/m2m/equations-tables-auto/expect.md b/test/m2m/equations-tables-auto/expect.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-tables-auto/expect.md
@@ -0,0 +1,73 @@
+This is a test file with some referenced equations, line
+
+  ---------------------------------------------------------------- ------
+                             $$ this $$                            $$(1)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+Some equations might be inside of text,
+
+  ---------------------------------------------------------------- ------
+                         $$ for example $$                         $$(2)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+this one.
+
+Some equations might be on start of paragraphs:
+
+  ---------------------------------------------------------------- ------
+                            $$ start $$                            $$(3)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+  ---------------------------------------------------------------- ------
+                           $$ separate $$                          $$(4)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+
+  ---------------------------------------------------------------- ------
+                             $$ this $$                            $$(5)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+Some equations might be inside of text,
+
+  ---------------------------------------------------------------- ------
+                         $$ for example $$                         $$(6)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+this one.
+
+Some equations might be on start of paragraphs:
+
+  ---------------------------------------------------------------- ------
+                            $$ start $$                            $$(7)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+  ---------------------------------------------------------------- ------
+                           $$ separate $$                          $$(8)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+Then they can be referenced:
+
+Individually eq. 5, eq. 6, eq. 7, eq. 8
+
+Or in groups eqns. 5, 6, 8
+
+Groups will be compacted eqns. 5-8
diff --git a/test/m2m/equations-tables-auto/expect.tex b/test/m2m/equations-tables-auto/expect.tex
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-tables-auto/expect.tex
@@ -0,0 +1,39 @@
+This is a test file with some referenced equations, line
+\begin{equation} this \end{equation}
+
+Some equations might be inside of text,
+\begin{equation} for example \end{equation} this one.
+
+Some equations might be on start of paragraphs:
+
+\begin{equation} start \end{equation} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\begin{equation} separate \end{equation}
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+\begin{equation} this \label{eq:0}\end{equation}
+
+Some equations might be inside of text,
+\begin{equation} for example \label{eq:1}\end{equation} this one.
+
+Some equations might be on start of paragraphs:
+
+\begin{equation} start \label{eq:2}\end{equation} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\begin{equation} separate \label{eq:3}\end{equation}
+
+Then they can be referenced:
+
+Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2},
+eq.~\ref{eq:3}
+
+Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}
+
+Groups will be compacted
+eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2}
diff --git a/test/m2m/equations-tables-auto/input.md b/test/m2m/equations-tables-auto/input.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-tables-auto/input.md
@@ -0,0 +1,38 @@
+---
+tableEqns: true
+autoEqnLabels: true
+...
+
+This is a test file with some referenced equations, line $$ this $$
+
+Some equations might be inside of text, $$ for example $$ this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $$
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line $$ this $${#eq:0}
+
+Some equations might be inside of text, $$ for example $${#eq:1} this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $${#eq:2} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $${#eq:3}
+
+Then they can be referenced:
+
+Individually @eq:0, @eq:1, @eq:2, @eq:3
+
+Or in groups [@eq:0; @eq:1; @eq:3]
+
+Groups will be compacted [@eq:0; @eq:1; @eq:3; @eq:2]
diff --git a/test/m2m/equations-tables/expect.md b/test/m2m/equations-tables/expect.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-tables/expect.md
@@ -0,0 +1,53 @@
+This is a test file with some referenced equations, line $$ this $$
+
+Some equations might be inside of text, $$ for example $$ this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $$
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+
+  ---------------------------------------------------------------- ------
+                             $$ this $$                            $$(1)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+Some equations might be inside of text,
+
+  ---------------------------------------------------------------- ------
+                         $$ for example $$                         $$(2)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+this one.
+
+Some equations might be on start of paragraphs:
+
+  ---------------------------------------------------------------- ------
+                            $$ start $$                            $$(3)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+  ---------------------------------------------------------------- ------
+                           $$ separate $$                          $$(4)$
+                                                                        $
+  ---------------------------------------------------------------- ------
+
+Then they can be referenced:
+
+Individually eq. 1, eq. 2, eq. 3, eq. 4
+
+Or in groups eqns. 1, 2, 4
+
+Groups will be compacted eqns. 1-4
diff --git a/test/m2m/equations-tables/expect.tex b/test/m2m/equations-tables/expect.tex
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-tables/expect.tex
@@ -0,0 +1,37 @@
+This is a test file with some referenced equations, line \[ this \]
+
+Some equations might be inside of text, \[ for example \] this one.
+
+Some equations might be on start of paragraphs:
+
+\[ start \] of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\[ separate \]
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+\begin{equation} this \label{eq:0}\end{equation}
+
+Some equations might be inside of text,
+\begin{equation} for example \label{eq:1}\end{equation} this one.
+
+Some equations might be on start of paragraphs:
+
+\begin{equation} start \label{eq:2}\end{equation} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\begin{equation} separate \label{eq:3}\end{equation}
+
+Then they can be referenced:
+
+Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2},
+eq.~\ref{eq:3}
+
+Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}
+
+Groups will be compacted
+eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2}
diff --git a/test/m2m/equations-tables/input.md b/test/m2m/equations-tables/input.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations-tables/input.md
@@ -0,0 +1,37 @@
+---
+tableEqns: true
+...
+
+This is a test file with some referenced equations, line $$ this $$
+
+Some equations might be inside of text, $$ for example $$ this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $$
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line $$ this $${#eq:0}
+
+Some equations might be inside of text, $$ for example $${#eq:1} this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $${#eq:2} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $${#eq:3}
+
+Then they can be referenced:
+
+Individually @eq:0, @eq:1, @eq:2, @eq:3
+
+Or in groups [@eq:0; @eq:1; @eq:3]
+
+Groups will be compacted [@eq:0; @eq:1; @eq:3; @eq:2]
diff --git a/test/m2m/equations/expect.md b/test/m2m/equations/expect.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations/expect.md
@@ -0,0 +1,35 @@
+This is a test file with some referenced equations, line $$ this $$
+
+Some equations might be inside of text, $$ for example $$ this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $$
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+$$ this \qquad(1)$$
+
+Some equations might be inside of text, $$ for example \qquad(2)$$ this
+one.
+
+Some equations might be on start of paragraphs:
+
+$$ start \qquad(3)$$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate \qquad(4)$$
+
+Then they can be referenced:
+
+Individually eq. 1, eq. 2, eq. 3, eq. 4
+
+Or in groups eqns. 1, 2, 4
+
+Groups will be compacted eqns. 1-4
diff --git a/test/m2m/equations/expect.tex b/test/m2m/equations/expect.tex
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations/expect.tex
@@ -0,0 +1,37 @@
+This is a test file with some referenced equations, line \[ this \]
+
+Some equations might be inside of text, \[ for example \] this one.
+
+Some equations might be on start of paragraphs:
+
+\[ start \] of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\[ separate \]
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line
+\begin{equation} this \label{eq:0}\end{equation}
+
+Some equations might be inside of text,
+\begin{equation} for example \label{eq:1}\end{equation} this one.
+
+Some equations might be on start of paragraphs:
+
+\begin{equation} start \label{eq:2}\end{equation} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+\begin{equation} separate \label{eq:3}\end{equation}
+
+Then they can be referenced:
+
+Individually eq.~\ref{eq:0}, eq.~\ref{eq:1}, eq.~\ref{eq:2},
+eq.~\ref{eq:3}
+
+Or in groups eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}
+
+Groups will be compacted
+eqns.~\ref{eq:0}, \ref{eq:1}, \ref{eq:3}, \ref{eq:2}
diff --git a/test/m2m/equations/input.md b/test/m2m/equations/input.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/equations/input.md
@@ -0,0 +1,33 @@
+This is a test file with some referenced equations, line $$ this $$
+
+Some equations might be inside of text, $$ for example $$ this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $$ of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $$
+
+Some of those can be labelled:
+
+This is a test file with some referenced equations, line $$ this $${#eq:0}
+
+Some equations might be inside of text, $$ for example $${#eq:1} this one.
+
+Some equations might be on start of paragraphs:
+
+$$ start $${#eq:2} of paragraph.
+
+Other might be on separate paragraphs of their own:
+
+$$ separate $${#eq:3}
+
+Then they can be referenced:
+
+Individually @eq:0, @eq:1, @eq:2, @eq:3
+
+Or in groups [@eq:0; @eq:1; @eq:3]
+
+Groups will be compacted [@eq:0; @eq:1; @eq:3; @eq:2]
diff --git a/test/m2m/subfigures-ccsDelim/expect.md b/test/m2m/subfigures-ccsDelim/expect.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures-ccsDelim/expect.md
@@ -0,0 +1,45 @@
+You can define subfigures:
+
+<div id="fig:subfigures" class="subfigures">
+
+![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2}
+![c](fig3.png "fig:")
+
+![d](fig4.png "fig:"){#fig:subfig4} ![e](fig5.png "fig:")
+![f](fig6.png "fig:"){#fig:subfig6}
+
+![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:")
+![i](fig9.png "fig:"){#fig:subfig9}
+
+Figure 1: Caption. a — 1; b — 2; c — 3; d — 4; e — 5; f — 6; g — 7; h —
+8; i — 9
+
+</div>
+
+<div id="fig:subfigures2" class="subfigures">
+
+![a](fig1.png){#fig:subfig21}
+
+![b](fig2.png){#fig:subfig22}
+
+![c](fig3.png)
+
+![d](fig4.png){#fig:subfig24}
+
+![e](fig5.png)
+
+![f](fig6.png){#fig:subfig26}
+
+![g](fig7.png){#fig:subfig27}
+
+![h](fig8.png)
+
+![i](fig9.png){#fig:subfig29}
+
+Figure 2: Caption. a — 1; b — 2; c — 3; d — 4; e — 5; f — 6; g — 7; h —
+8; i — 9
+
+</div>
+
+Figures themselves can be referenced fig. 2, as well as individual
+subfigures: figs. 1 (a), 1 (b), 2 (i)
diff --git a/test/m2m/subfigures-ccsDelim/expect.tex b/test/m2m/subfigures-ccsDelim/expect.tex
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures-ccsDelim/expect.tex
@@ -0,0 +1,51 @@
+You can define subfigures:
+
+\begin{figure}
+
+\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig1}}
+\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig2}}
+\subfloat[3]{\includegraphics{fig3.png}}
+
+\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig4}}
+\subfloat[5]{\includegraphics{fig5.png}}
+\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig6}}
+
+\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig7}}
+\subfloat[8]{\includegraphics{fig8.png}}
+\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig9}}
+
+\caption{Caption}
+
+\label{fig:subfigures}
+
+\end{figure}
+
+\begin{figure}
+
+\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}}
+
+\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}}
+
+\subfloat[3]{\includegraphics{fig3.png}}
+
+\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}}
+
+\subfloat[5]{\includegraphics{fig5.png}}
+
+\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}}
+
+\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}}
+
+\subfloat[8]{\includegraphics{fig8.png}}
+
+\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}}
+
+\caption{Caption}
+
+\label{fig:subfigures2}
+
+\end{figure}
+
+Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well
+as individual subfigures:
+figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29}
diff --git a/test/m2m/subfigures-ccsDelim/input.md b/test/m2m/subfigures-ccsDelim/input.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures-ccsDelim/input.md
@@ -0,0 +1,45 @@
+---
+ccsDelim: ";&#32;"
+...
+
+You can define subfigures:
+
+<div id="fig:subfigures">
+  ![1](fig1.png){#fig:subfig1}
+  ![2](fig2.png){#fig:subfig2}
+  ![3](fig3.png)
+
+  ![4](fig4.png){#fig:subfig4}
+  ![5](fig5.png)
+  ![6](fig6.png){#fig:subfig6}
+
+  ![7](fig7.png){#fig:subfig7}
+  ![8](fig8.png)
+  ![9](fig9.png){#fig:subfig9}
+
+  Caption
+</div>
+
+<div id="fig:subfigures2">
+  ![1](fig1.png){#fig:subfig21}
+
+  ![2](fig2.png){#fig:subfig22}
+
+  ![3](fig3.png)
+
+  ![4](fig4.png){#fig:subfig24}
+
+  ![5](fig5.png)
+
+  ![6](fig6.png){#fig:subfig26}
+
+  ![7](fig7.png){#fig:subfig27}
+
+  ![8](fig8.png)
+
+  ![9](fig9.png){#fig:subfig29}
+
+  Caption
+</div>
+
+Figures themselves can be referenced @fig:subfigures2, as well as individual subfigures: [@fig:subfig1; @fig:subfig2; @fig:subfig29]
diff --git a/test/m2m/subfigures-grid/expect.md b/test/m2m/subfigures-grid/expect.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures-grid/expect.md
@@ -0,0 +1,52 @@
+You can define subfigures:
+
+<div id="fig:subfigures" class="subfigures">
+
++-----------------------+-----------------------+-----------------------+
+| ![a](fig1.png){#fig:s | ![b](fig2.png){#fig:s | ![c](fig3.png){width= |
+| ubfig1                | ubfig2                | "100%"}               |
+| width="100%"}         | width="100%"}         |                       |
++-----------------------+-----------------------+-----------------------+
+| ![d](fig4.png){#fig:s | ![e](fig5.png){width= | ![f](fig6.png){#fig:s |
+| ubfig4                | "100%"}               | ubfig6                |
+| width="100%"}         |                       | width="100%"}         |
++-----------------------+-----------------------+-----------------------+
+| ![g](fig7.png){#fig:s | ![h](fig8.png){width= | ![i](fig9.png){#fig:s |
+| ubfig7                | "100%"}               | ubfig9                |
+| width="100%"}         |                       | width="100%"}         |
++-----------------------+-----------------------+-----------------------+
+
+Figure 1: Caption. a — 1, b — 2, c — 3, d — 4, e — 5, f — 6, g — 7, h —
+8, i — 9
+
+</div>
+
+<div id="fig:subfigures2" class="subfigures">
+
++-------------------------------------------------------------------------+
+| ![a](fig1.png){#fig:subfig21 width="100%"}                              |
++-------------------------------------------------------------------------+
+| ![b](fig2.png){#fig:subfig22 width="100%"}                              |
++-------------------------------------------------------------------------+
+| ![c](fig3.png){width="100%"}                                            |
++-------------------------------------------------------------------------+
+| ![d](fig4.png){#fig:subfig24 width="100%"}                              |
++-------------------------------------------------------------------------+
+| ![e](fig5.png){width="100%"}                                            |
++-------------------------------------------------------------------------+
+| ![f](fig6.png){#fig:subfig26 width="100%"}                              |
++-------------------------------------------------------------------------+
+| ![g](fig7.png){#fig:subfig27 width="100%"}                              |
++-------------------------------------------------------------------------+
+| ![h](fig8.png){width="100%"}                                            |
++-------------------------------------------------------------------------+
+| ![i](fig9.png){#fig:subfig29 width="100%"}                              |
++-------------------------------------------------------------------------+
+
+Figure 2: Caption. a — 1, b — 2, c — 3, d — 4, e — 5, f — 6, g — 7, h —
+8, i — 9
+
+</div>
+
+Figures themselves can be referenced fig. 2, as well as individual
+subfigures: figs. 1 (a), 1 (b), 2 (i)
diff --git a/test/m2m/subfigures-grid/expect.tex b/test/m2m/subfigures-grid/expect.tex
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures-grid/expect.tex
@@ -0,0 +1,51 @@
+You can define subfigures:
+
+\begin{figure}
+
+\subfloat[1]{\includegraphics[width=0.30000\textwidth]{fig1.png}\label{fig:subfig1}}
+\subfloat[2]{\includegraphics[width=0.30000\textwidth]{fig2.png}\label{fig:subfig2}}
+\subfloat[3]{\includegraphics[width=0.30000\textwidth]{fig3.png}}
+
+\subfloat[4]{\includegraphics[width=0.30000\textwidth]{fig4.png}\label{fig:subfig4}}
+\subfloat[5]{\includegraphics[width=0.30000\textwidth]{fig5.png}}
+\subfloat[6]{\includegraphics[width=0.30000\textwidth]{fig6.png}\label{fig:subfig6}}
+
+\subfloat[7]{\includegraphics[width=0.30000\textwidth]{fig7.png}\label{fig:subfig7}}
+\subfloat[8]{\includegraphics[width=0.30000\textwidth]{fig8.png}}
+\subfloat[9]{\includegraphics[width=0.30000\textwidth]{fig9.png}\label{fig:subfig9}}
+
+\caption{Caption}
+
+\label{fig:subfigures}
+
+\end{figure}
+
+\begin{figure}
+
+\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}}
+
+\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}}
+
+\subfloat[3]{\includegraphics{fig3.png}}
+
+\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}}
+
+\subfloat[5]{\includegraphics{fig5.png}}
+
+\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}}
+
+\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}}
+
+\subfloat[8]{\includegraphics{fig8.png}}
+
+\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}}
+
+\caption{Caption}
+
+\label{fig:subfigures2}
+
+\end{figure}
+
+Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well
+as individual subfigures:
+figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29}
diff --git a/test/m2m/subfigures-grid/input.md b/test/m2m/subfigures-grid/input.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures-grid/input.md
@@ -0,0 +1,45 @@
+---
+subfigGrid: true
+...
+
+You can define subfigures:
+
+<div id="fig:subfigures">
+  ![1](fig1.png){#fig:subfig1 width=30%}
+  ![2](fig2.png){#fig:subfig2 width=30%}
+  ![3](fig3.png){width=30%}
+
+  ![4](fig4.png){#fig:subfig4 width=30%}
+  ![5](fig5.png){width=30%}
+  ![6](fig6.png){#fig:subfig6 width=30%}
+
+  ![7](fig7.png){#fig:subfig7 width=30%}
+  ![8](fig8.png){width=30%}
+  ![9](fig9.png){#fig:subfig9 width=30%}
+
+  Caption
+</div>
+
+<div id="fig:subfigures2">
+  ![1](fig1.png){#fig:subfig21}
+
+  ![2](fig2.png){#fig:subfig22}
+
+  ![3](fig3.png)
+
+  ![4](fig4.png){#fig:subfig24}
+
+  ![5](fig5.png)
+
+  ![6](fig6.png){#fig:subfig26}
+
+  ![7](fig7.png){#fig:subfig27}
+
+  ![8](fig8.png)
+
+  ![9](fig9.png){#fig:subfig29}
+
+  Caption
+</div>
+
+Figures themselves can be referenced @fig:subfigures2, as well as individual subfigures: [@fig:subfig1; @fig:subfig2; @fig:subfig29]
diff --git a/test/m2m/subfigures/expect.md b/test/m2m/subfigures/expect.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures/expect.md
@@ -0,0 +1,45 @@
+You can define subfigures:
+
+<div id="fig:subfigures" class="subfigures">
+
+![a](fig1.png "fig:"){#fig:subfig1} ![b](fig2.png "fig:"){#fig:subfig2}
+![c](fig3.png "fig:")
+
+![d](fig4.png "fig:"){#fig:subfig4} ![e](fig5.png "fig:")
+![f](fig6.png "fig:"){#fig:subfig6}
+
+![g](fig7.png "fig:"){#fig:subfig7} ![h](fig8.png "fig:")
+![i](fig9.png "fig:"){#fig:subfig9}
+
+Figure 1: Caption. a — 1, b — 2, c — 3, d — 4, e — 5, f — 6, g — 7, h —
+8, i — 9
+
+</div>
+
+<div id="fig:subfigures2" class="subfigures">
+
+![a](fig1.png){#fig:subfig21}
+
+![b](fig2.png){#fig:subfig22}
+
+![c](fig3.png)
+
+![d](fig4.png){#fig:subfig24}
+
+![e](fig5.png)
+
+![f](fig6.png){#fig:subfig26}
+
+![g](fig7.png){#fig:subfig27}
+
+![h](fig8.png)
+
+![i](fig9.png){#fig:subfig29}
+
+Figure 2: Caption. a — 1, b — 2, c — 3, d — 4, e — 5, f — 6, g — 7, h —
+8, i — 9
+
+</div>
+
+Figures themselves can be referenced fig. 2, as well as individual
+subfigures: figs. 1 (a), 1 (b), 2 (i)
diff --git a/test/m2m/subfigures/expect.tex b/test/m2m/subfigures/expect.tex
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures/expect.tex
@@ -0,0 +1,51 @@
+You can define subfigures:
+
+\begin{figure}
+
+\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig1}}
+\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig2}}
+\subfloat[3]{\includegraphics{fig3.png}}
+
+\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig4}}
+\subfloat[5]{\includegraphics{fig5.png}}
+\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig6}}
+
+\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig7}}
+\subfloat[8]{\includegraphics{fig8.png}}
+\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig9}}
+
+\caption{Caption}
+
+\label{fig:subfigures}
+
+\end{figure}
+
+\begin{figure}
+
+\subfloat[1]{\includegraphics{fig1.png}\label{fig:subfig21}}
+
+\subfloat[2]{\includegraphics{fig2.png}\label{fig:subfig22}}
+
+\subfloat[3]{\includegraphics{fig3.png}}
+
+\subfloat[4]{\includegraphics{fig4.png}\label{fig:subfig24}}
+
+\subfloat[5]{\includegraphics{fig5.png}}
+
+\subfloat[6]{\includegraphics{fig6.png}\label{fig:subfig26}}
+
+\subfloat[7]{\includegraphics{fig7.png}\label{fig:subfig27}}
+
+\subfloat[8]{\includegraphics{fig8.png}}
+
+\subfloat[9]{\includegraphics{fig9.png}\label{fig:subfig29}}
+
+\caption{Caption}
+
+\label{fig:subfigures2}
+
+\end{figure}
+
+Figures themselves can be referenced fig.~\ref{fig:subfigures2}, as well
+as individual subfigures:
+figs.~\ref{fig:subfig1}, \ref{fig:subfig2}, \ref{fig:subfig29}
diff --git a/test/m2m/subfigures/input.md b/test/m2m/subfigures/input.md
new file mode 100644
--- /dev/null
+++ b/test/m2m/subfigures/input.md
@@ -0,0 +1,41 @@
+You can define subfigures:
+
+<div id="fig:subfigures">
+  ![1](fig1.png){#fig:subfig1}
+  ![2](fig2.png){#fig:subfig2}
+  ![3](fig3.png)
+
+  ![4](fig4.png){#fig:subfig4}
+  ![5](fig5.png)
+  ![6](fig6.png){#fig:subfig6}
+
+  ![7](fig7.png){#fig:subfig7}
+  ![8](fig8.png)
+  ![9](fig9.png){#fig:subfig9}
+
+  Caption
+</div>
+
+<div id="fig:subfigures2">
+  ![1](fig1.png){#fig:subfig21}
+
+  ![2](fig2.png){#fig:subfig22}
+
+  ![3](fig3.png)
+
+  ![4](fig4.png){#fig:subfig24}
+
+  ![5](fig5.png)
+
+  ![6](fig6.png){#fig:subfig26}
+
+  ![7](fig7.png){#fig:subfig27}
+
+  ![8](fig8.png)
+
+  ![9](fig9.png){#fig:subfig29}
+
+  Caption
+</div>
+
+Figures themselves can be referenced @fig:subfigures2, as well as individual subfigures: [@fig:subfig1; @fig:subfig2; @fig:subfig29]
diff --git a/test/test-integrative.hs b/test/test-integrative.hs
new file mode 100644
--- /dev/null
+++ b/test/test-integrative.hs
@@ -0,0 +1,32 @@
+import Test.Hspec
+import Text.Pandoc
+import Text.Pandoc.CrossRef
+import System.FilePath
+import System.Directory
+import Control.Monad
+
+lines' :: String -> [(Integer, String)]
+lines' = zip [1..] . lines
+
+-- m2m :: Meta -> String -> String -> Expectation
+m2m :: String -> Spec
+m2m dir
+  | dir == "." = return ()
+  | dir == ".." = return ()
+  | otherwise =
+  describe dir $ do
+    input <- runIO $ readFile ("test" </> "m2m" </> dir </> "input.md")
+    expect_md <- runIO $ readFile ("test" </> "m2m" </> dir </> "expect.md")
+    expect_tex <- runIO $ readFile ("test" </> "m2m" </> dir </> "expect.tex")
+    p@(Pandoc meta _) <- either (fail . show) return $ readMarkdown def input
+    let actual_md = writeMarkdown def $ runCrossRef meta (Just $ Format "markdown") defaultCrossRefAction p
+        actual_tex = writeLaTeX def $ runCrossRef meta (Just $ Format "latex") defaultCrossRefAction p
+    it "Markdown" $ zipWithM_ shouldBe (lines' actual_md) (lines' expect_md)
+    it "LaTeX" $ zipWithM_ shouldBe (lines' actual_tex) (lines' expect_tex)
+
+main :: IO ()
+main = do
+  mds <- getDirectoryContents ("test" </> "m2m")
+  hspec $
+    describe "Integrative tests" $
+      mapM_ m2m mds
