# include "dvoshell.h"

/* return average.field based on the selection */
double dbExtractAverages (Average *average, SecFilt *secfilt, Measure *measure, dbField *field) {

  int i;
  double value;

  value = NO_MAG;

  /* assign vector values */
  switch (field->ID) {
    case AVE_RA:
      value = average[0].R;
      break;
    case AVE_DEC:
      value = average[0].D;
      break;
    case AVE_RA_ERR:
      value = average[0].dR;
      break;
    case AVE_DEC_ERR:
      value = average[0].dD;
      break;

    case AVE_U_RA:
      value = average[0].uR;
      break;
    case AVE_U_DEC:
      value = average[0].uD;
      break;
    case AVE_U_RA_ERR:
      value = average[0].duR;
      break;
    case AVE_U_DEC_ERR:
      value = average[0].duD;
      break;

    case AVE_PAR:
      value = average[0].P;
      break;
    case AVE_PAR_ERR:
      value = average[0].dP;
      break;

    case AVE_NMEAS:
      value = average[0].Nm;
      break;
    case AVE_NMISS:
      value = average[0].Nn;
      break;
    case AVE_Xp:
      value = 0.01*average[0].Xp;
      break;
    case AVE_FLAG:
      value = average[0].code;
      break;

    case AVE_MAG:
      switch (field->magMode) {
	case MAG_AVE:
	  value = PhotAve  (field->photcode, average, secfilt);
	  break;
	case MAG_REF:
	  value = PhotRef  (field->photcode, average, secfilt, measure);
	  break;
	case MAG_INST:
	case MAG_CAT:
	case MAG_SYS:
	case MAG_REL:
	case MAG_CAL:
	  // XXX need to code this correctly: this returns just the first matching value
	  value = NO_MAG;
	  for (i = 0; i < average[0].Nm; i++) {
	    if (field->photcode->code != measure[i].photcode) continue;
	    value = measure[i].M;
	    break;
	  }
	  break;
      }
      break;
    case AVE_dMAG:
      value = PhotdM (field->photcode, average, secfilt);
      break;
    case AVE_Xm:
      value = PhotXm (field->photcode, average, secfilt);
      break;
    case AVE_TYPE:
      break;
    case AVE_TYPEFRAC:
      break;
    case AVE_NCODE:
      value = 0;
      for (i = 0; i < average[0].Nm; i++) {
	if (field->photcode->code != GetPhotcodeEquivCodebyCode (measure[i].photcode)) continue;
	value ++;
      }
      break;
    case AVE_NPHOT:
      value = 0;
      for (i = 0; i < average[0].Nm; i++) {
	if (field->photcode->code != GetPhotcodeEquivCodebyCode (measure[i].photcode)) continue;
	if (measure[i].flags & (ID_MEAS_POOR | ID_MEAS_SKIP)) continue;
	value ++;
      }
      break;
    case AVE_NCRIT:
      break;
  }
  return (value);
}  

