:- expects_dialect(sicstus).

:- use_module(library(lists),[append/3,member/2,delete/3]).       
:- use_module(library(system)).
:- use_module('html.pl').
:- use_module(papers,[bibentry/3]).
:- use_module(authors,[author/3]).
:- use_module(global_definitions).

    % fills the article and proceedings templates 
    % for the details corresponding to
    % Key in papers.pl. links are created for various files in
    % /users/faculty/cs/mcodish/.html/Papers/Sources. 
    % The output goes on the file 
    % /users/faculty/cs/mcodish/.html/Papers/Pages/Key.html
    % The bibtex entry goes on the file 
    % /users/faculty/cs/mcodish/.html/Papers/BibTex/Key.bib

all_pages :-
        by_year,            % creates the top-level list
        do_paper_pages,     % creates the individual pages for papers
        do_coauthor_pages.  % creates the pages for co-authors
        

by_year :-
      target(papers_dir,['ppapers.html'],Target),
      bot_year(Y1), top_year(Y2), 
      tell(Target),

    output_html([h1(font([color=darkred],'Publications Listed by Year')),
         'For details on a publication, click the title link. You will
         find an abstract, access to a bibtex item, and in many cases an
         online version of the paper. These are usually similar to the
         published version. Please observe the copyright notice. For
         information on a coauthor click,  the authors
         name. You will find a list of papers coauthored with that
         person and sometimes  a link to his/her homepage.',
         'For some information about how these pages were created check ',
         ref('Prolog/about.html','here'),'.']), 

    mbetween(Y1,Y2,Year),
      % display(Year),display(' ... '),
      output_html([h4(font([color=darkblue],['Published in ', Year]))]),
    member(Type,[article,inproceedings,tech_report]),
      findall(Key,
                (bibentry(Type,Key,ADic),member(year=Year,ADic)),Keys1),
      prepare_html_items(Type,Keys1,H1),
      output_html([itemize(H1)]),
    fail.

by_year :-
    output_html(["<p>","<hr>"]), 
    told.


prepare_html_items(_,[],[]).
prepare_html_items(article, [Key|Ks],
       [ [ref(URL,["\n",Title]),";<br>","\n",Author,"\n",
          ";&nbsp&nbsp&nbsp",em(Journal),";&nbsp",
          bf(Vol),Num,":", Pgs, ".","\n", "<p>","\n"] | Hs ]):-
    target(papers_url,['Pages','/',Key,'.html'],URL),
    bibentry(article,Key,ADic),
    member(title=Title,ADic),
    member(author=As,ADic),authors2html(As,Author),
    member(journal=Journal,ADic),
    member(volume=Vol,ADic),
    (member(number=N,ADic)->Num=['(',N,')'];Num=[]),
    member(pages=Pgs,ADic),
    prepare_html_items(article,Ks,Hs).

