visualization.ml 56.7 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 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
(*
 *  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 lemma_of_token = function
    PreTypes.SmallLetter orth -> orth
  | PreTypes.CapLetter(orth,lc) -> orth
  | PreTypes.AllSmall orth -> orth
  | PreTypes.AllCap(orth,lc,lc2) -> orth
  | PreTypes.FirstCap(orth,lc,cl,ll) -> orth
  | PreTypes.SomeCap orth -> orth
  | PreTypes.RomanDig(v,t) -> v
  | PreTypes.Interp orth -> orth
  | PreTypes.Symbol orth  -> orth
  | PreTypes.Dig(v,t) -> v
  | PreTypes.Other2 orth  -> orth
  | PreTypes.Lemma(lemma,cat,interps) -> lemma
  | PreTypes.Proper(lemma,cat,interps,senses) -> lemma
  | PreTypes.Compound(sense,l) -> "Compound"
  | PreTypes.Tokens(cat,l) -> "Tokens"

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 -> "too_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)
            (escape_string (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 tokens edge upper = function
    Tuple l -> Xlist.iter l (print_simplified_dependency_tree_rec2 file tokens 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 tokens 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 tokens edge upper id = function
    Node t ->
          let orth = if t.id = 0 then "" else (ExtArray.get tokens 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 tokens "" 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 tokens 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 tokens 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 tokens 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 tokens "" "" ("x" ^ string_of_int i) dependency_tree.(i));
(*      match dependency_tree.(i) with
        Node t ->
          let orth = if t.id = 0 then "" else tokens.(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 ^ "parser2.cgi\">
      <p><input type=\"text\" name=\"text0\" value=\"\" size=\"100\"></p>
      <p><input type=\"submit\" value=\"Analizuj\" size=\"60\"></p>
   </form>"

(*<textarea name="text0" cols="100" rows="10"></textarea>*)

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"
  | Swigra -> "Swigra"
  | POLFIE -> "POLFIE"

(*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 html_of_tokens_simple_valence tokens =
  "<table><tr><td><b>id</b></td><td><b>orth</b></td><td><b>simple_valence</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
    Xlist.fold t.simple_valence l (fun l (fnum,frame) ->
      (sprintf "<tr><td>%d</td><td>%s</td><td>%s</td></tr>"
        id t.PreTypes.orth (WalStringOf.fnum_frame (lemma_of_token t.token) (fnum,frame))) :: l)))) ^
  "</table>"

let html_of_tokens_valence tokens =
  "<table><tr><td><b>id</b></td><td><b>orth</b></td><td><b>simple_valence</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
    Xlist.fold t.valence l (fun l (fnum,frame) ->
      (sprintf "<tr><td>%d</td><td>%s</td><td>%s</td></tr>"
        id t.PreTypes.orth (WalStringOf.fnum_frame (lemma_of_token t.token) (fnum,frame))) :: 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_parsed_dep_chart path name parsed_dep_chart =
  LatexMain.latex_file_out path name "a1" false (fun file ->
    Printf.fprintf file "%s\n" (LCGlatexOf.parsed_dep_chart parsed_dep_chart));
  LatexMain.latex_compile_and_clean path name

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

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

let html_of_eniam_sentence path tokens (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.file_prefix ^ "_chart") result.chart;
      sprintf "error_parse: %s\n" result.msg ^
      sprintf "<BR><A HREF=\"%s_chart.pdf\">Chart</A>\n" result.file_prefix
  | ParseTimeout ->
      create_latex_chart path (result.file_prefix ^ "_chart") result.chart;
      sprintf "timeout: %s\n" result.msg ^
      sprintf "<BR><A HREF=\"%s_chart.pdf\">Chart</A>\n" result.file_prefix
  | NotParsed ->
      create_latex_chart path (result.file_prefix ^ "_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.file_prefix
  | 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.file_prefix ^ "_simplified_dependency_tree") tokens result.dependency_tree; *)
      (* print_dependency_tree path (result.file_prefix ^ "_dependency_tree") result.dependency_tree; *)
      (* LCGlatexOf.print_dependency_tree path (result.file_prefix ^ "_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.file_prefix ^ *)
      (* sprintf "<BR><A HREF=\"%s_dependency_tree.png\">Dependency Tree</A>\n" result.file_prefix  ^ *)
      (* sprintf "<BR><A HREF=\"%s_dependency_tree_references.pdf\">Dependency Tree References</A>\n" result.file_prefix *)
  | _ -> failwith "html_of_eniam_sentence"

let html_of_conll_sentence path tokens (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_chart path (result.file_prefix ^ "_dep_chart") result.dep_chart;
      create_latex_parsed_dep_chart path (result.file_prefix ^ "_parsed_dep_chart") result.parsed_dep_chart;
      sprintf "error_parse: %s\n" result.msg ^
      sprintf "<BR><A HREF=\"%s_dep_chart.pdf\">Chart</A>\n" result.file_prefix ^
      sprintf "<BR><A HREF=\"%s_parsed_dep_chart.pdf\">Parsed Chart</A>\n" result.file_prefix
  | ParseTimeout ->
      create_latex_dep_chart path (result.file_prefix ^ "_dep_chart") result.dep_chart;
      create_latex_parsed_dep_chart path (result.file_prefix ^ "_parsed_dep_chart") result.parsed_dep_chart;
      sprintf "timeout: %s\n" result.msg ^
      sprintf "<BR><A HREF=\"%s_dep_chart.pdf\">Chart</A>\n" result.file_prefix ^
      sprintf "<BR><A HREF=\"%s_parsed_dep_chart.pdf\">Parsed Chart</A>\n" result.file_prefix
  | NotParsed ->
      create_latex_dep_chart path (result.file_prefix ^ "_dep_chart") result.dep_chart;
      create_latex_not_parsed_dep_chart path (result.file_prefix ^ "_not_parsed_dep_chart") result.not_parsed_dep_chart;
      sprintf "not_parsed\n" ^
      html_of_dep_sentence tokens result.paths ^
      sprintf "<BR><A HREF=\"%s_dep_chart.pdf\">Chart</A>\n" result.file_prefix ^
      sprintf "<BR><A HREF=\"%s_not_parsed_dep_chart.pdf\">Not Parsed Chart</A>\n" result.file_prefix
  | 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.file_prefix ^ "_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.file_prefix
  | 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.file_prefix ^ "_simplified_dependency_tree") tokens result.dependency_tree; *)
      (* print_dependency_tree path (result.file_prefix ^ "_dependency_tree") result.dependency_tree; *)
      (* LCGlatexOf.print_dependency_tree path (result.file_prefix ^ "_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.file_prefix ^ *)
      (* sprintf "<BR><A HREF=\"%s_dependency_tree.png\">Dependency Tree</A>\n" result.file_prefix ^ *)
      (* sprintf "<BR><A HREF=\"%s_dependency_tree_references.pdf\">Dependency Tree References</A>\n" result.file_prefix *)
  | _ -> failwith "html_of_conll_sentence"

let html_of_sem_sentence path tokens (result : semantic_processing_result) =
  match result.status with
    Idle -> "idle\n"
  | SemError -> sprintf "error_sem: %s\n" result.msg
      (* print_dependency_tree path (result.file_prefix ^ "_disamb") result.disamb;
      print_dependency_tree path (result.file_prefix ^ "_sem") result.sem;
      print_dependency_tree path (result.file_prefix ^ "_sem2") result.sem2;
      print_graph2 "results/" "sem3" query result.sem3; *)
  | NotTranslated ->
      (* print_dependency_tree path (result.file_prefix ^ "_disamb") result.disamb;
      print_dependency_tree path (result.file_prefix ^ "_sem") result.sem;
      print_dependency_tree path (result.file_prefix ^ "_sem2") result.sem2; *)
      print_graph2 path (result.file_prefix ^ "_sem3") "" result.sem3;
      sprintf "not_translated \n" ^
      (* sprintf "<BR><A HREF=\"%s_disamb.png\">Disambiguated Dependency Tree</A>\n" result.file_prefix ^
      sprintf "<BR><A HREF=\"%s_sem.png\">Semantic Graph 1</A>\n" result.file_prefix ^
      sprintf "<BR><A HREF=\"%s_sem2.png\">Semantic Graph 2</A>\n" result.file_prefix ^ *)
      sprintf "<BR><A HREF=\"%s_sem3.png\">Semantic Graph</A>\n" result.file_prefix
  | Parsed ->
      print_graph2 path (result.file_prefix ^ "_sem3") "" result.sem3;
      sprintf "parsed \n" ^
      sprintf "<BR><A HREF=\"%s_sem3.png\">Semantic Graph</A>\n" result.file_prefix
  | _ -> failwith "html_of_sem_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 tokens result
  | CONLLSentence result -> html_of_conll_sentence path tokens result
  | SemSentence result -> html_of_sem_sentence path tokens 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 -> (*print_endline "AltSentence";*)
     "<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 -> (*print_endline "RawParagraph";*) s
  | StructParagraph sentences -> (*print_endline "StructParagraph";*)
      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 -> (*print_endline "AltParagraph";*)
     "<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\n%s\n%s"
        (String.concat "<BR>\n" (Xlist.map paragraphs (html_of_paragraph path tokens)))
        (html_of_tokens tokens) (html_of_tokens_simple_valence tokens) (html_of_tokens_valence 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)

let rec find_prev_next_sentence pid rev = function
    AltSentence[Raw,_;Struct,QuotedSentences sentences] ->
      Xlist.fold sentences rev (fun rev p -> find_prev_next_sentence p.pid rev p.psentence)
  | AltSentence[Raw,RawSentence s; mode,SemSentence result] -> result.file_prefix :: rev
  | AltSentence[Raw,RawSentence s] -> ("p" ^ pid) :: rev
  | _ -> failwith "find_prev_next_sentence: ni"

let rec find_prev_next_paragraph rev = function
    RawParagraph s -> rev
  | StructParagraph sentences ->
      Xlist.fold sentences rev (fun rev p -> find_prev_next_sentence p.pid rev p.psentence)
  | AltParagraph l -> Xlist.fold l rev (fun rev (mode,paragraph) -> find_prev_next_paragraph rev paragraph)

let rec make_prev_next_map map prev = function
    [x] -> StringMap.add map x (prev,"")
  | x :: next :: l -> make_prev_next_map (StringMap.add map x (prev,next)) x (next :: l)
  | [] -> failwith "make_prev_next_map"

let print_main_result cg_bin_path mode path id tokens query result prev_next_map =
  let prev,next = try StringMap.find prev_next_map result.file_prefix with Not_found -> failwith "print_main_result" in
  File.file_out (path ^ "page" ^ id ^ "_" ^ result.file_prefix ^ ".html") (fun file ->
    fprintf file "%s\n" (page_header cg_bin_path);
    if prev <> "" then fprintf file "<A HREF=\"page%s_%s.html\">Poprzednie zdanie</A> " id prev;
    if next <> "" then fprintf file " <A HREF=\"page%s_%s.html\">Następne zdanie</A>" id next;
    fprintf file "\n<H3>%s</H3>\n" query;
    if mode <> ENIAM then fprintf file "<P>Parsed by %s\n" (string_of_mode mode);
    ignore (Xlist.fold2 result.trees result.mrls 1 (fun n tree mrl ->
      print_graph2 path ("tree" ^ id ^ "_" ^ result.file_prefix ^ "_" ^ string_of_int n) "" tree;
      print_xml_tree path ("tree" ^ id ^ "_" ^ result.file_prefix ^ "_" ^ string_of_int n) tree;
      let mml = SemMmlOf.mml_of_mrl mrl in
      print_mml path ("formula" ^ id ^ "_" ^ result.file_prefix ^ "_" ^ string_of_int n) mml;
      fprintf file "<P><IMG SRC=\"tree%s_%s_%d.png\">\n" id result.file_prefix n;
      fprintf file "<P>%s\n" (Xml.to_string_fmt mml);
      fprintf file "<P><A HREF=\"tree%s_%s_%d.xml\">Graf w formacie XML</A>\n" id result.file_prefix n;
      fprintf file "<P><A HREF=\"formula%s_%s_%d.mml\">Formuła w formacie MathML</A>\n" id result.file_prefix n;
      n+1));
    fprintf file "<P>";
    if prev <> "" then fprintf file "<A HREF=\"page%s_%s.html\">Poprzednie zdanie</A> " id prev;
    if next <> "" then fprintf file " <A HREF=\"page%s_%s.html\">Następne zdanie</A>" id next;
    fprintf file "%s\n" page_trailer)

let print_not_parsed_main_result cg_bin_path path id query pid prev_next_map =
  let pid = "p" ^ pid in
  let prev,next = try StringMap.find prev_next_map pid with Not_found -> failwith "print_not_parsed_main_result" in
  File.file_out (path ^ "page" ^ id ^ "_" ^ pid ^ ".html") (fun file ->
    fprintf file "%s\n" (page_header cg_bin_path);
    if prev <> "" then fprintf file "<A HREF=\"page%s_%s.html\">Poprzednie zdanie</A> " id prev;
    if next <> "" then fprintf file " <A HREF=\"page%s_%s.html\">Następne zdanie</A>" id next;
    fprintf file "\n<H3>%s</H3>\n" query;
    fprintf file "<P>Not parsed\n";
    fprintf file "<P>";
    if prev <> "" then fprintf file "<A HREF=\"page%s_%s.html\">Poprzednie zdanie</A> " id prev;
    if next <> "" then fprintf file " <A HREF=\"page%s_%s.html\">Następne zdanie</A>" id next;
    fprintf file "%s\n" page_trailer)

let rec print_main_result_sentence cg_bin_path path id tokens pid prev_next_map = function
    AltSentence[Raw,_;Struct,QuotedSentences sentences] ->
      Xlist.iter sentences (fun p -> print_main_result_sentence cg_bin_path path id tokens p.pid prev_next_map p.psentence)
  | AltSentence[Raw,RawSentence query; mode,SemSentence result] ->
      print_main_result cg_bin_path mode path id tokens query result prev_next_map
  | AltSentence[Raw,RawSentence query] -> print_not_parsed_main_result cg_bin_path path id query pid prev_next_map
  | _ -> failwith "print_main_result_sentence: ni"

let rec print_main_result_paragraph cg_bin_path path id tokens prev_next_map = function
    RawParagraph s -> ()
  | StructParagraph sentences ->
      Xlist.iter sentences (fun p -> print_main_result_sentence cg_bin_path path id tokens p.pid prev_next_map p.psentence)
  | AltParagraph l -> Xlist.iter l (fun (mode,paragraph) -> print_main_result_paragraph cg_bin_path path id tokens prev_next_map paragraph)

let rec print_main_result_text cg_bin_path path id = function
    RawText s -> ()
  | StructText(paragraphs,tokens) ->
      let prev_next_map = make_prev_next_map StringMap.empty ""
        (List.rev (Xlist.fold paragraphs [] find_prev_next_paragraph)) in
      Xlist.iter paragraphs (print_main_result_paragraph cg_bin_path path id tokens prev_next_map)
  | AltText l -> Xlist.iter l (fun (mode,text) -> print_main_result_text cg_bin_path path id text)

let print_main_result_first_page cg_bin_path mode path id tokens query result prev_next_map =
  let prev,next = try StringMap.find prev_next_map result.file_prefix with Not_found -> failwith "print_main_result" in
  printf "%s\n" (page_header cg_bin_path);
  if prev <> "" then printf "<A HREF=\"%spage%s_%s.html\">Poprzednie zdanie</A> " path id prev;
  if next <> "" then printf " <A HREF=\"%spage%s_%s.html\">Następne zdanie</A>" path id next;
  printf "\n<H3>%s</H3>\n" query;
  if mode <> ENIAM then printf "<P>Parsed by %s\n" (string_of_mode mode);
  ignore (Xlist.fold2 result.trees result.mrls 1 (fun n tree mrl ->
    let mml = SemMmlOf.mml_of_mrl mrl in
    printf "<P><IMG SRC=\"%stree%s_%s_%d.png\">\n" path id result.file_prefix n;
    printf "<P>%s\n" (Xml.to_string_fmt mml);
    printf "<P><A HREF=\"%stree%s_%s_%d.xml\">Graf w formacie XML</A>\n" path id result.file_prefix n;
    printf "<P><A HREF=\"%sformula%s_%s_%d.mml\">Formuła w formacie MathML</A>\n" path id result.file_prefix n;
    n+1));
  printf "<P>";
  if prev <> "" then printf "<A HREF=\"%spage%s_%s.html\">Poprzednie zdanie</A> " path id prev;
  if next <> "" then printf " <A HREF=\"%spage%s_%s.html\">Następne zdanie</A>" path id next;
  printf "%s\n" page_trailer

let print_not_parsed_main_result_first_page cg_bin_path path id query pid prev_next_map =
  let pid = "p" ^ pid in
  let prev,next = try StringMap.find prev_next_map pid with Not_found -> failwith "print_not_parsed_main_result" in
  printf "%s\n" (page_header cg_bin_path);
  if prev <> "" then printf "<A HREF=\"%spage%s_%s.html\">Poprzednie zdanie</A> " path id prev;
  if next <> "" then printf " <A HREF=\"%spage%s_%s.html\">Następne zdanie</A>" path id next;
  printf "\n<H3>%s</H3>\n" query;
  printf "<P>Not parsed\n";
  printf "<P>";
  if prev <> "" then printf "<A HREF=\"%spage%s_%s.html\">Poprzednie zdanie</A> " path id prev;
  if next <> "" then printf " <A HREF=\"%spage%s_%s.html\">Następne zdanie</A>" path id next;
  printf "%s\n" page_trailer

let rec print_main_result_first_page_sentence cg_bin_path path id tokens pid prev_next_map = function
    AltSentence[Raw,_;Struct,QuotedSentences sentences] ->
      let p = List.hd sentences in
      print_main_result_first_page_sentence cg_bin_path path id tokens p.pid prev_next_map p.psentence
  | AltSentence[Raw,RawSentence query; mode,SemSentence result] ->
      print_main_result_first_page cg_bin_path mode path id tokens query result prev_next_map
  | AltSentence[Raw,RawSentence query] -> print_not_parsed_main_result_first_page cg_bin_path path id query pid prev_next_map
  | _ -> failwith "print_main_result_first_page_sentence: ni"

let rec print_main_result_first_page_paragraph cg_bin_path path id tokens prev_next_map = function
    RawParagraph s -> ()
  | StructParagraph sentences ->
      let p = List.hd sentences in
      print_main_result_first_page_sentence cg_bin_path path id tokens p.pid prev_next_map p.psentence
  | AltParagraph l -> Xlist.iter l (fun (mode,paragraph) -> print_main_result_first_page_paragraph cg_bin_path path id tokens prev_next_map paragraph)

let rec print_main_result_first_page_text cg_bin_path path id = function
    RawText s -> ()
  | StructText(paragraphs,tokens) ->
      let prev_next_map = make_prev_next_map StringMap.empty ""
        (List.rev (Xlist.fold paragraphs [] find_prev_next_paragraph)) in
      print_main_result_first_page_paragraph cg_bin_path path id tokens prev_next_map (List.hd paragraphs)
  | AltText l -> Xlist.iter l (fun (mode,text) -> print_main_result_first_page_text cg_bin_path path id text)