visualization.ml 43.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
(*
 *  ENIAM: Categorial Syntactic-Semantic Parser for Polish
 *  Copyright (C) 2016 Wojciech Jaworski <wjaworski atSPAMfree mimuw dot edu dot pl>
 *  Copyright (C) 2016 Institute of Computer Science Polish Academy of Sciences
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *)

open LCGtypes
open Xstd
open Printf
open PreTypes

let string_of_interps interps =
      String.concat "|" (Xlist.map interps (fun interp ->
        (String.concat ":" (Xlist.map interp (fun interp2 ->
          (String.concat "." interp2))))))

let rec string_of_token = function
    PreTypes.SmallLetter orth -> sprintf "SmallLetter(%s)" orth
  | PreTypes.CapLetter(orth,lc) -> sprintf "CapLetter(%s,%s)" orth lc
  | PreTypes.AllSmall orth -> sprintf "AllSmall(%s)" orth
  | PreTypes.AllCap(orth,lc,lc2) -> sprintf "AllCap(%s,%s,%s)" orth lc lc2
  | PreTypes.FirstCap(orth,lc,cl,ll) -> sprintf "FirstCap(%s,%s,%s,%s)" orth lc cl ll
  | PreTypes.SomeCap orth -> sprintf "SomeCap(%s)" orth
  | PreTypes.RomanDig(v,t) -> sprintf "RomanDig(%s,%s)" v t
  | PreTypes.Interp orth -> sprintf "Interp(%s)" orth
  | PreTypes.Symbol orth  -> sprintf "Symbol(%s)" orth
  | PreTypes.Dig(v,t) -> sprintf "Dig(%s,%s)" v t
  | PreTypes.Other2 orth  -> sprintf "Other(%s)" orth
  | PreTypes.Lemma(lemma,cat,interps) -> sprintf "Lemma(%s,%s,%s)" lemma cat (string_of_interps interps)
  | PreTypes.Proper(lemma,cat,interps,senses) -> sprintf "Proper(%s,%s,%s,%s)" lemma cat (string_of_interps interps) (String.concat "|" senses)
  | PreTypes.Compound(sense,l) -> sprintf "Compound(%s,[%s])" sense (String.concat ";" (Xlist.map l string_of_token))
  | PreTypes.Tokens(cat,l) -> sprintf "Tokens(%s,%s)" cat (String.concat ";" (Xlist.map l string_of_int))

let rec spaces i =
  if i = 0 then "" else "  " ^ spaces (i-1)

let rec string_of_tokens i = function
    PreTypes.Token t -> sprintf "%s{orth=%s;beg=%d;len=%d;next=%d;token=%s;weight=%.2f;attrs=[%s];\n%s senses=[%s];\n%s valence=[%s];\n%s simple_valence=[%s];lroles=%s,%s}" (spaces i) t.PreTypes.orth t.PreTypes.beg t.PreTypes.len t.PreTypes.next (string_of_token t.PreTypes.token)
      t.PreTypes.weight (String.concat ";" t.PreTypes.attrs) (spaces i) (String.concat ";" (Xlist.map t.PreTypes.senses (fun (sense,hipero,weight) -> sprintf "%s[%s]%.2f" sense (String.concat "," hipero) weight)))
      (spaces i) (String.concat ";" (Xlist.map t.PreTypes.valence (WalStringOf.fnum_frame ""))) (spaces i) (String.concat ";" (Xlist.map t.PreTypes.simple_valence (WalStringOf.fnum_frame ""))) (fst t.lroles) (snd t.lroles)
  | PreTypes.Variant l -> sprintf "%sVariant[\n%s]" (spaces i) (String.concat ";\n" (Xlist.map l (string_of_tokens (i+1))))
  | PreTypes.Seq l -> sprintf "%sSeq[\n%s]" (spaces i) (String.concat ";\n" (Xlist.map l (string_of_tokens (i+1))))

let paths_to_string_indexed (paths,last,next_id) =
  String.concat "\n" (Xlist.map paths (fun (i,j,t) ->
    Printf.sprintf "%2d %2d %s" i j (string_of_tokens 0 (PreTypes.Token t))))
  ^ Printf.sprintf "\nlast=%d next_id=%d" last next_id

(*let string_of_token_record1 t =
  sprintf "{orth=%s;beg=%d;len=%d;next=%d;token=%s;id=%d;lnode=%d;rnode=%d;conll_id=%s;conll_super=%s;conll_label=%s;attrs=[%s]}"
    t.PreTypes.orth t.PreTypes.beg t.PreTypes.len t.PreTypes.next (string_of_token t.PreTypes.token)
    t.PreTypes.id t.PreTypes.lnode t.PreTypes.rnode t.PreTypes.conll_id t.PreTypes.conll_super t.PreTypes.conll_label
    (String.concat ";" t.PreTypes.attrs)
  (* sprintf "{orth=%s;beg=%d;len=%d;next=%d;token=%s}"
    t.PreTypes.orth t.PreTypes.beg t.PreTypes.len t.PreTypes.next (string_of_token t.PreTypes.token)  *)

let string_of_paths1 paths =
  String.concat "\n            " (Xlist.map paths string_of_token_record1)*)

let string_of_status = function
    ExecTypes.Idle -> "idle"
  | ExecTypes.PreprocessingError -> "error_pre"
  | ExecTypes.LexiconError -> "error_lex"
  | ExecTypes.ParseError -> "error_parse"
  | ExecTypes.ParseTimeout -> "timeout"
  | ExecTypes.NotParsed -> "not_parsed"
  | ExecTypes.ReductionError -> "error_reduction"
  | ExecTypes.TooManyNodes -> "to_many_nodes"
  | ExecTypes.NotReduced -> "not_reduced"
  | ExecTypes.SemError -> "error_sem"
  | ExecTypes.NotTranslated -> "not_translated"
  | ExecTypes.Parsed -> "parsed"