prepare_html_items(inproceedings, [Key|Ks],
       [ [ref(URL,Title),";<br>","\n",Author,";
          &nbsp&nbsp&nbsp",em(Booktitle),"<p>"] | Hs ]):-
    target(papers_url,['Pages','/',Key,'.html'],URL),
    bibentry(inproceedings,Key,ADic),
    member(title=Title,ADic),
    member(author=As,ADic),authors2html(As,Author),
    member(booktitle=Booktitle,ADic),
    prepare_html_items(inproceedings,Ks,Hs).

prepare_html_items(tech_report, [Key|Ks],
       [ [ref(URL,Title), ";<br>", "\n", Author,
          "; Technical Report (unpublished);", "<br>",
          Inst,"; ",
%          "Department of Computer Science; Ben-Gurion University; ", 
          Month, ", ", Year, ".","<p>"] | Hs ]):-
    target(papers_url,['Pages','/',Key,'.html'],URL),
    bibentry(tech_report,Key,ADic),
    member(title=Title,ADic),
    member(author=As,ADic),authors2html(As,Author),
    member(institution = Inst, ADic),
    member(year=Year,ADic),
    member(month=Month,ADic),
    prepare_html_items(tech_report,Ks,Hs).





do_paper_pages :- 
    findall(Key,bibentry(_,Key,_),KeysList),
    paper_pages(KeysList).


do_coauthor_pages :-
        findall(AuthorK,
          (bibentry(_,_,ADic),member(author=Authors,ADic),
           member(AuthorK,Authors),author(AuthorK,_,_)), Coauthors),
        do_coauthor_pages(Coauthors).
      



paper_pages([]).
paper_pages([K|Ks]) :- paper_page(K),!, paper_pages(Ks).

paper_page(Key) :-
        display('doing page and bibtex for...  '), display(Key), nl,

        % take the details on the paper from the papers database
        % and do the bibtex
        bibentry(Type,Key,ADic),
        make_bibtex(Type,Key,ADic),

        % Read the appropriate template file &
        % Convert it to pillow Terms
        %
        concat_str([Type,'_template.html'],TemplateStr),
        name(Template,TemplateStr),
        read_file(Template,TempStr),
        html_template(TempStr,PiLLoWTemplate,Dic),

        % Fill the template holes
        %
        authors(ADic,Dic),
        title(ADic,Dic),
        abstract(ADic,Dic),
        year(ADic,Dic),
        (Type = article ->
            journal(ADic,Dic),
            volume(ADic,Dic),
            pages(ADic,Dic),
            number(ADic,Dic)
           ;
         Type = inproceedings ->
                   booktitle(ADic,Dic)
           ;
         Type = tech_report ->
                member(month=X,ADic),
                member(month=X,Dic)
           ;
               display('bibentry type error'),nl
        ),
        available(Key,ADic,Dic),
        %notes(ADic,Dic),
        related(ADic,Dic),

        % Print the Template on Key.html
        %    
        write_template(Key,PiLLoWTemplate).

number(ADic,Dic):-
    (member(number=N,ADic) -> 
         member(number=['(',N,')'],Dic)
          ; member(number=' ',Dic)).
year(ADic,Dic) :-
    member(year=X,ADic),
    member(year=X,Dic).
pages(ADic,Dic) :-
    member(pages=X,ADic),
    member(pages=X,Dic).
volume(ADic,Dic) :-
    member(volume=X,ADic),
    member(volume=X,Dic).
journal(ADic,Dic) :-
    member(journal=X,ADic),
    member(journal=X,Dic).
booktitle(ADic,Dic) :-
    member(booktitle=X,ADic),
    member(booktitle=X,Dic).
title(ADic,Dic) :-
    member(title=X,ADic),
    member(title=X,Dic).
abstract(ADic,Dic) :-
    (member(abstract=X,ADic) -> 
        member(abstract=["<H4>Abstract:</H4><EM>","\n",
                          X,"\n","</EM><HR><P>"],Dic)
        ; member(abstract=' ',Dic)).

authors(ADic,Dic) :-            % authors could be a string or a list
    member(author=X,ADic),      % of keys and strings. the keys are
    authors2html(X,Hs),         % associated with names and urls in
    member(author=Hs,Dic).      % author/3

authors2html([One,Two],[OneHTML,' and ',"\n",TwoHTML]) :- !,
    a2h(One,OneHTML), a2h(Two,TwoHTML).
authors2html([One],[OneHTML,"\n"]) :- !,
    a2h(One,OneHTML).
authors2html([One|Rest],[OneHTML,', ',"\n"|RestHTML]) :- !,
    a2h(One,OneHTML),
    authors2html(Rest,RestHTML).
authors2html(String,String). 

a2h(K,HTML) :- 
      (author(K,Name,URL) ->
          (K=codish -> URL1=URL;
               target(papers_url,['Pages','/',K,'_list.html'],URL1)),
          HTML=ref(URL1,Name)
        ; HTML=K
      ).

make_bibtex(Type,Key,Info) :- 
    findall(F=Data,
        (member(F,[title,journal,
                   booktitle,editor,series,
                   volume,number,institution,month,year,pages,publisher]),
         member(F=Data,Info)
        ), List),
    member(author = As,Info),
    authors2txt(As,As1),
    target(papers_dir,['BibTex','/',Key,'.bib'],Target),
    tell(Target),
      write('@'),write(Type),write('{'),
      write(Key),write(','),nl,
      do_bib_fields([author=As1|List]),
    told.

authors2txt([A1,A2|As],Str) :- !,
        a2txt(A1,S1),
        authors2txt([A2|As],S2),
        concat_str([S1,' and ',S2],TStr),
        name(Str,TStr).
authors2txt([A1],S1) :- !,
        a2txt(A1,S1).
authors2txt(S,S).

a2txt(A,S) :- author(A,S,_),!.
a2txt(A,A).


do_bib_fields([F=Data,B|Bs]) :-
    write('   '),write(F),write(' = '), write('{'),
    write(Data), write('},'),nl,
    do_bib_fields([B|Bs]).
do_bib_fields([F=Data]) :-
    write('   '),write(F),write(' = '), write('{'),
    write(Data), write('}'),nl,
    write('}'),nl,nl.


available(Key,ADic,Dic) :-
        (member(available=Avail,ADic) -> X=[bibtex|Avail] ; X=[bibtex]),
        available2html(Key,X,HList),
        member(available=["Available: &nbsp;" | HList], Dic).
        
available2html(Key,[A|As],
             ["&nbsp;","&nbsp;",ref(URL,TXT),'\n'|Hs]) :-
        (
         A='bibtex'  -> TXT='bibtex entry',
                 target(papers_url,['BibTex','/', Key,'.bib'], URL);
         A='ps'      -> TXT='postscript', 
                 target(papers_url,['Sources','/', Key,'.ps'], URL);
         A='pdf'      -> TXT='pdf', 
                 target(papers_url,['Sources','/', Key,'.pdf'], URL);
         A='dvi'     -> TXT='dvi',        
                 target(papers_url,['Sources','/', Key,'.dvi'],URL);
         A='ps.gz'   -> TXT='compressed postscript',
                 target(papers_url,['Sources','/', Key,'.ps.gz'], URL); 
         A='dvi.gz'   -> TXT='compressed dvi',
                 target(papers_url,['Sources','/', Key,'.dvi.gz'],URL);  
         true
        ),
        available2html(Key,As,Hs).
available2html(_,[],[]).

related(ADic,Dic) :-
        ( member(related=X,ADic) 
        ->
          related2html(X,HList),
          member(related=["<P>","\n", 
                          "Related sites:  ", 
                           "\n" | HList], Dic)
       ;
          member(related=' ',Dic)
        ).
related2html( [(U,Text)|As], ["&nbsp;","&nbsp;",ref(URL,Text),'\n'|Hs]) :-
        (U = paper(Key) -> 
            target(papers_url,['Pages','/',Key,'.html'],URL);
         U = off_home(U1) -> 
            target(off_home,[U1],URL);
         U = source(U1) ->
            target(papers_url,['Sources','/',U1],URL);
         U = url(URL) -> true ;
         display('oops')
        ),
        related2html(As,Hs).
related2html([],[]).

do_coauthor_pages([]).
do_coauthor_pages([A|As]) :-
        make_coauthor_page(A),
        delete(As,A,As1),
        do_coauthor_pages(As1).
      
make_coauthor_page(AuthorK) :-
   display('doing author page for...  '), display(AuthorK), nl,
      author(AuthorK,Name,URL),
      (ground(URL) -> 
          Homepage=['Click here for coauthors ',ref(URL,homepage),'.']
        ;
          Homepage=' '),
      target(papers_dir,['Pages','/',AuthorK,'_list.html'],Target),
      bot_year(Y1), top_year(Y2), 
      tell(Target),
      output_html([h1(font([color=darkred],
                             ['Publications Coauthored with ',Name])),
                   'For details on a publication, 
                             click the title link.
                    For information on a coauthor click,
                    the authors name.', Homepage]),
%%add copyright note            
    mbetween(Y1,Y2,Year),
    member(Type,[article,inproceedings,tech_report]),
      findall(Key,
           (bibentry(Type,Key,ADic),member(year=Year,ADic),
            member(author=Authors,ADic),member(AuthorK,Authors)),Keys1),
      prepare_html_items(Type,Keys1,H1),
      (H1=[] -> true;output_html([itemize(H1)])),
    fail.

make_coauthor_page(_) :-
    output_html(["<p>","<hr>"]), 
    told.
 


fill_templates([],_,_).
fill_templates([F|Fs],ADic,Dic) :-
        member(F=X,ADic),
        member(F=X,Dic),
        fill_templates(Fs,ADic,Dic).


target(Type, Ts, Target) :-
        ( Type=papers_url -> home_page(HP),    Ts1=[HP,'Papers/'|Ts];
          Type=papers_dir -> web_dir(WD),      Ts1=[WD,'Papers/'|Ts];
          Type=off_home -> home_page(T),Ts1=[T|Ts];
          write('illegal target type')
        ),
    concat_str(Ts1, TargetStr),
    name(Target,TargetStr).


concat_str([],[]).
concat_str([T|Ts],TargetStr) :- 
    concat_str(Ts,TmpStr), 
    name(T,TStr), append(TStr,TmpStr,TargetStr).

write_template(Key,PiLLoWTemplate) :-
    target(papers_dir,['Pages','/',Key,'.html'],Target),
        tell(Target),
        output_html([PiLLoWTemplate]),
        told.


% read_file(+File, -String) : read a file into a string
%
read_file(File,String) :-
        open(File,read,S),
        read_all(S,String),
        close(S).

read_all(S,Str) :-
        get0(S,C),
        (
           C == -1 -> Str = []
        ;
           Str = [C|Cs],
           read_all(S,Cs)
        ).


mbetween(I,J,J) :- I =< J.
mbetween(I,J,K) :- I < J, J1 is J - 1, mbetween(I,J1,K).



