
#ifndef RULES_H
#define RULES_H

#define MAX_N_RULES 256

// The form of a Rule can be one of the following:
// 1. if projection n region m then projection i
// 2. if projection n region m then class i
struct Rule {
	unsigned char Flag; // 0:Rule:Proj, 1:Rule:Class, 2:Cond:Proj, 3:Cond:Class
	unsigned char Projection;
	unsigned char Region;
	unsigned char ProjClass;
};

class Rules {

public:

	int specialruleclass;
	int numspecialrules;
	int specialrules[32][3]; // [rulenum][proj,reg,class]

	Rule rarray[MAX_N_RULES];
	int numRules;
	char buffer[1024];

	Rules() : numRules(0) , numspecialrules(0) { };

	void AddSpecialRule(int p, int r) {
		specialrules[numspecialrules][0]= p;
		specialrules[numspecialrules][1]= r;
		specialrules[numspecialrules][2]= specialruleclass;
		numspecialrules++;
	};

	void AddRule(int rulecondflag, int p, int r, int projclassflag, int pc) {
		rarray[numRules].Flag = 0;
		if (rulecondflag) rarray[numRules].Flag |= (unsigned char)2;
		rarray[numRules].Projection = (unsigned char)p;
		rarray[numRules].Region = (unsigned char)r;
		if (projclassflag) rarray[numRules].Flag |= (unsigned char)1;
		rarray[numRules].ProjClass = (unsigned char)pc;
		numRules++;
	};

	void ReadRules() {
		char ifstr[16];
		char projstr[16];
		char regstr[16];
		char thenstr[16];
		char pcstr[16];
		int p, r, pc;
		FILE *fptr;
		fptr = fopen("rules.txt","rt");
		while(!feof(fptr)) { // while file is not empty
			fgets(buffer,1024,fptr); // read a line
			if (strlen(buffer)>16) { // if the line is valid
				sscanf(buffer,"%s %s %d %s %d %s %s %d", ifstr, projstr, &p, regstr, &r, thenstr, pcstr, &pc); 
				rarray[numRules].Projection = (unsigned char)p;
				rarray[numRules].Region = (unsigned char)r;
				rarray[numRules].ProjClass = (unsigned char)pc;
				rarray[numRules].Flag = (unsigned char)0;
				if (strcmp(pcstr,"class")==0) rarray[numRules].Flag |= (unsigned char)1;
				if (strcmp(projstr,"condproj")==0) rarray[numRules].Flag |= (unsigned char)2;
				numRules++;
			}
		}
	};

};

#endif

