module Main where

import ParsecTree
import Data.Attoparsec.Text
import Data.Text
import Control.Applicative
import System.IO
import System.Environment


main = do
  args <- getArgs
  let parser = setup args
  loop stdin parser

setup (expr : []) = case parser of Right p -> p
                                   Left msg -> error msg
                        where x = parseOnly ((skipSpace *> ptreeParser <* skipSpace) <* endOfInput) (pack expr)
                              ptree = case x of Left e -> error $ show e
                                                Right t -> t
                              parser = (buildParser predefinedParsers ptree)
setup _ = error usage

usage = "USAGE: pgrep [PARSER]"

loop h p = do
        isEof <- hIsEOF h
        let f ln = do
                   case (parseOnly p (pack ln)) of Left _ -> return ()
                                                   Right res -> putStrLn res
                   loop h p
        if isEof then return () else (hGetLine h) >>= f
