-- vim: sw=2: ts=2: expandtab: autoindent:

-- module MemScript where
-- module Main where

import Prelude hiding ( print, putStr, putStrLn, getLine, readLn,
                        interact, getContents )
-- openBinaryFile, withBinaryFile, -- where do these come from other than UTF8?
import System.IO
import Codec.Binary.UTF8.String

import Data.List
import Control.Monad
import Data.Maybe
import System.Environment (getArgs)

import System.Console.Readline


main = do filenames <- getArgs
          if length filenames == 1
            -- then memScript (head filenames)
            then initialize >> memScriptReadLine (head filenames)
            else putStrLn "Usage: memscript <filename>"

memScriptReadLine filename = checkVersesByLine =<< getVersesFromFile filename

getVersesFromFile = liftM lines . getFileContents

getFileContents filename = hGetContents =<< openFile filename ReadMode


checkVersesByLine = checkVersesByLineWith (readlineUTF8withAddHistory "% ")


checkVersesByLineWith _        []            = return ()
checkVersesByLineWith readLine verses@(v:vs) =
  {-
  do mg <- readLine
     case mg of Just g  -> checkOneVerseAndContinue g
                Nothing -> handleEOF
  -}
  maybe handleEOF checkOneLineAndContinue =<< readLine
  where
  handleEOF = printDiff (concat $ intersperse "\n< " verses) ""
  checkOneLineAndContinue g
     | v == g    = checkVersesByLineWith readLine vs
     | otherwise = printDiff v g >> checkVersesByLineWith readLine verses


readlineUTF8withAddHistory prompt =
  do ms <- readline prompt
     whenJust addHistory ms
     return (liftM decodeString ms)

whenJust = maybe (return ())

showDiff v g = concat $ intersperse "\n" ["===",
                                          "< "++v,
                                          "---",
                                          "> "++g,
                                          "==="]

printDiff v g = putStrLn $ showDiff v g


{-
-- below is the version without readline which does not handle UTF8 strings

memScript filename =
  do hScript <- openFile filename ReadMode
     script <- hGetContents hScript
     input <- getContents
     let results = checkScript script input
     putResults results


putResults []                = return ()
putResults (Right _    : rs) = putResults rs
putResults (Left (v,g) : rs) = printDiff v g >> putResults rs

checkScript script input = checkVerses (lines script) (lines input)

checkVerses []            _              = []
checkVerses verses@(v:vs) guesses@(g:gs)
  | v == g    = Right ()   : checkVerses vs gs
  | otherwise = Left (v,g) : checkVerses verses gs
checkVerses verses        []             = [Left (concat $
                                                  intersperse "\n" verses,"")]

-}