#include "pswarp.h"
#include <ppStats.h>

bool pswarpMaskStats(const pmReadout *readout, psMetadata *stats, const pmConfig *config) {
  PS_ASSERT_PTR_NON_NULL(readout, false);
  PS_ASSERT_PTR_NON_NULL(config, false);

  bool status;
  psMetadata *recipe = psMetadataLookupMetadata(&status, config->recipes, PSWARP_RECIPE);
  psU16 staticMaskVal = psMetadataLookupU32(&status, recipe, "MASKSTAT.STATIC");
  psU16 magicMaskVal = psMetadataLookupU32(&status, recipe, "MASKSTAT.MAGIC");
  psU16 dynamicMaskVal = psMetadataLookupU32(&status, recipe, "MASKSTAT.DYNAMIC");
  psU16 advisoryMaskVal = psMetadataLookupU32(&status, recipe, "MASKSTAT.ADVISORY");

  psS32 Npix_valid = 0;
  psS32 Npix_static = 0;
  psS32 Npix_magic = 0;
  psS32 Npix_dynamic = 0;
  psS32 Npix_advisory = 0;

  if (!readout || !readout->data_exists) {
    // Nothing to process
    return(true);
  }
  psWarning("pswarpMaskStats: %d %d %d %d\n",staticMaskVal,magicMaskVal,dynamicMaskVal,advisoryMaskVal);
  psImage *mask = readout->mask;  // Mask of interest;
  if (!pmSingleImageMaskStats(mask,&Npix_valid,&Npix_static,&Npix_magic,
			      &Npix_dynamic,&Npix_advisory,
			      staticMaskVal,magicMaskVal,
			      dynamicMaskVal,advisoryMaskVal)) {
    psError(PS_ERR_UNKNOWN, false, "Unable to calculate masks for readout.");
    return(false);
  }
  psMetadataAddS32(stats, PS_LIST_TAIL,"MASKFRAC_NPIX", 0,
		   "Number of valid pixels", Npix_valid);
  psMetadataAddF32(stats,PS_LIST_TAIL, "MASKFRAC_STATIC", 0,
		   "Fraction of pixels statically masked", (float) Npix_static / Npix_valid);
  psMetadataAddF32(stats,PS_LIST_TAIL, "MASKFRAC_DYNAMIC", 0,
		   "Fraction of pixels dynamically masked", (float) Npix_dynamic / Npix_valid);
  psMetadataAddF32(stats,PS_LIST_TAIL, "MASKFRAC_MAGIC", 0,
		   "Fraction of pixels magically masked", (float) Npix_magic / Npix_valid);
  psMetadataAddF32(stats,PS_LIST_TAIL, "MASKFRAC_ADVISORY", 0,
		   "Fraction of pixels masked as an advisory", (float) Npix_advisory / Npix_valid);
  return(true);
}