let rec xml_of_dependency_tree = function
    Node t -> Xml.Element("node",["pred",t.pred;"cat",t.cat;"weight",string_of_float t.weight;"id",string_of_int t.id],[
          Xml.Element("gs",[],[xml_of_dependency_tree t.gs]);
          Xml.Element("agf",[],[Xml.PCData (WalStringOf.gf t.agf)]);
          Xml.Element("amorf",[],[Xml.PCData (WalStringOf.morf t.amorf)]);
          Xml.Element("attrs",[],Xlist.map t.attrs (fun (e,t) -> Xml.Element("attr",["label",e],[xml_of_dependency_tree t])));
          Xml.Element("args",[],[xml_of_dependency_tree t.args])])
  | Concept c -> Xml.Element("concept",["var",fst c.c_variable ^ snd c.c_variable;"pos",string_of_int c.c_pos],[
      Xml.Element("sense",[],[xml_of_dependency_tree c.c_sense]);
      Xml.Element("quant",["local",if c.c_local_quant then "t" else "f"],[xml_of_dependency_tree c.c_quant]);
      Xml.Element("relations",[],[xml_of_dependency_tree c.c_relations])])
  | Context c -> Xml.Element("context",["var",fst c.cx_variable ^ snd c.cx_variable;"pos",string_of_int c.cx_pos],[
      Xml.Element("sense",[],[xml_of_dependency_tree c.cx_sense]);
      Xml.Element("contents",[],[xml_of_dependency_tree c.cx_contents]);
      Xml.Element("relations",[],[xml_of_dependency_tree c.cx_relations])])
  | Relation(r,a,t) -> Xml.Element("relation",[],[
      Xml.Element("role",[],[xml_of_dependency_tree r]);
      Xml.Element("role_attr",[],[xml_of_dependency_tree r]);
      xml_of_dependency_tree t])
  | RevRelation(r,a,t) -> Xml.Element("revrelation",[],[
      Xml.Element("role",[],[xml_of_dependency_tree r]);
      Xml.Element("role_attr",[],[xml_of_dependency_tree r]);
      xml_of_dependency_tree t])
  | SingleRelation(r) -> Xml.Element("singlerelation",[],[xml_of_dependency_tree r])
  | Tuple l -> Xml.Element("tuple",[],Xlist.map l xml_of_dependency_tree)
  | Val s -> Xml.Element("val",[],[Xml.PCData s])
  | Variant(e,l) -> Xml.Element("variants",["label",e],Xlist.map l (fun (i,t) ->
          Xml.Element("variant",["id",i],[xml_of_dependency_tree t])))
  | Dot -> Xml.Element("dot",[],[])
  | Ref i -> Xml.Element("ref",["id",string_of_int i],[])
  | Morf _ -> Xml.Element("dot",[],[]) (* FIXME!!! *)
  | t -> failwith ("xml_of_dependency_tree: " ^ LCGstringOf.linear_term 0 t)

let print_xml_dependency_tree path name dependency_tree =
  let l = Int.fold 0 (Array.length dependency_tree - 1) [] (fun l i ->
    (i, xml_of_dependency_tree dependency_tree.(i)) :: l) in
  let xml = Xml.Element("graph",[],Xlist.rev_map l (fun (i,xml) ->
    Xml.Element("graph_node",["id",string_of_int i],[xml]))) in
  File.file_out (path ^ name ^ ".xml") (fun file ->
    fprintf file "%s\n" (Xml.to_string_fmt xml))

let print_xml_tree path name tree =
  let xml = xml_of_dependency_tree tree in
  File.file_out (path ^ name ^ ".xml") (fun file ->
    fprintf file "%s\n" (Xml.to_string_fmt xml))



let rec get_refs rev = function
    Ref i -> i :: rev
  | Tuple l -> Xlist.fold l rev get_refs
  | Variant(e,l) -> Xlist.fold l rev (fun rev (i,t) -> get_refs rev t)
  | Dot -> rev
  | _ -> (*failwith*)print_endline "get_refs"; rev

let escape_string s =
  Int.fold 0 (String.length s - 1) "" (fun t i ->
    match String.sub s i 1 with
       "<" -> t ^ "〈"
     | ">" -> t ^ "〉"
     | c -> t ^ c)

let string_of_node t =
  let l = [
    "PRED",Val t.pred;"CAT",Val t.cat;"ID",Val (string_of_int t.id);"WEIGHT",Val (string_of_float t.weight);"GS",t.gs;
    "AGF",Gf t.agf;"AMORF",Morf t.amorf;"AROLE",Val t.arole;"AROLE-ATTR",Val t.arole_attr;
    "MEANING",Val t.meaning;"HIPERO",Tuple(Xlist.map (StringSet.to_list t.hipero) (fun s -> Val s));"MEANING-WEIGHT",Val (string_of_float t.meaning_weight);
    "ROLE",Val t.position.WalTypes.role;"ROLE-ATTR",Val t.position.WalTypes.role_attr;"SEL-PREFS",Tuple(Xlist.map t.position.WalTypes.sel_prefs (fun s -> Val s));
    "GF",Gf t.position.WalTypes.gf] @ t.attrs in
  "{ " ^ String.concat " | " (Xlist.map l (fun (e,t) -> "{ " ^ e ^ " | " ^ escape_string (LCGstringOf.linear_term 0 t) ^ " }")) ^ " }"

let single_rel_id_count = ref 0

let get_single_rel_id () =
  let id = !single_rel_id_count in
  incr single_rel_id_count;
  "s" ^ string_of_int id

let print_edge file label upper id =
  if upper <> "" then
    if label = "" then fprintf file "  %s -> %s\n" upper id
    else fprintf file "  %s -> %s  [label=\"%s\"]\n" upper id label

(*let rec print_graph_rec2 file edge upper = function
    Tuple l -> Xlist.iter l (print_graph_rec2 file edge upper)
  | Node t ->
          let id = get_single_rel_id () in
          fprintf file "  %s [label=\"%s\"]\n" id (string_of_node t);
          print_edge file edge upper id;
          print_graph_rec2 file "" id t.args
  | Concept t ->
          let id = get_single_rel_id () in
          fprintf file "  %s [shape=box,label=\"%s %s\"]\n" id
            (LCGchart.string_of_linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGchart.string_of_linear_term 0 t.c_name ^ "”"); (* FIXME *)
          print_edge file edge upper id;
          print_graph_rec2 file "" id t.c_relations
  | SingleRelation(role) ->
          let id = get_single_rel_id () in
          fprintf file "  %s [shape=circle,label=\"%s\"]\n" id (LCGchart.string_of_linear_term 0 role);
          if upper <> "" then fprintf file "  %s -> %s\n" upper id
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond]\n" e;
          print_edge file edge upper e;
          Xlist.iter l (fun (i,t) -> print_graph_rec2 file i e t)
  | Dot -> ()
  | Ref i -> print_edge file edge upper ("x" ^ string_of_int i)
  | t -> failwith ("print_graph_rec2: " ^ LCGchart.string_of_linear_term 0 t)    *)

