// $Id: xxl_sumif.cc,v 1.3 1997/01/07 01:07:38 aml Exp $

#include "xxl_funcs.hh"
#include "sheet.hh"


Stack_elem *Sumif::eval(Stack_elem *p,Sheet *sheet, short col, short row) {
    int i,j,k,l;
    char *st;
    Ref ref1, ref2;
    double sum = 0;
    Stack_elem *s1,*s2;
    static double exp2;

    switch (cnt) {
    case 0:
      rg1 = p->contents.rg_val;
      break;
    case 1:
      cond = p->contents.string_val;
      break;
    case 2:
      if (!sheet->propagate_error(p,se)) {
          switch(p->type) {
            case FORM_FP:
            case FORM_INT:
            case FORM_REF:
            case FORM_STRING:
              exp2 = sheet->stack_value(p);
              break;
          }
      }
    case 3:
      rg2 = p->contents.rg_val;
      break;
    }

    if (cnt == 3) {
      Range_iter r1(rg1);
      Range_iter r2(rg2);
      float f1,f2,f3;
      
      for(r1.first(ref1),r2.first(ref2); 
          !(r1.last() || r2.last());  r1.next(ref1),r2.next(ref2)){
        i = cell_address(ref1.col,col);
        j = cell_address(ref1.row,row);
        k = cell_address(ref2.col,col);
        l = cell_address(ref2.row,row);
        s1 = sheet->cellRef(i,j);
        f1 = sheet->stack_value(s1);
        sheet->propagate_error(s1,se);
        s2 = sheet->cellRef(k,l);
        f2 = sheet->stack_value(s2);
        sheet->propagate_error(s2,se);
        switch(cond[0]) {
        case '=':
          if (f2 == exp2) {
            sum += f1;
          }
          break;
        case '>':
          if (f2 > exp2) {
            sum += f1;
          }
          break;
        case '<':
          if (f2 < exp2) {
            sum += f1;
          }
          break;
        default:
          SET_ERROR(se,ERROR_BAD_CONDITION);
          return(se);
        }
      }

      se->type = FORM_FP;
      se->contents.fp_val = sum;
    }

    cnt++;
    return(se);
}

Sumif::Sumif() {
  cnt = 0;
  se = new Stack_elem;
}

Sumif::~Sumif() {
  delete se;
}


// $Log: xxl_sumif.cc,v $
// Revision 1.3  1997/01/07  01:07:38  aml
// Error propagation for formulas fixed.
// Edit operations in place.
//
// Revision 1.2  1996/12/11  21:39:52  aml
// Sumif implemented.
// Diverse time functions implemented.
// Fixed needtoscroll2 to avoid out of control scroll.
//
// Revision 1.1  1996/11/28 15:46:16  aml
// Initial revision
//
