module MyParserSpec where

import Regexp
import HXML
import Char

--(=~) :: String -> String -> String
matchRe s re = wholeMatch( searchS re [] s)
			      
isToken[] = []
isToken s = matchRe s "[#]?[a-zA-Z0-9]*|[#]?['][a-zA-Z0-9\\s\\.]*[']|[&][a-zA-Z0-9\\+\\s\\.\\(\\)\\,\\->\\:\\=\\+\\-\\/\\<\\>\\$\\[\\]\\*\\']*[&]|\\(|\\)|,|\\->|\\:"  
	

tokenList xs 
	|(isToken xs)/=[] = (isToken xs):(tokenList (drop (length (isToken xs)) xs))
	|xs==[]           = []
	|otherwise        = []


isVar ('#':x:xs) = isUpper x
isVar (x:xs) = isUpper x
isVar (_) = False

isText ('#':x:xs) = (x==''')
isText (x:xs) =  (x==''')
isText (_) = False

isTag ('#':x:xs) = isLower x
isTag (x:xs) = isLower x
isTag (_) = False

isError token = (token=="error")

obtBeforep op cp before [] = before
obtBeforep op cp before (x:xs) | x=="(" = obtBeforep (op+1) cp (before++[x]) xs
			       | x==")" = obtBeforep op (cp+1) (before++[x]) xs
			       | ((op == cp) && (op/=0)) || ((op == 0) && (cp>0)) = before
			       |otherwise = obtBeforep op cp (before++[x]) xs
obtAfterp op cp before [] = []
obtAfterp op cp before (x:xs) | x=="(" = obtAfterp (op+1) cp (before++[x]) xs
			      | x==")" = obtAfterp op (cp+1) (before++[x]) xs
			      | ((op == cp) && (op/=0)) || ((op == 0) && (cp>0)) = (x:xs)
			      |otherwise = obtAfterp op cp (before++[x]) xs


calcParts [] = []
calcParts tklist = bef:(calcParts (drop ((length bef)+1) tklist))	
		where
		bef = (obtBeforep 0 0 [] tklist)
   

tk2Xml tklist 
	|(null tklist) = []
	|isError(head tklist) = if (null(tail tklist)) 
				then [Tree (ELNode "error" []) []]
				else [Tree (ELNode "error" []) (expresionError (tail (tail tklist)))]  
	|isTag(head tklist) && ((head (tail tklist))=="(") && ((head (tail (tail tklist)))==")") = [Tree (ELNode (head tklist) []) []]
	|isTag(head tklist) = [Tree (ELNode (head tklist) []) (concat (map tk2Xml (calcParts (tail (tail tklist)))))]
	|(head tklist) == "(" = tk2Xml (tail tklist)
	|otherwise = [Tree (TXNode (head tklist)) []]



expresionError tklist = if (elem "," tklist)
			then (Tree (TXNode (concat before)) []):(expresionError after)
			else [Tree (TXNode (concat tklist)) []]
			   where
				(before,_:after) = break (==",") tklist

skipRT (Tree RTNode listTree) = (head listTree)

specPairs []=error("Error in SpecPairs: empty tokenlist")
specPairs tklist = ((head(tk2Xml before)),(head(tk2Xml after)))
			 where (before,_:after) = break (=="->") tklist  
