module PrintNFA
where
import PP
import NFA
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 (NFA q s)
   where pp (NFA { states = q,
                   symbols = sigma,
                   delta = d,
                   start = q0,
                   final = f}) 
             = text "NFA" $$ 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 "->" <+> (set (d p a)) | p <- q, a <- sigma]

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

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

instance (Eq q,Show q,Show s) => Graph (NFA 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,m,show s,None) 
            | (q1,n) <- pairs
            , s <- symbols t
            , m <- locate q1 s ]
    where pairs = zip (states t) [0..]
          find q = case lookup q pairs of {Just n -> n}
          locate q1 s = map find (delta t q1 s)  

