module Converter where
convertToMd :: String -> String
convertToMd = unlines . convert' "" . lines
where
convert' :: String -> [String] -> [String]
convert' prev []
| isFirstOO prev "<>" = ["```"]
| otherwise = []
convert' prev (h:t)
| not (isFirstOO prev "<>") &&
isFirstOO h "<>" = (if prev == "" then [] else [""]) ++ ["```haskell", drop 2 h] ++ rest
| isFirstOO h "<>" = (drop 2 h):rest
| isFirstOO prev "<>" = ["```"] ++ (if h == "" then [] else [""]) ++ [h] ++ rest
| otherwise = h:rest
where
rest = convert' h t
convertToLhs :: String -> String
convertToLhs = unlines . convert' False False "" . lines
where
convert' :: Bool -> Bool -> String -> [String] -> [String]
convert' inCode inSample prev [] = []
convert' inCode inSample prev (h:t)
| inCode && h /= "```" = ["> " ++ h] ++ (convert' True False h t)
| inSample && h /= "```" = ["< " ++ h] ++ (convert' False True h t)
| headingN h /= 0 = [headingO h ++ (tail $ dropWhile (=='#') h) ++ headingC h] ++ rest
| h == "```haskell" = (if prev == "" then [] else [""]) ++ convert' True False prev t
| (inCode || inSample) && h == "```" = (if length t > 0 && (head t) == "" then [] else [""]) ++ convert' False False prev t
| take 3 h == "```" = (if prev == "" then [] else [""]) ++ convert' False True prev t
| isFirstOO h ">" = ["NOTE: " ++ drop 2 h] ++ rest
| otherwise = h:rest
where
headingO h = "<h" ++ show (headingN h) ++ ">"
headingC h = "</h" ++ show (headingN h) ++ ">"
headingN h = length $ takeWhile (=='#') h
rest = convert' False False h t
isFirstOO :: String -> [Char] -> Bool
isFirstOO l e = or $ map (isFirst l) e
isFirst :: String -> Char -> Bool
isFirst [] _ = False
isFirst (h:' ':_) a = a == h
isFirst (h:_) a = False