/* -*- Mode: Prolog -*- */
/** @copyright
  
  This file is part of PrologDoc (http://prologdoc.sourceforge.net/).

  Copyright (C) 2004 by Salvador Fandino (sfandino@@yahoo.com)

  PrologDoc 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.

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

  @/copyright */

:- module(pd_process, [process_files/1]).

:- use_module(pd).
:- use_module(library('prologdoc/config')).
:- use_module(library('prologdoc/comments_parser')).
:- use_module(library('prologdoc/callback')).


process_files(Files) :-
	Tree = t($all, [], Eles),
	files_to_eles(Files, Eles, []),
	call_callbacks(Tree, Tree1, process, [], _),
	call_callbacks(Tree1, Tree2, autodoc, [], _),
	call_callbacks(Tree2, Tree3, assignid, [], _),
	call_callbacks(Tree3, Tree4, consults, [], _),
	call_callbacks(Tree4, Tree5, arrange, [], _),
	call_callbacks(Tree5, _, generate, [], _).
%	listing(pd:ele_ref),
%	listing(pd:ele_prop),
%	listing(pd:ele_consult).

files_to_eles([], [], _).
files_to_eles([N|More], [t($file, [$abs=A, $unique=U, $target=T, $original=N], [Top])|More1], Used) :-
	absolute_file_name(N, [access(read)], A),
	absolute_to_unique(A, U, Used),
	unique_to_target(U, T),
	parse_comments(A, Top),
	files_to_eles(More, More1, [U|Used]).

absolute_to_unique(A, U, Used) :-
	(   config(base, Base)
	->  (	(   atom_concat(Base, '/', Base1),
		    atom_concat(Base1, U1, A)
		;   atom_concat(Base, U1, A) )
	    ->	true
	    ;	throw(file_not_under_base(Base, A)) )
	;   file_base_name(A, U1) ),
	config(pl_ext, PlExt, ['pl', '']),
	(   (   file_name_extension(U2, _, U1)
	    ;	U2=U1 ),
	    member(Ext, PlExt),
	    file_name_extension(U2, Ext, U1)
	->  absolute_to_unique1(1, U2, U, Used)
	;   throw(unknow_file_extension(A, PlExt)) ).

absolute_to_unique1(1, N, U, Used) :-
	!,
	(   member(N, Used)
	->  absolute_to_unique1(2, N, U, Used)
	;   U = N).
absolute_to_unique1(I, N, U, Used) :-
	(   atom_concat(N, I, U),
	    \+ member(U, Used)
	->  true
	;   I1 is I + 1,
	    absolute_to_unique1(I1, N, U, Used) ).

unique_to_target(U, T) :-
	config(xml_ext, E, 'xml'),
	file_name_extension(U, E, U1),
	config(to, To, '.'),
	absolute_file_name(U1, [relative_to(To)], T).