let rec string_of_quant_rec quant = function
    Tuple l -> Xlist.fold l quant string_of_quant_rec
  | Variant(e,l) -> (LCGstringOf.linear_term 0 (Variant(e,l))) :: quant
  | Dot -> quant
  | Val s -> s :: quant
  | _ -> failwith "string_of_quant_rec"

let string_of_quant t =
  let l = string_of_quant_rec [] t in
  let s = String.concat " " l in
  if s = "" then "" else "<I>" ^ s ^ "</I> "

let rec print_dependency_tree_rec file edge upper id = function
    Node t ->
          fprintf file "  %s [label=\"%s\"]\n" id (string_of_node t);
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t.args
  | Concept t ->
          fprintf file "  %s [shape=box,label=<%s%s %s>]\n" id
            (string_of_quant t.c_quant)
            (LCGstringOf.linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGstringOf.linear_term 0 t.c_name ^ "”"); (* FIXME *)
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t.c_relations
  | Context t ->
          if t.cx_sense = Dot then fprintf file "  %s [shape=Msquare,label=\"\"]\n" id
          else fprintf file "  %s [shape=Msquare,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 t.cx_sense);
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t.cx_contents;
          print_dependency_tree_rec2 file "" id t.cx_relations;
  | Relation(role,role_attr,t) ->
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t
  | RevRelation(role,role_attr,t) -> (* FIXME: odwrócenie strzałek *)
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t
  | SingleRelation(role) ->
          fprintf file "  %s [shape=circle,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 role);
          print_edge file edge upper id
  | AddRelation(t,role,role_attr,s) ->
          fprintf file "  %s [shape=circle,label=\"AddRelation\\n%s\\n%s\"]\n" id role role_attr;
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t;
          print_dependency_tree_rec2 file "" id s;
  | SetContextName(s,t) ->
          fprintf file "  %s [shape=circle,label=\"SetContextName\\n%s\"]\n" id s;
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t
  | RemoveRelation t ->
          fprintf file "  %s [shape=circle,label=\"RemoveRelation\"]\n" id;
          print_edge file edge upper id;
          print_dependency_tree_rec2 file "" id t
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond,label=\"%s\"]\n" id e;
          print_edge file edge upper id;
          Xlist.iter l (fun (i,t) -> print_dependency_tree_rec2 file i id t)
  | Choice choice ->
          fprintf file "  %s [shape=Mdiamond,label=\"%s\"]\n" id "";
          print_edge file edge upper id;
          StringMap.iter choice (fun ei t -> print_dependency_tree_rec2 file ei id t)
  | Val s ->
          fprintf file "  %s [shape=box,label=\"%s\"]\n" id s;
          print_edge file edge upper id
  | Dot -> ()
(*          fprintf file "  %s [shape=box,label=\"Dot\"]\n" id;
          print_edge file edge upper id*)
  | Ref i -> print_edge file edge upper ("x" ^ string_of_int i)
  | t -> failwith ("print_dependency_tree_rec: " ^ LCGstringOf.linear_term 0 t)

and print_dependency_tree_rec2 file edge upper = function
    Tuple l -> Xlist.iter l (print_dependency_tree_rec2 file edge upper)
  | t -> print_dependency_tree_rec file edge upper (get_single_rel_id ()) t

(*let rec print_graph_rec file is_rev upper i = function  (* FIXME: dokończyć is_rev *)
    Node t ->
 (*         let orth = if t.id = 0 then "" else.(t.id).PreTypes.orth in
          fprintf file "  %s [label=\"%s\\n%s\\n%s:%s\"]\n" i (LCGstringOf.linear_term 0 t.gs) orth t.pred t.cat;*)
          fprintf file "  %s [label=\"%s\"]\n" i (string_of_node t);
          if upper <> "" then
            if is_rev then fprintf file "  %s -> %s\n" i upper
            else fprintf file "  %s -> %s\n" upper i;
          print_graph_rec file false i i t.args
  | Concept t ->
          fprintf file "  %s [shape=box,label=\"%s %s\"]\n" ("c" ^ i)
            (LCGstringOf.linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGstringOf.linear_term 0 t.c_name ^ "”"); (* FIXME *)
          if upper <> "" then
            if is_rev then fprintf file "  %s -> %s\n" ("c" ^ i) upper
            else fprintf file "  %s -> %s\n" upper ("c" ^ i);
          print_graph_rec file false ("c" ^ i) i t.c_relations
  | Context t ->
          fprintf file "  %s [shape=Msquare,label=\"\"]\n" ("i" ^ i);
          if upper <> "" then
            if is_rev then fprintf file "  %s -> %s\n" ("i" ^ i) upper
            else fprintf file "  %s -> %s\n" upper ("i" ^ i);
          print_graph_rec file false ("i" ^ i) i t.cx_contents
  | SingleRelation(role) ->
          let id = get_single_rel_id () in
          fprintf file "  %s [shape=circle,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 role);
          if upper <> "" then fprintf file "  %s -> %s\n" upper id
  | Relation(role,role_attr,t) ->
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" i (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          if upper <> "" then fprintf file "  %s -> %s\n" upper i;
          print_graph_rec file false i i t
  | RevRelation(role,role_attr,t) ->
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" i (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          if upper <> "" then fprintf file "  %s -> %s\n" i upper;
          print_graph_rec file true i i t
  | Tuple l -> Xlist.iter l (print_graph_rec file is_rev upper i)
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond]\n" e;
          if upper <> "" then fprintf file "  %s -> %s\n" upper e;
          Xlist.iter l (fun (i2,t) -> print_graph_rec file false e ("x" ^ i ^ "y" ^ i2) t)
  | Dot -> ()
  | Ref i2 -> fprintf file "  %s -> %d\n" upper i2
  | t -> failwith ("print_graph_rec: " ^ LCGstringOf.linear_term 0 t)*)

