import java.io.File;
import java.io.RandomAccessFile;
import java.io.BufferedReader;
import java.io.FileReader;

/**
   Join file1 and file2 based on timestamp in first column - not strictly an "equality join", 
   but join file2 record that has closest timestamp to file1 record timestamp.
   Assumes that timestamps in both files are in ascending order.
 */
public class JoinClosest {

    
    public static void main(String[] args) {
	if (args.length != 2) {
	    System.err.println("usage: file1 file2");
	    return;
	}

	String file1name = args[0];
	BufferedReader file1Reader;
	try {
	    file1Reader = new BufferedReader(new FileReader(new File(file1name)));
	}
	catch (Exception e) {
	    System.err.println("Error opening " + file1name + ": " + e);
	    return;
	}

	String file2name = args[1];
	RandomAccessFile file2;
	try {
	    file2 = new RandomAccessFile(new File(file2name), "r");
	}
	catch (Exception e) {
	    System.err.println("Error opening " + file2name + ": " + e);
	    return;
	}

	// Read column 1 from file 1
	while ((line1 = readLine(reader1)) != null) {
	    if (line1.trim().startsWith("#")) {
		// Skip comment line
		continue;
	    }
	    String[] tokens1 = line.split("\\s+");
	    long value1 = 0;
	    try {
		value1 = Long.parseLong(tokens1[0]);
	    }
	    catch (Exception e) {
		System.err.println("Unable to parse long value from " + tokens1[0]);
		continue;
	    }
	}
    }

    /** Find line in file2 with column 1 value that is closest match to specified value */
    String closestMatch(long value, RandomAccessFile file2) throws Exception {
	if (value < _previousValue) {
	    file2.seek(0);
	}
	
	long prevDelta = Long.MAX_VALUE;

	while (true) {
	    long startPos = file2.getFilePointer();
	    String line = file2.readLine();
	    if (line == null) {
		throw new Exception("Encountered EOF without finding closest match to " + value);
	    }

	    String[] tokens = line.split("\\s+");
	    if (tokens[0].trim().startsWith("#")) {
		// Ignore comment lines
		continue;
	    }

	    long value2 = Long.parseLong(tokens[0]);
	    long delta = Math.absolute(value2-value);
	    if (delta > prevDelta) {
		// Passed minimum difference; return previous line
		return prevLine;
	    }
	}
    }
}
