-- http://www.codewars.com/kata/537e18b6147aa838f600001b
module TextAlignJustify where

import Data.List

justify :: String -> Int -> String
justify text width = (intercalate "\n" . reverse) (mh:mt) where
  (wh:wt) = words text
  (lh:lt) = foldl f [(0, length wh, [wh])] wt
  f vs@((n, l, vh):vt) v
    | n + l + 1 + length v <= width = (n + 1, l + length v, v:vh) : vt
    | otherwise                     = (0, length v, [v]) : vs
  mh = (unwords . reverse . \(_,_,a) -> a) lh
  mt = map g lt
  g (0, _, vh:_) = vh
  g (n, l, vs) = intercalate spaceQ $ intercalate (' ':spaceQ) vs' : vs'' where
    (q, r) = (width - l) `quotRem` n
    (vs', vs'') = splitAt (r + 1) (reverse vs)
    spaceQ  = replicate q ' '
