(*
    HLins: insert http-links into HTML documents.
    See http://www.lri.fr/~treinen/hlins

    Copyright (C) 1999 Ralf Treinen <treinen@lri.fr>

    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 2 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, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*)

open String;;
open Str;;
open List;;

(* (addindices [s1;...;sn]) yields [(1,p1,l1),...,(n,pn,ln)]
   where pi is the part of string s1 up to the last blank, and ln
   is the word form the last blank on.
*)
let addindices l =
  let rec addindices_aux i = function
      [] -> []
    | h::r -> 
	(try
	  let bi = rindex h ' '
	  in (i,(string_before h bi),(string_after h (bi+1)))
	 with
	     Not_found -> (i,"",h)
	)::(addindices_aux (i+1) r)
  in addindices_aux 0 l
    ;;

let preamble =
"<html>
<head>
<title>Hlins Database Listing</title>
</head>

<body>
<h1>Hlins Database Listing</h1>
";;

let postamble =
"</body>
</html>
";;

let dumpdb al ul =
begin
  print_string preamble;
  fold_left
    (fun  (lastname, lastfirstname, lasturl, lastchar) (i,p,l)   ->
       let lc = String.get l 0
       and u = ul.(i)
       in
	 begin
	   if lastname <> l || lastfirstname <> p
	   then print_string "<br>\n";
	   if lc <> lastchar
	   then
	     begin
	       print_string "<a name=";
	       print_char lc;
	       print_char '>'
	     end;
	   if l = lastname && p = lastfirstname
	   then 
	     if u <> lasturl
	     then
	       begin
		 print_string "[<a href=\"";
		 print_string u;
		 print_string "\">Alternative Site</a>]\n"
	       end
	     else
	       ()
	   else
	     begin
	       print_string "<a href=\"";
	       print_string u;
	       print_string "\">";
	       print_string p;
	       if String.length p <> 0 then print_char ' ';
	       print_string "<b>";
	       print_string l;
	       print_string "</b></a>\n"
	     end;
	   (l,p,u,lc)
	 end)
    ("","","",Char.chr(0))
    (sort 
       (fun (_,p1,l1) (_,p2,l2) ->
	  let lc = compare l1 l2
	  in if lc = 0 then compare p1 p2 else lc
       )
       (addindices al));
  print_string postamble
end



