/* lp_print.c
 * Neil Moore <neil@cs.uky.edu>
 * 28 Mar 2000
 *
 * Part of liblp.  See COPYRIGHT for copyright information.
 */
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <lp.h>
#include <lp_print.h>
#include <lp_util.h>

static void lp_print_rule(FILE *f, struct lp *prog, struct lp_rule *rule);

/* Print a logic program to a file.  Each rule is printed, and the number
 * of models and all requirements are put into a compute statement.  The
 * program is acceptable as input to lparse.
 *
 */
int lp_print_program(FILE *outfile, struct lp *prog)
{
	int i;

	lp_assert(prog);
	lp_assert(outfile);
	
	for(i=0; i<prog->nrules; i++)
		lp_print_rule(outfile, prog, &prog->rules[i]);

	fprintf(outfile, "compute %d", prog->nmodels);
	fprintf(outfile, " { ");
	for(i=0; i<prog->nposreq; i++) {
		if(i>0)
			fprintf(outfile, ", ");
		fprintf(outfile, "%s", prog->posreq[i]->name);
	}
	for(i=0; i<prog->nnegreq; i++) {
		if(i>0 || prog->nposreq)
			fprintf(outfile, ", ");
		fprintf(outfile, "not %s", prog->negreq[i]->name);
	}
	fprintf(outfile, " }.");
	fprintf(outfile, "\n");
	
	return 0;
}


/* Print a rule from a logic program.  The rule is printed as:
 *   a :- b1, . . ., bn, not c1, . . ., not cm.
 *
 */
void lp_print_rule(FILE *f, struct lp *prog, struct lp_rule *rule) 
{
	int i;

	fprintf(f, "%s", rule->head->name);
	
	if(rule->npos)
		fprintf(f, " :- %s", rule->pos[0]->name);

	for(i=1; i<rule->npos; i++)
		fprintf(f, ", %s", rule->pos[i]->name);

	if(rule->nneg && rule->npos == 0)
		fprintf(f, " :- not %s", rule->neg[0]->name);	
	else if(rule->nneg)
		fprintf(f, ", not %s", rule->neg[0]->name);
	
	for(i=1; i<rule->nneg; i++)
		fprintf(f, ", not %s", rule->neg[i]->name);
	
	fprintf(f, ".\n");
}
