import java.io.IOException;
import java.util.Iterator;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;

/* Phase 2 Reducer: Sum weights of edges
*/
   

public class P2Reducer extends MapReduceBase implements Reducer {

	public void reduce(WritableComparable key, Iterator values,
			   OutputCollector output, Reporter reporter) throws IOException
    {
	GraphEdge efinal = null;
	while (efinal == null && values.hasNext()) {
	    try {
		efinal = new GraphEdge(values.next().toString());
	    } catch (BadGraphException e) {}
	}
	if (efinal != null) {
	    while(values.hasNext()) {
		try {
		    GraphEdge eother = new GraphEdge(values.next().toString());
		    efinal.weight += eother.weight;
		} catch (BadGraphException e) {}
	    }
	    if (efinal.weight != 0)
		output.collect(new Text(efinal.toString()), new Text(""));
	}
    }
}
