#!/usr/bin/runhugs
-- created on 2009-01-21
--does simple HTML escaping on a main body text

import System.Environment(getArgs)
import Data.List(groupBy)

flatmap f = concat . map f

toHtml = flatmap code where
   code '&' = "&amp;"
   code '<' = "&lt;"
   code '>' = "&gt;"
   code c   = [c]

allnb = flatmap (\' ' -> "&nbsp;")

multinb = flatmap inter . groupBy (==) where
    inter = \w -> case w of
                      (' ':' ':_) -> allnb w
                      _           -> w

eachLine s = allnb i ++ multinb l where
    (i,l) = span (==' ') s

tr = unlines . map eachLine . lines . toHtml where

trf fi fo = do
    i <- readFile fi
    writeFile fo (tr i)

main = do
    args <- getArgs
    case args of
        [i@(_:_),o@(_:_)] -> trf i o
        otherwise         -> fail "params: inputfile outputfile"