let print_dependency_tree path name dependency_tree =
  single_rel_id_count := 0;
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n  node [shape=record]\n";
    Int.iter 0 (Array.length dependency_tree - 1) (fun i -> print_dependency_tree_rec file (*false*) "" "" ("x" ^ string_of_int i) dependency_tree.(i));
(*    Int.iter 0 (Array.length dependency_tree - 1) (fun i ->
      match dependency_tree.(i) with
        Node t ->
          fprintf file "  %d [label=\"%s\"]\n" i (string_of_node t);
          let refs = get_refs [] t.args in
          Xlist.iter refs (fun r ->
            fprintf file "  %d -> %d\n" i r)
      | t -> failwith ("print_dependency_tree: " ^ LCGstringOf.linear_term 0 t));*)
    fprintf file "}\n");
  Sys.chdir path;
  ignore (Sys.command ("dot -Tpng " ^ name ^ ".gv -o " ^ name ^ ".png"));
  String.iter (function '/' -> Sys.chdir ".." | _ -> ()) path

let id_counter = ref 0

let print_edge2 file edge_rev edge_label edge_head edge_tail upper id =
  let edge_head,edge_tail,upper,id = if edge_rev then edge_tail,edge_head,id,upper else edge_head,edge_tail,upper,id in
  let l =
    (if edge_label = "" then [] else ["label=\"" ^ edge_label ^ "\""]) @
    (if edge_head = "" then [] else ["ltail=\"" ^ edge_head ^ "\""]) @
    (if edge_tail = "" then [] else ["lhead=\"" ^ edge_tail ^ "\""]) in
  if upper <> 0 then
    if l = [] then fprintf file "  %d -> %d\n" upper id
    else fprintf file "  %d -> %d  [%s]\n" upper id (String.concat "," l)

let rec print_graph2_rec file edge_rev edge_label edge_head upper = function
    Node t ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [label=\"%s\"]\n" id (string_of_node t);
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t.args
  | Concept t ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=box,label=<%s%s %s>]\n" id
            (string_of_quant t.c_quant)
            (LCGstringOf.linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGstringOf.linear_term 0 t.c_name ^ "”"); (* FIXME *)
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t.c_relations
  | Context t ->
          let id = !id_counter in
          incr id_counter;
          if t.cx_sense = Dot then fprintf file "  subgraph cluster%d {\nlabel=\"\"\n" id
          else fprintf file "  subgraph cluster%d {\nlabel=\"%s\"\n" id (LCGstringOf.linear_term 0 t.cx_sense);
          print_graph2_rec file false "" "" 0 t.cx_contents;
          fprintf file "  }\n";
          print_edge2 file edge_rev edge_label edge_head ("cluster" ^ string_of_int id) upper (id+1);
          print_graph2_rec file false "" ("cluster" ^ string_of_int id) (id+1) t.cx_relations;
  | Relation(role,role_attr,t) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge2 file false edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t
  | RevRelation(role,role_attr,t) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge2 file true edge_label edge_head "" upper id;
          print_graph2_rec file true "" "" id t
  | SingleRelation(role) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 role);
          print_edge2 file false edge_label edge_head "" upper id
  | AddRelation(t,role,role_attr,s) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"AddRelation\\n%s\\n%s\"]\n" id role role_attr;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t;
          print_graph2_rec file false "" "" id s
  | RemoveRelation t ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"RemoveRelation\"]\n" id;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t
  | SetContextName(s,t) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"SetContextName\\n%s\"]\n" id s;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t;
  | Tuple l -> Xlist.iter l (print_graph2_rec file edge_rev edge_label edge_head upper)
  | Variant(e,l) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=diamond,label=\"%s\"]\n" id e;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          Xlist.iter l (fun (i,t) -> print_graph2_rec file edge_rev  i "" id t)
  | Val s ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=box,label=\"%s\"]\n" id s;
          print_edge2 file edge_rev edge_label edge_head "" upper id
  | Dot -> ()
  | t -> failwith ("print_graph_rec: " ^ LCGstringOf.linear_term 0 t)

let print_graph2 path name query t =
(*   print_endline  *)
  id_counter := 1;
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n  compound=true\n  node [shape=record]\n";
    print_graph2_rec file false "" "" 0 t;
    fprintf file "label=\"%s\"\n  }\n" query);
(*   Sys.chdir path; *)
  ignore (Sys.command ("dot -Tpng " ^ path ^ name ^ ".gv -o " ^ path ^ name ^ ".png"))(*;
  Xlist.iter (Str.split (Str.regexp path) path) (fun _ -> Sys.chdir "..")*)

let rec get_lemma = function
    PreTypes.Interp orth -> orth
  | PreTypes.Lemma(lemma,cat,_) -> lemma ^ "\n" ^ cat
  | _ -> ""

let print_paths path name paths =
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n";
    Array.iter (fun t ->
      let lemma = get_lemma t.PreTypes.token in
      if lemma <> "" then fprintf file "  %d -> %d [label=\"%s\\n%s\"]\n" t.PreTypes.beg t.PreTypes.next t.PreTypes.orth lemma) paths;
    fprintf file "}\n");
  Sys.chdir path;
  ignore (Sys.command ("dot -Tpng " ^ name ^ ".gv -o " ^ name ^ ".png"));
  String.iter (function '/' -> Sys.chdir ".." | _ -> ()) path

let rec print_simplified_dependency_tree_rec2 file paths edge upper = function
    Tuple l -> Xlist.iter l (print_simplified_dependency_tree_rec2 file paths edge upper)
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond]\n" e;
          print_edge file edge upper e;
          Xlist.iter l (fun (i,t) -> print_simplified_dependency_tree_rec2 file paths i e t)
  | Dot -> ()
  | Ref i -> print_edge file edge upper ("x" ^ string_of_int i)
  | t -> failwith ("print_simplified_dependency_tree_rec: " ^ LCGstringOf.linear_term 0 t)

