# include "psphotInternal.h"

bool psphotRadialProfile (pmSource *source, psMetadata *recipe, float skynoise, psImageMaskType maskVal) {

    bool status;

    // allocate pmSourceExtendedParameters, if not already defined
    if (!source->extpars) {
        source->extpars = pmSourceExtendedParsAlloc ();
    }

    // XXX these need to go into recipe values
    int Nsec = 24;
    float Rmax = 200;
    float fluxMin = 0.0;
    float fluxMax = source->peak->flux;

    bool RAW_RADIUS = psMetadataLookupBool (&status, recipe, "EXTENDED_SOURCE_RAW_RADIUS");

    // generate a series of radial profiles at Nsec evenly spaced angles.  the profile flux
    // is measured by interpolation for small radii; for large radii, the pixels in a box
    // are averaged to increase the S/N
    if (!psphotRadialProfilesByAngles (source, Nsec, Rmax)) {
	psError (PS_ERR_UNKNOWN, false, "failed to measure radial profile for petrosian");
	return false;
    }

    // use the radial profiles to determine the radius of a given isophote.  this isophote
    // is used to determine the elliptical shape of the object, so it has a relatively high
    // value (nominally 25% of the peak)
    if (!psphotRadiiFromProfiles (source, fluxMin, fluxMax)) {
	psError (PS_ERR_UNKNOWN, false, "failed to measure isophotal radii from profiles");
	return false;
    }

    // convert the isophotal radius vs angle measurements to an elliptical contour
    if (!psphotEllipticalContour (source)) {
	psLogMsg ("psphot", 3, "failed to measure elliptical contour");
	return false;
    }
  
    // generate a single, normalized radial profile following the elliptical contours.
    // the radius is normalized by the axis ratio so that on the major axis, 1 pixel = 1 pixel
    if (!psphotEllipticalProfile (source, RAW_RADIUS)) {
	psError (PS_ERR_UNKNOWN, false, "failed to generate elliptical profile");
	return false;
    }
  
    // generated profile in averaged bins
    if (!psphotRadialBins (recipe, source, Rmax, skynoise)) {
	psError (PS_ERR_UNKNOWN, false, "failed to generate radial bins");
	return false;
    }
  
    return true;
}
