import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.LineNumberReader;

public class FortlaufendeIDs {

    private static String COMMONSUBSTRING = "_ID";
    private static String[] VARS = {"PARAM_ID", "CONSTR_ID", "COND_ID", "ASSERT_ID", "DOCU_ID"};

    public static void main(String[] argv) throws IOException {
	if (argv.length != 3) {
	    System.err.println("Usage: java FortlaufendeIDs " +
			       "<NameOfInputFile> <FirstID> <NameOfOutputFile");
	    System.err.println("The input file is usually 'constraints.txt', FirstID can be set to 500, the output file will be 'Operators.sql'.");
	    System.exit(-1);
	}

	long id = 0;
	try {
	    id = Long.parseLong(argv[1]);
	}
	catch (NumberFormatException e) {
	    System.err.println("Start-ID invalid: " + argv[0]);
	    System.exit(-1);
	}
	String inputFileName = System.getProperty("user.dir") + File.separator + argv[0];
	String outputFileName = System.getProperty("user.dir") + File.separator + argv[2];

	LineNumberReader in  = new LineNumberReader (new FileReader(inputFileName));
	PrintStream out = new PrintStream(new FileOutputStream(outputFileName));
	String inputLine;
	while ((inputLine = in.readLine()) != null)
	    id = adjustLine(inputLine, out, id);
	in.close();
	out.flush();
	out.close();

	System.exit(0);
    }

    private static long adjustLine(String line, PrintStream out, long id) {
    	String newLine = line;
	    if (line.indexOf(COMMONSUBSTRING) != -1) {
	    	int firstVarIndex = -1;
	    	int lastVarIndex  = -1;
	    	for (int i=0; i<VARS.length; i++) {
	    		int index = line.indexOf(VARS[i]);
	    		if ( (firstVarIndex == -1)
	    				|| (index != -1 && index < firstVarIndex) )
	    		{
	    			firstVarIndex = index;
	    			lastVarIndex  = index + VARS[i].length();
	    		}
	    	}
	    	if (lastVarIndex != -1) {
	    		newLine = line.substring(0, firstVarIndex);
	    		newLine += Long.toString(id++);
	    		newLine += line.substring(lastVarIndex);
	    	}
	    }
	    out.println(newLine);
	    return id;
    }

} 