let rec print_simplified_dependency_tree_rec file paths edge upper id = function
    Node t ->
          let orth = if t.id = 0 then "" else paths.(t.id).PreTypes.orth in
          fprintf file "  %s [label=\"%s\\n%s\\n%s:%s\\n%f\"]\n" id (LCGstringOf.linear_term 0 t.gs) orth t.pred t.cat t.weight;
          print_edge file edge upper id;
          print_simplified_dependency_tree_rec2 file paths "" id t.args
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond,label=\"%s\"]\n" id e;
          print_edge file edge upper id;
          Xlist.iter l (fun (i,t) -> print_simplified_dependency_tree_rec file paths i id (id ^ "y" ^ i) t)
  | Choice choice ->
          fprintf file "  %s [shape=Mdiamond,label=\"%s\"]\n" id "";
          print_edge file edge upper id;
          StringMap.iter choice (fun ei t -> print_simplified_dependency_tree_rec file paths ei id (id ^ "b" ^ ei) t)
  | Dot -> ()
  | t -> failwith ("print_simplified_dependency_tree_rec: " ^ LCGstringOf.linear_term 0 t)

let print_simplified_dependency_tree path name paths dependency_tree =
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n  node [shape=box]\n";
    Int.iter 0 (Array.length dependency_tree - 1) (fun i -> print_simplified_dependency_tree_rec file paths "" "" ("x" ^ string_of_int i) dependency_tree.(i));
(*      match dependency_tree.(i) with
        Node t ->
          let orth = if t.id = 0 then "" else paths.(t.id).PreTypes.orth in
          fprintf file "  %d [label=\"%s\\n%s\\n%s:%s\"]\n" i (LCGstringOf.linear_term 0 t.gs) orth t.pred t.cat;
          let refs = get_refs [] t.args in
          Xlist.iter refs (fun r ->
            fprintf file "  %d -> %d\n" i r)
      | t -> failwith ("print_simplified_dependency_tree: " ^ LCGstringOf.linear_term 0 t));*)
    fprintf file "}\n");
  Sys.chdir path;
  ignore (Sys.command ("dot -Tpng " ^ name ^ ".gv -o " ^ name ^ ".png"));
  String.iter (function '/' -> Sys.chdir ".." | _ -> ()) path

(*let print_tree filename paths dependency_tree =
  File.file_out filename (fun file ->
    fprintf file "digraph G {\n";
    let set = Xlist.fold paths IntSet.empty (fun set t ->
      IntSet.add (IntSet.add set t.PreTypes.beg) t.PreTypes.next) in
    IntSet.iter set (fun i -> fprintf file "  %d [width=0; height=0; label=\"\"]\n" i);
    Xlist.iter paths (fun t ->
      let lemma = get_lemma t.PreTypes.token in
      if lemma <> "" then (
        let s = if t.PreTypes.orth = "" then lemma else t.PreTypes.orth ^ "\n" ^ lemma in
        fprintf file "  %d -> i%d -> %d [arrowhead=none]\n" t.PreTypes.beg t.PreTypes.id t.PreTypes.next;
        fprintf file "  i%d [label=\"%s\"]\n" t.PreTypes.id s));
    fprintf file "}\n");
  Sys.chdir "results";
  ignore (Sys.command "dot -Tpng tree.gv -o tree.png");
  String.iter (function '/' -> Sys.chdir ".." | _ -> ()) path*)

(*let print_tree filename paths dependency_tree =
  File.file_out filename (fun file ->
    fprintf file "digraph G {\n";
      fprintf file "  subgraph {\n  ordering=out\n";
      let same = Xlist.fold (Xlist.sort paths (fun s t -> compare s.PreTypes.beg t.PreTypes.beg)) [] (fun same t ->
        let lemma = get_lemma t.PreTypes.token in
        if lemma <> "" then (
          let s = if t.PreTypes.orth = "" then lemma else t.PreTypes.orth ^ "\n" ^ lemma in
          fprintf file "    i%d -> out [arrowhead=none]\n" t.PreTypes.id;
          fprintf file "    i%d [label=\"%s\"]\n" t.PreTypes.id s;
          t.PreTypes.id :: same)
        else same) in
      fprintf file "  }\n";
      fprintf file "  { rank = same; %s }\n" (String.concat "; " (Xlist.map same (fun i -> sprintf "\"i%d\"" i)));
    Int.iter 0 (Array.length dependency_tree - 1) (fun i ->
      match dependency_tree.(i) with
        Node t ->
          fprintf file "  %d [label=\"%s\"]\n" i t.pred;
          fprintf file "  %d -> i%d\n" i t.id;
          let refs = get_refs [] t.args in
          Xlist.iter refs (fun r ->
            fprintf file "  %d -> %d\n" i r)
      | _ -> failwith "print_graph");
    fprintf file "}\n");
  Sys.chdir "results";
  ignore (Sys.command "dot -Tpng tree.gv -o tree.png");
  Sys.chdir ".."*)

let rec schema_latex schema =
  "\\begin{tabular}{l}" ^
  String.concat "\\\\" (Xlist.map schema (fun s ->
    LatexMain.escape_string (String.concat "," (
      (if s.WalTypes.gf = WalTypes.ARG then [] else [WalStringOf.gf s.WalTypes.gf])@
      (if s.WalTypes.role = "" then [] else [s.WalTypes.role])@
      (if s.WalTypes.role_attr = "" then [] else [s.WalTypes.role_attr])@
      s.WalTypes.sel_prefs@(WalStringOf.controllers s.WalTypes.cr)@(WalStringOf.controllees s.WalTypes.ce)) ^ WalStringOf.direction s.WalTypes.dir ^ "{" ^  String.concat ";" (Xlist.map s.WalTypes.morfs WalStringOf.morf) ^ "}"))) ^
  "\\end{tabular}"

let fnum_frame_latex = function
    fnum,WalTypes.Frame(atrs,s) ->
      Printf.sprintf "%d: %s: %s" fnum (LatexMain.escape_string (WalStringOf.frame_atrs atrs)) (schema_latex s)
  | fnum,WalTypes.LexFrame(id,p,r,s) ->
      Printf.sprintf "%d: %s: %s: %s: %s" fnum id (LatexMain.escape_string (WalStringOf.pos p)) (WalStringOf.restr r) (schema_latex s)
  | fnum,WalTypes.ComprepFrame(le,p,r,s) ->
      Printf.sprintf "%d: %s: %s: %s: %s" fnum le (LatexMain.escape_string (WalStringOf.pos p)) (WalStringOf.restr r) (schema_latex s)

