package MasteringHadoop;
 
 import org.apache.pig.Algebraic;
 import org.apache.pig.EvalFunc;
 import org.apache.pig.backend.executionengine.ExecException;
 import org.apache.pig.data.DataBag;
 import org.apache.pig.data.Tuple;
 
 import java.io.IOException;
 import java.util.Iterator;
 
 public class COUNT extends EvalFunc<Long> implements Algebraic {
 
      protected static Long count(Tuple input) throws ExecException{
          DataBag dataBag = (DataBag) input.get(0);
          return dataBag.size();
     }
 
     protected static Long sum(Tuple input) throws ExecException{
 
         long returnSum = 0;
         DataBag dataBag = (DataBag) input.get(0);
         for(Iterator<Tuple> it = dataBag.iterator(); it.hasNext();){
             Tuple tuple = it.next();
             returnSum += (long)tuple.get(0);
         }
         return returnSum;
 
     }
 
     static class Initial extends EvalFunc<Long>{
 
         @Override
         public Long exec(Tuple objects) throws IOException {
             return count(objects);  
         }
     }
 
     static class Intermediate extends EvalFunc<Long>{
 
         @Override
         public Long exec(Tuple objects) throws IOException {
             return sum(objects);  
         }
     }
 
     static class Final extends EvalFunc<Long>{
 
         @Override
         public Long exec(Tuple objects) throws IOException {
             return sum(objects);  
         }
     }
 
 
     @Override
     public Long exec(Tuple objects) throws IOException {
         return count(objects);  
     }
 
 
     @Override
     public String getInitial() {
         return Initial.class.getName();  
     }
 
     @Override
     public String getIntermed() {
         return Intermediate.class.getName();  
     }
 
     @Override
     public String getFinal() {
         return Final.class.getName();  
     }
 }
 
 
