package petablox.souffle;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import petablox.bddbddb.Dom;
import petablox.bddbddb.Rel;
import petablox.project.Config;
import petablox.project.PetabloxException;

public abstract class SouffleIOBase {
	protected String workDir = Config.souffleWorkDirName;
	
	protected PrintWriter createPrintWriter(File outFile) { return createPrintWriter(outFile, false); }
    protected PrintWriter createPrintWriter(File outFile, boolean autoFlush) {
        try {
            return new PrintWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"), autoFlush);
        } catch (IOException e) {
            throw new PetabloxException(e);
        }
    }	
	
	public void setWorkDir(String dirName) {
		workDir = Config.souffleWorkDirName;
	}
	
	protected String getDomainDefinition(Dom<?> dom) {
		StringBuilder sb = new StringBuilder();
		sb.append(".symbol_type ");
		sb.append(dom.getName());
		return sb.toString();
	}
	
	protected String getDomainInclude(Dom<?> dom) {
		StringBuilder sb = new StringBuilder();
		sb.append("#ifdef ");
		sb.append(dom.getName() + "\n");
		sb.append("#include ");
		sb.append(dom.getName() + ".dl" + "\n");
		sb.append("#endif\n");
		return sb.toString();
	}

	protected String getRelationDefinition(Rel rel) {
		StringBuilder sb = new StringBuilder();
		sb.append(".decl ");
		sb.append(rel.getName());
		sb.append("(");
		
		int i = 0;
		for (Dom<?> d : rel.getDoms()) {
			sb.append(rel.getName() + i);
			sb.append(":");
			sb.append(d.getName());
			i++;
			
			if (i != rel.getDoms().length) sb.append(",");
		}
		
		sb.append(")");
		
		return sb.toString();
	}
	
}

@@ -164,16 +164,64 @@
 tWriter;
+%0Aimport java.util.HashMap;%0Aimport java.util.Map;
 %0A%0Aimport
@@ -1568,73 +1568,349 @@
 ;%0A%09%09
-for (Dom%3C?%3E d : rel.getDoms()) %7B%0A%09%09%09sb.append(rel.get
+Map%3CString, Integer%3E m = new HashMap%3CString, Integer%3E();%0A%09%09for (Dom%3C?%3E d : rel.getDoms()) %7B%0A%09%09%09String domainName = d.getName();%0A%09%09%09if (m.containsKey(domainName)) %7B%0A%09%09%09%09int index = m.get(domainName);%0A%09%09%09%09sb.append(domainName + index);%0A%09%09%09%09m.put(domainName, index + 1);%0A%09%09%09%7D else %7B%0A%09%09%09%09sb.append(domain
 Name
-()
  + 
-i);
+0);%0A%09%09%09%09m.put(domainName, 1);%0A%09%09%09%7D
 %0A%09%09%09
@@ -1956,16 +1956,20 @@
 ));%0A
+%09%09%09%0A
 %09%09%09i++;%0A
 %09%09%09%0A
@@ -1964,20 +1964,16 @@
 %09%09%09i++;%0A
-%09%09%09%0A
 %09%09%09if (i

Implement Kihong's suggestion