(*let print_paths_latex name paths =
  LatexMain.latex_file_out "results/" name "a0" false (fun file ->
    fprintf file "\\begin{longtable}{|l|l|l|l|l|l|l|p{4cm}|l|l|l|l|}\n\\hline\north & beg & len & next & token & id & weight & attrs & lroles & senses & simple valence & valence\\\\\n";
    Int.iter 0 (Array.length paths - 1) (fun i ->
      let t = paths.(i) in
      fprintf file "%s & %d & %d & %d & %s & %d & %.4f & %s & %s %s &\\begin{tabular}{l|l|p{4cm}}%s\\end{tabular} &\\begin{tabular}{l}%s\\end{tabular} &\\begin{tabular}{l}%s\\end{tabular}\\\\\n\\hline\n"
        t.PreTypes.orth t.PreTypes.beg t.PreTypes.len t.PreTypes.next (LatexMain.escape_string (string_of_token t.PreTypes.token)) t.PreTypes.id t.PreTypes.weight
        (String.concat ";" t.PreTypes.attrs) (fst t.PreTypes.lroles) (snd t.PreTypes.lroles)
        (String.concat "\\\\\n" (Xlist.map t.PreTypes.senses (fun (sense,hipero,weight) -> sprintf "%s & %.2f & %s" sense weight (String.concat "," hipero))))
        (String.concat "\\\\\n\\hline\n" (Xlist.map t.PreTypes.simple_valence (fun x -> fnum_frame_latex x)))
        (String.concat "\\\\\n\\hline\n" (Xlist.map t.PreTypes.valence (fun x -> fnum_frame_latex x))));
    fprintf file "\\end{longtable}");
  LatexMain.latex_compile_and_clean "results/" name*)

let print_mml path name mml =
  File.file_out (path ^ name ^ ".mml") (fun file ->
    fprintf file "<!DOCTYPE math PUBLIC \"-//W3C//DTD MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd\">\n";
    fprintf file "%s\n" (Xml.to_string_fmt mml))

let page_header path =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
  <head>
	<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=utf8\">
	<TITLE>ENIAM: Kategorialny Parser Składniowo-Semantyczny</TITLE>
	<META HTTP-EQUIV=\"Content-Language\" CONTENT=\"pl\">
  </head>

  <body>
 <center>
   <h1>ENIAM: Kategorialny Parser Składniowo-Semantyczny</h1>
    <h3>Podaj tekst:</h3>
    <form method=POST action=\"" ^ path ^ "parser.cgi\">
      <p><input type=\"text\" name=\"text0\" value=\"\" size=\"40\"></p>
      <p><input type=\"submit\" value=\"Analizuj\" size=\"60\"></p>
   </form>"

let page_trailer =
"<BR><BR>
<hr align=\"center\" size=\"2\" width=\"800\" />
Copyright &copy; 2016 Institute of Computer Science Polish Academy of Sciences<BR>
</center>
  </body>
</html>"

