module Main(main) where

import Debug.Trace
import Data.Maybe
import Text.ParserCombinators.Parsec
import Text.Parsec.Prim (ParsecT)
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language (emptyDef)

data PrmTopBlock = AtomNames [String]
                 deriving (Show, Eq)

countBetween m n p = do xs <- count m p
                        ys <- count (n - m) $ option Nothing $ do
                                y <- p
                                return (Just y)
                        return (xs ++ catMaybes ys)

restLine = do a <- many (noneOf "\n")
              eol
              return a

eol = do skipMany $ char ' '
         char '\n'

natural = P.integer $ P.makeTokenParser emptyDef

float = do sign <- option 1 (do s <- oneOf "+- "
                                return $ if s == '-' then -1 else 1)
           x <- P.float $ P.makeTokenParser emptyDef
           return $ sign * x

flagDecl x = do string $ "%FLAG " ++ x
                eol

formatDecl = do string "%FORMAT("
                count <- many1 digit
                format <- letter
                length <- many1 digit
                char ')'
                eol
                return (count, format, length)

-- |Multiple lines of lists of a given item
linesOf item = do ls <- many1 $ try (do lookAhead (noneOf "%")
                                        l <- many1 item
                                        eol
                                        return $ trace (show l) l)
                  return $ concat ls

atomNameBlock = do flagDecl "ATOM_NAME"
                   formatDecl
                   atomNames <- linesOf atomName
                   return $ AtomNames atomNames
                where
                atomName = do spaces
                              name <- countBetween 1 4 (alphaNum <|> oneOf "\'+-") <?> "atom name"
                              return name

ignoredBlock = do string "%FLAG" <?> "ignored block flag"
                  restLine
                  formatDecl
                  skipMany (noneOf "%" >> restLine)

hello = do ignoredBlock
           ignoredBlock
           atomNameBlock

parsePrmTopFile input = parse hello "(unknown)" input

test = do a <- readFile "test.prmtop"
          print $ parsePrmTopFile a

main = test
