module PrintDFA ()
where
import PP
import Auxfuns
import DFA
import qualified Text.PrettyPrint.HughesPJ as PP
import Text.PrettyPrint.HughesPJ(Doc,text,char,int,(<>),(<+>),($+$),($$),render,nest,vcat)
import Graphviz


instance (PP q, PP s) => PP (DFA q s)
   where pp (DFA { states = q,
                   symbols = sigma,
                   delta = d,
                   start = q0,
                   final = f}) 
             = text "DFA" $$ nest 5 (vcat [text "Q"     $$ (nest 7 $ set q),
                                           text "Sigma" $$ (nest 7 $ set sigma),
                                           text "Delta" $$ (nest 7 $ graph q sigma d),
                                           text "q0"    $$ (nest 7 $ pp q0),
                                           text "F"     $$ (nest 7 $ set f)
                                          ])

graph q sigma d = vcat [ (pp p) <+> (pp a) <+> text "->" <+> (pp (d p a)) | p <- q, a <- sigma]

instance (PP q, PP s) => Show (DFA q s)
  where show = render . pp

------------------------------------------------
-- class instance for graphviz drawing.
-- e.g.    pnG ma      opens a window with a picture of ma

instance (Ord q,Show q,Show s) => Graph (DFA q s) where
  nodes t = map f pairs
    where pairs = zip (states t) [0..] 
          f (q,n) = (n,show q,stateColor t q)
          stateColor t q | q == (start t)   = Green
	  stateColor t q | elem q (final t) = Red
	  stateColor t q                    = None
	                            
 

  edges t = [(n,locate q1 s,show s,None) | (q1,n) <- pairs, s <- symbols t]
    where pairs = zip (states t) [0..]
          find q = case lookup q pairs of { Just n -> n}
          locate q1 s = case lookup ((delta t q1 s)) pairs of
                          Just n -> n
                          Nothing -> error("Bad "++show q1++" "++show s++" "++show (delta t q1 s)++"\n  "++show pairs)


  
  