let print_webpage file cg_bin_path html_path id query n max_n mml =
  fprintf file "%s\n" (page_header cg_bin_path);
  fprintf file "\n<H3>%s</H3>\n" query;
  fprintf file "<P>%s %s\n"
    (if n = 1 then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Poprzednia interpretacja</A>" html_path id (n-1))
    (if n = max_n then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Następna interpretacja</A>" html_path id (n+1));
  fprintf file "<P><IMG SRC=\"%stree%s_%d.png\">\n" html_path id n;
  fprintf file "<P>%s\n" (Xml.to_string_fmt mml);
  fprintf file "<P><A HREF=\"%stree%s_%d.xml\">Graf w formacie XML</A>\n" html_path id n;
  fprintf file "<P><A HREF=\"%sformula%s_%d.mml\">Formuła w formacie MathML</A>\n" html_path id n;
  fprintf file "<P>%s %s\n"
    (if n = 1 then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Poprzednia interpretacja</A>" html_path id (n-1))
    (if n = max_n then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Następna interpretacja</A>" html_path id (n+1));
  fprintf file "%s\n" page_trailer

open ExecTypes

let generate_status_message result = function
    Idle -> "Server error: " ^ result.msg
  | PreprocessingError -> "Error during preprocessing: " ^ result.msg
  | LexiconError -> "Error during LCG lexicon generation: " ^ result.msg
  | ParseError -> "Error during parsing: " ^ result.msg
  | ParseTimeout -> "Parser timeout: " ^ result.msg
  | NotParsed -> "Unable to parse query"
  | ReductionError -> "Error during dependency tree generation: " ^ result.msg
  | TooManyNodes -> "Depencency tree is too big"
  | NotReduced -> "Unable to generate dependency tree"
  | SemError -> "Error during logical form generation: " ^ result.msg
  | NotTranslated -> "Unable to generate logical form"
  | Parsed -> "parsed"

let print_other_result file cg_bin_path query result =
  fprintf file "%s\n" (page_header cg_bin_path);
  fprintf file "\n<H3>%s</H3>\n" query;
  fprintf file "\n<P>%s\n" (generate_status_message result result.status);
  fprintf file "%s\n" page_trailer

let string_of_mode = function
    Raw -> "Raw"
  | Struct -> "Struct"
  | CONLL -> "CONLL"
  | ENIAM -> "ENIAM"
  | Mate -> "Mate"

(*let rec string_of_sentence = function
    RawSentence s -> sprintf "RawSentence(%s)" s
  | StructSentence(id,paths,last) -> sprintf "StructSentence(%s,%s,%d)" id (string_of_paths1 paths) last
  | ORSentence _ -> failwith "string_of_sentence: ni"
  | AltSentence l -> sprintf "AltSentence([\n          %s])" (String.concat ";\n          " (Xlist.map l (fun (mode,sentence) ->
      string_of_mode mode ^ ", " ^ string_of_sentence sentence)))
  | _ -> failwith "string_of_sentence: ni"

let rec string_of_paragraph = function
    RawParagraph s -> sprintf "RawParagraph(%s)" s
  | StructParagraph sentences ->
      sprintf "StructParagraph([\n        %s])" (String.concat ";\n        " (Xlist.map sentences (fun p ->
        sprintf "{pid=%s; pbeg=%d; plen=%d; psentence=%s}" p.pid p.pbeg p.plen (string_of_sentence p.psentence))))
  | AltParagraph l -> sprintf "AltParagraph(\n      %s)" (String.concat "\n      " (Xlist.map l (fun (mode,paragraph) ->
      string_of_mode mode ^ ", " ^ string_of_paragraph paragraph)))

let rec string_of_text = function
    RawText s -> sprintf "RawText(%s)" s
  | StructText(paragraphs,next_id) ->
      sprintf "StructText([\n    %s],%d)" (String.concat ";\n    " (Xlist.map paragraphs string_of_paragraph)) next_id
  | AltText l -> sprintf "AltText(\n  %s)" (String.concat "\n  " (Xlist.map l (fun (mode,text) ->
      string_of_mode mode ^ ", " ^ string_of_text text)))*)

let html_header =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
  <head>
	<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=utf8\">
	<TITLE>ENIAM: Kategorialny Parser Składniowo-Semantyczny</TITLE>
	<META HTTP-EQUIV=\"Content-Language\" CONTENT=\"pl\">
  </head>

  <body>
 <center>"

let html_trailer =
"</center>
  </body>
</html>"

let escape_html s =
  Int.fold 0 (String.length s - 1) "" (fun t i ->
    match String.sub s i 1 with
       "<" -> t ^ "&lt;"
     | ">" -> t ^ "&gt;"
     | "&" -> t ^ "&amp;"
     | c -> t ^ c)

let html_of_struct_sentence tokens paths last =
  "<table><tr><td><b>orth</b></td><td><b>token</b></td><td><b>id</b></td><td><b>lnode</b></td><td><b>rnode</b></td></tr>" ^
  String.concat "\n" (Xlist.map (List.sort compare paths) (fun (id,lnode,rnode) ->
    let t = ExtArray.get tokens id in
    sprintf "<tr><td>%s</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td></tr>"
      t.PreTypes.orth (escape_html (string_of_token t.PreTypes.token)) id lnode rnode)) ^
  sprintf "<tr><td></td><td></td><td></td><td>%d</td><td></td></tr>" last ^
  "</table>"

let html_of_dep_sentence tokens paths =
  "<table><tr><td><b>orth</b></td><td><b>token</b></td><td><b>id</b></td><td><b>conll_id</b></td><td><b>super</b></td><td><b>label</b></td></tr>" ^
  String.concat "\n" (List.rev (Int.fold 0 (Array.length paths - 1) [] (fun l conll_id ->
    let id,super,label = paths.(conll_id) in
    let t = ExtArray.get tokens id in
    (sprintf "<tr><td>%s</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td></tr>"
      t.PreTypes.orth (escape_html (string_of_token t.PreTypes.token)) id conll_id super label) :: l))) ^
  "</table>"

let html_of_tokens tokens =
  "<table><tr><td><b>id</b></td><td><b>orth</b></td><td><b>beg</b></td><td><b>len</b></td><td><b>next</b></td><td><b>token</b></td></td><td><b>attrs</b></td></tr>" ^
  String.concat "\n" (List.rev (Int.fold 0 (ExtArray.size tokens - 1) [] (fun l id ->
    let t = ExtArray.get tokens id in
    (sprintf "<tr><td>%d</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td><td>%s</td></tr>"
      id t.PreTypes.orth t.PreTypes.beg t.PreTypes.len t.PreTypes.next (escape_html (string_of_token t.PreTypes.token))
      (String.concat "; " t.PreTypes.attrs)) :: l))) ^
  "</table>"

let create_latex_chart path name chart =
  LatexMain.latex_file_out path name "a1" false (fun file ->
    Printf.fprintf file "%s\n" (LCGlatexOf.chart chart));
  LatexMain.latex_compile_and_clean path name

let create_latex_dep_graph_parsed path name graph =
  LatexMain.latex_file_out path name "a1" false (fun file ->
    Printf.fprintf file "%s\n" (LCGlatexOf.dep_graph_parsed graph));
  LatexMain.latex_compile_and_clean path name

let create_latex_dep_graph path name graph =
  LatexMain.latex_file_out path name "a1" false (fun file ->
    Printf.fprintf file "%s\n" (LCGlatexOf.dep_graph graph));
  LatexMain.latex_compile_and_clean path name

let html_of_eniam_sentence path (result : eniam_parse_result) =
  match result.status with
    Idle -> "idle\n"
  (* | PreprocessingError -> "error_pre: %s\n" result.msg *)
  | LexiconError -> sprintf "error_lex: %s\n" result.msg
  | ParseError ->
      create_latex_chart path (result.id ^ "_chart") result.chart;
      sprintf "error_parse: %s\n" result.msg ^
      sprintf "<BR><A HREF=\"%s_chart.pdf\">Chart</A>\n" result.id
  | ParseTimeout ->
      create_latex_chart path (result.id ^ "_chart") result.chart;
      sprintf "timeout: %s\n" result.msg ^
      sprintf "<BR><A HREF=\"%s_chart.pdf\">Chart</A>\n" result.id
  | NotParsed ->
      create_latex_chart path (result.id ^ "_chart") result.chart;
      sprintf "not_parsed: paths_size=%d chart_size=%d\n" result.paths_size result.chart_size ^
      sprintf "<BR><A HREF=\"%s_chart.pdf\">Chart</A>\n" result.id
  | ReductionError -> sprintf "error_reduction: %s\n" result.msg
  | TooManyNodes -> sprintf "to_many_nodes: paths_size=%d chart_size=%d\n" result.paths_size result.chart_size
  | NotReduced -> sprintf "not_reduced: paths_size=%d chart_size=%d\n" result.paths_size result.chart_size
  | SemError -> sprintf "error_sem: %s dependency_tree_size=%d\n" result.msg result.dependency_tree_size
  (* | NotTranslated -> "not_translated: \n"  *)
  | Parsed ->
(*      print_simplified_dependency_tree path (result.id ^ "_simplified_dependency_tree") result.paths result.dependency_tree;
      print_dependency_tree path (result.id ^ "_dependency_tree") result.dependency_tree;*)
      LCGlatexOf.print_dependency_tree path (result.id ^ "_dependency_tree_references") result.dependency_tree;
      sprintf "parsed: paths_size=%d chart_size=%d dependency_tree_size=%d\n" result.paths_size result.chart_size result.dependency_tree_size ^
      sprintf "<BR><A HREF=\"%s_simplified_dependency_tree.png\">Simplified Dependency Tree</A>\n" result.id ^
      sprintf "<BR><A HREF=\"%s_dependency_tree.png\">Dependency Tree</A>\n" result.id ^
      sprintf "<BR><A HREF=\"%s_dependency_tree_references.pdf\">Dependency Tree References</A>\n" result.id
  | _ -> failwith "html_of_eniam_sentence"

let html_of_conll_sentence path (result : conll_parse_result) =
  match result.status with
    Idle -> "idle\n"
  (* | PreprocessingError -> "error_pre: %s\n" result.msg *)
  | LexiconError -> sprintf "error_lex: %s\n" result.msg
  | ParseError ->
      create_latex_dep_graph path (result.id ^ "_dep_chart") result.dep_graph;
      create_latex_dep_graph_parsed path (result.id ^ "_dep_chart_parsed") result.dep_graph_parsed;
      sprintf "error_parse: %s\n" result.msg
  | ParseTimeout ->
      create_latex_dep_graph path (result.id ^ "_dep_chart") result.dep_graph;
      create_latex_dep_graph_parsed path (result.id ^ "_dep_chart_parsed") result.dep_graph_parsed;
      sprintf "timeout: %s\n" result.msg
  | NotParsed ->
      create_latex_dep_graph path (result.id ^ "_dep_chart") result.dep_graph;
      create_latex_dep_graph_parsed path (result.id ^ "_dep_chart_parsed") result.dep_graph_parsed;
      sprintf "not_parsed\n"
  | ReductionError -> sprintf "error_reduction: %s\n" result.msg
  | TooManyNodes -> sprintf "to_many_nodes: paths_size=%d\n" result.paths_size
  | NotReduced ->
      LCGlatexOf.print_dependency_tree path (result.id ^ "_dependency_tree_references") result.dependency_tree;
      sprintf "not_reduced: paths_size=%d\n" result.paths_size ^
      sprintf "<BR><A HREF=\"%s_dependency_tree_references.pdf\">Dependency Tree References</A>\n" result.id
  | SemError -> sprintf "error_sem: %s dependency_tree_size=%d\n" result.msg result.dependency_tree_size
  (* | NotTranslated -> "not_translated: \n"  *)
  | Parsed ->
      print_simplified_dependency_tree path (result.id ^ "_simplified_dependency_tree") result.paths result.dependency_tree;
      print_dependency_tree path (result.id ^ "_dependency_tree") result.dependency_tree;
      LCGlatexOf.print_dependency_tree path (result.id ^ "_dependency_tree_references") result.dependency_tree;
      sprintf "parsed: paths_size=%d dependency_tree_size=%d\n" result.paths_size result.dependency_tree_size ^
      sprintf "<BR><A HREF=\"%s_simplified_dependency_tree.png\">Simplified Dependency Tree</A>\n" result.id ^
      sprintf "<BR><A HREF=\"%s_dependency_tree.png\">Dependency Tree</A>\n" result.id ^
      sprintf "<BR><A HREF=\"%s_dependency_tree_references.pdf\">Dependency Tree References</A>\n" result.id
  | _ -> failwith "html_of_conll_sentence"


let rec html_of_sentence path tokens = function
    RawSentence s -> s
  | StructSentence(_,paths,last) -> html_of_struct_sentence tokens paths last
  | DepSentence(_,paths) -> html_of_dep_sentence tokens paths
  | ENIAMSentence result -> html_of_eniam_sentence path result
  | CONLLSentence result -> html_of_conll_sentence path result
  | QuotedSentences sentences ->
      String.concat "<BR>\n" (Xlist.map sentences (fun p ->
        sprintf "pid=%s pbeg=%d plen=%d pnext=%d<BR>%s" p.pid p.pbeg p.plen p.pnext (html_of_sentence path tokens p.psentence)))
  | AltSentence l ->
     "<table border=1>" ^
     String.concat "\n" (Xlist.map l (fun (mode,sentence) ->
       sprintf "<tr><td>%s</td><td>%s</td></tr>" (string_of_mode mode) (html_of_sentence path tokens sentence))) ^
     "</table>"
  (* | _ -> failwith "html_of_sentence: ni" *)

let rec html_of_paragraph path tokens = function
    RawParagraph s -> s
  | StructParagraph sentences ->
      String.concat "<BR>\n" (Xlist.map sentences (fun p ->
        sprintf "pid=%s pbeg=%d plen=%d pnext=%d<BR>%s" p.pid p.pbeg p.plen p.pnext (html_of_sentence path tokens p.psentence)))
  | AltParagraph l ->
     "<table border=2>" ^
     String.concat "\n" (Xlist.map l (fun (mode,paragraph) ->
       sprintf "<tr><td>%s</td><td>%s</td></tr>" (string_of_mode mode) (html_of_paragraph path tokens paragraph))) ^
     "</table>"

let rec html_of_text path = function
    RawText s -> s
  | StructText(paragraphs,tokens) ->
      sprintf "%s<BR>\n%s"
        (String.concat "<BR>\n" (Xlist.map paragraphs (html_of_paragraph path tokens)))
        (html_of_tokens tokens)
  | AltText l ->
     "<table border=3>" ^
     String.concat "\n" (Xlist.map l (fun (mode,text) ->
       sprintf "<tr><td>%s</td><td>%s</td></tr>" (string_of_mode mode) (html_of_text path text))) ^
     "</table>"

let print_html_text path name text =
  File.file_out (path ^ name ^ ".html") (fun file ->
    fprintf file "%s\n" html_header;
    fprintf file "%s\n" (html_of_text path text);
    fprintf file "%s\n" html_trailer)