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


/** Merge interpolated lat and lon with records of input log file.
    First column of log file must be epoch seconds. 
 */
public class Merger {

    public static void main(String[] args) {

	if (args.length != 2) {
	    System.err.println("usage: time-log time-location");
	    return;
	}

	BufferedReader logData = null;
	try {
	    logData = 
		new BufferedReader(new FileReader(new File(args[0])));
	}
	catch (Exception e) {
	    System.err.println("Couldn't open log file " + args[0] + 
			       ": " + e);
	    return;
	}
	    
	LocationFile locations = null;
	try {
	    locations = new LocationFile(args[1]);
	}
	catch (Exception e) {
	    System.err.println("Couldn't open location file " + args[1] + 
			       ": " + e);
	    return;
	}
	
	// Get interpolated location for each line in log file, 
	// insert interpolated lat and lon as columns 2 and 3
	int recordNo = 0;
	
	while (true) {

	    try {
		String logLine = logData.readLine();
		if (logLine == null) {
		    break;
		}
		String[] tokens = logLine.split("\\s+");
		long epochMsec = Long.parseLong(tokens[0].trim());
		try {
		    LocationFile.Location location = 
			locations.getLocation(epochMsec);


		    System.out.print(epochMsec + " " + location._latitude + " " + 
				     location._longitude);
		    // Append remainder of log tokens
		    for (int i = 1; i < tokens.length; i++) {
			System.out.print(" " + tokens[i]);
		    }
		    System.out.print("\n");
		}
		catch (Exception e2) {
		    System.err.println("Interpolation error: " + e2);
		    e2.printStackTrace();
		}
		
	    }
	    catch (Exception e) {
		System.err.println("Error processing log record #" + recordNo + ": " + e);
	    }
	    recordNo++;
	}
    }
}
