/* This file defines the library functions available to external programs.  It must be included
 * by programs which are compiled against psphot functions.
 */

#ifndef PSPHOT_H
#define PSPHOT_H

#include <psmodules.h>
#include "psphotErrorCodes.h"

#define PSPHOT_RECIPE "PSPHOT" // Name of the recipe to use

#define PSPHOT_RECIPE_PSF_FAKE_ALLOW "PSF.FAKE.ALLOW" // Name for recipe component permitting fake PSFs

// pmPCMData : PSF Convolved Model data storage structure
typedef struct {
    psImage *model;
    psArray *dmodels;
    psImage *modelConv;
    psArray *dmodelsConv;
} pmPCMData;

// top-level psphot functions
const char     *psphotCVSName(void);
psString        psphotVersion(void);
psString        psphotSource(void);
psString        psphotVersionLong(void);
bool            psphotVersionHeader(psMetadata *header);
bool            psphotVersionHeaderFull(psMetadata *header);
void            psphotVersionPrint(void);

bool            psphotModelTest (pmConfig *config, const pmFPAview *view, psMetadata *recipe);
bool            psphotInit (void);
bool            psphotReadout (pmConfig *config, const pmFPAview *view);
bool            psphotReadoutFindPSF(pmConfig *config, const pmFPAview *view, psArray *inSources);
bool            psphotReadoutKnownSources(pmConfig *config, const pmFPAview *view, psArray *inSources);
bool            psphotReadoutMinimal(pmConfig *config, const pmFPAview *view);

bool            psphotReadoutCleanup (pmConfig *config, const pmFPAview *view);
bool            psphotReadoutCleanupReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotDefineFiles (pmConfig *config, pmFPAfile *input);
void            psphotFilesActivate(pmConfig *config, bool state);

bool            psphotSetMaskBits (pmConfig *config);
bool            psphotSetMaskRecipe (pmConfig *config, psImageMaskType maskValue, psImageMaskType markValue);

// XXX test functions
psArray        *psphotFakeSources (void);
bool            psphotMaskCosmicRayFootprintCheck (psArray *sources);

// psphotReadout functions
bool            psphotAddPhotcode (pmConfig *config, const pmFPAview *view);
bool            psphotAddPhotcodeReadout (pmConfig *config, const pmFPAview *view, const char *filerule, int index);

bool            psphotSetMaskAndVariance (pmConfig *config, const pmFPAview *view);
bool            psphotSetMaskAndVarianceReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotModelBackground (pmConfig *config, const pmFPAview *view);
bool            psphotModelBackgroundReadoutFileIndex (pmConfig *config, const pmFPAview *view, const char *filename, int index);

bool            psphotSubtractBackground (pmConfig *config, const pmFPAview *view);
bool            psphotSubtractBackgroundReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotFindDetections (pmConfig *config, const pmFPAview *view, bool firstPass);
bool            psphotFindDetectionsReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe, bool firstPass);

bool            psphotSourceStats (pmConfig *config, const pmFPAview *view, bool setWindow);
bool            psphotSourceStatsReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe, bool setWindow);

bool            psphotDeblendSatstars (pmConfig *config, const pmFPAview *view);
bool            psphotDeblendSatstarsReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index);

bool            psphotBasicDeblend (pmConfig *config, const pmFPAview *view);
bool            psphotBasicDeblendReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index);

bool            psphotRoughClass (pmConfig *config, const pmFPAview *view);
bool            psphotRoughClassReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);
bool            psphotRoughClassRegion (int nRegion, psRegion *region, psArray *sources, psMetadata *analysis, psMetadata *recipe, const bool havePSF);

bool            psphotImageQuality (pmConfig *config, const pmFPAview *view);
bool            psphotImageQualityReadout(pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotChoosePSF (pmConfig *config, const pmFPAview *view);
bool            psphotChoosePSFReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotGuessModels (pmConfig *config, const pmFPAview *view);
bool            psphotGuessModelsReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index);

bool            psphotMergeSources (pmConfig *config, const pmFPAview *view);
bool            psphotMergeSourcesReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index);

bool            psphotFitSourcesLinear (pmConfig *config, const pmFPAview *view, bool final);
bool            psphotFitSourcesLinearReadout (psMetadata *recipe, pmReadout *readout, psArray *sources, pmPSF *psf, bool final);

bool            psphotSourceSize (pmConfig *config, const pmFPAview *view, bool getPSFsize);
bool            psphotSourceSizeReadout(pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe, bool getPSFsize);

bool            psphotBlendFit (pmConfig *config, const pmFPAview *view);
bool            psphotBlendFitReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);
bool            psphotBlendFit_Threaded (psThreadJob *job);

bool            psphotReplaceAllSources (pmConfig *config, const pmFPAview *view);
bool            psphotReplaceAllSourcesReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotAddNoise (pmConfig *config, const pmFPAview *view);
bool            psphotSubNoise (pmConfig *config, const pmFPAview *view);
bool            psphotAddOrSubNoise (pmConfig *config, const pmFPAview *view, bool add);
bool            psphotAddOrSubNoiseReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe, bool add);

bool            psphotExtendedSourceAnalysis (pmConfig *config, const pmFPAview *view);
bool            psphotExtendedSourceAnalysisReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotExtendedSourceFits (pmConfig *config, const pmFPAview *view);
bool            psphotExtendedSourceFitsReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotApResid (pmConfig *config, const pmFPAview *view);
bool            psphotApResidReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotMagnitudes (pmConfig *config, const pmFPAview *view);
bool            psphotMagnitudesReadout(pmConfig *config, psMetadata *recipe, const pmFPAview *view, pmReadout *readout, psArray *sources, pmPSF *psf);
bool            psphotMagnitudes_Threaded (psThreadJob *job);

bool            psphotEfficiency (pmConfig *config, const pmFPAview *view);
bool            psphotEfficiencyReadout(pmConfig *config, const pmFPAview *view, const char *filename, int index, psMetadata *recipe);

bool            psphotPSFWeights(pmConfig *config, pmReadout *readout, const pmFPAview *view, psArray *sources);
bool            psphotPSFWeights_Threaded (psThreadJob *job);

bool            psphotSkyReplace (pmConfig *config, const pmFPAview *view);
bool            psphotSkyReplaceReadout (pmConfig *config, const pmFPAview *view, const char *filename, int index);

bool            psphotSourceFreePixels (pmConfig *config, const pmFPAview *view);
bool            psphotSourceFreePixelsReadout(pmConfig *config, const pmFPAview *view, const char *filename, int index);

// in psphotSourceStats.c:
bool            psphotSourceStats_Threaded (psThreadJob *job);
bool            psphotSourceStatsUpdate (psArray *sources, pmConfig *config, pmReadout *readout);
bool            psphotSetMomentsWindow (psMetadata *recipe, psMetadata *analysis, psArray *sources);

// in psphotChoosePSF.c:
bool            psphotPSFstats (pmReadout *readout, pmPSF *psf);
bool            psphotMomentsStats (pmReadout *readout, psArray *sources);

// in psphotGuessModel.c
bool            psphotGuessModel_Threaded (psThreadJob *job);

// in psphotMergeSources.c:
bool            psphotLoadExtSources (pmConfig *config, const pmFPAview *view);
psArray        *psphotLoadPSFSources (pmConfig *config, const pmFPAview *view);
bool            psphotRepairLoadedSources (pmConfig *config, const pmFPAview *view);
bool            psphotCheckExtSources (pmConfig *config, const pmFPAview *view);

// generate the detection structure for the supplied array of sources
bool            psphotDetectionsFromSources (pmConfig *config, const pmFPAview *view, psArray *sources);

// generate the detection structure for the supplied array of sources
bool            psphotSetSourceParams (pmConfig *config, psArray *sources, pmPSF *psf);

// in psphotModelBackground.c:
// Create a background model for a readout, without saving the result as a pmFPAfile on config->files.  Otherwise identical to psphotModelBackgroundFileIndex.
psImage        *psphotModelBackgroundReadoutNoFile(pmReadout *readout, const pmConfig *config);
psImageBinning *psphotBackgroundBinning(const psImage *image, const pmConfig *config);

// in psphotReplaceUnfit.c:
bool            psphotRemoveAllSources (const psArray *sources, const psMetadata *recipe);
bool            psphotReplaceUnfitSources (psArray *sources, psImageMaskType maskVal);

// thread-related:
bool            psphotSetThreads (void);
bool            psphotChooseCellSizes (int *Cx, int *Cy, pmReadout *readout, int nThreads);
bool            psphotCoordToCell (int *group, int *cell, float x, float y, int Cx, int Cy);
psArray        *psphotAssignSources (int Cx, int Cy, psArray *sources);

// used by psphotFindDetections
psImage        *psphotSignificanceImage (pmReadout *readout, psMetadata *recipe, const int pass, psImageMaskType maskVal);
psArray        *psphotFindPeaks (psImage *significance, pmReadout *readout, psMetadata *recipe, const float threshold, const int nMax);
bool            psphotFindFootprints (pmDetections *detections, psImage *significance, pmReadout *readout, psMetadata *recipe, const float threshold, const int pass, psImageMaskType maskVal);
psErrorCode     psphotCullPeaks(const pmReadout *readout, const psMetadata *recipe, psArray *footprints);

// in psphotApResid.c:
pmTrend2D      *psphotApResidTrend (float *apResidSysErr, pmReadout *readout, int Nx, int Ny, psVector *xPos, psVector *yPos, psVector *apResid, psVector *dMag);
bool            psphotApResidMags_Threaded (psThreadJob *job);

// basic support functions
void            psphotModelClassInit (void);
bool            psphotGrowthCurve (pmReadout *readout, pmPSF *psf, bool ignore, psImageMaskType maskVal);

// functions to set the correct source pixels
bool            psphotInitRadiusPSF(const psMetadata *recipe, const psMetadata *analysis, const pmModelType type);

bool            psphotCheckRadiusPSF (pmReadout *readout, pmSource *source, pmModel *model, psImageMaskType markVal);
bool            psphotCheckRadiusPSFBlend (pmReadout *readout, pmSource *source, pmModel *model, psImageMaskType markVal, float dR);
bool            psphotInitRadiusEXT (psMetadata *recipe, pmModelType type);
bool            psphotCheckRadiusEXT (pmReadout *readout, pmSource *source, pmModel *model, psImageMaskType markVal);
float           psphotSetRadiusEXT (pmReadout *readout, pmSource *source, psImageMaskType markVal);

bool            psphotDumpMoments (psMetadata *recipe, psArray *sources);
psMetadata     *psphotDefineHeader (psMetadata *recipe);
int             psphotSaveImage (psMetadata *header, psImage *image, char *filename);
bool            psphotDumpConfig (pmConfig *config);
pmReadout      *psphotSelectBackground (pmConfig *config, const pmFPAview *view);
pmReadout      *psphotSelectBackgroundStdev (pmConfig *config, const pmFPAview *view);

// PSF / DBL / EXT evaluation functions
bool            psphotEvalPSF (pmSource *source, pmModel *model);
bool            psphotEvalDBL (pmSource *source, pmModel *model);
bool            psphotEvalEXT (pmSource *source, pmModel *model);

//  functions to support the source fitting process
bool            psphotInitLimitsPSF (psMetadata *recipe, pmReadout *readout);
bool            psphotInitLimitsEXT (psMetadata *recipe);
bool            psphotFitBlend (pmReadout *readout, pmSource *source, pmPSF *psf, psImageMaskType maskVal, psImageMaskType markVal);
bool            psphotFitBlob (pmReadout *readout, pmSource *source, psArray *sources, pmPSF *psf, psImageMaskType maskVal, psImageMaskType markVal);
bool            psphotFitPSF (pmReadout *readout, pmSource *source, pmPSF *psf, psImageMaskType maskVal, psImageMaskType markVal);
pmModel        *psphotFitEXT (pmReadout *readout, pmSource *source, pmModelType modelType, psImageMaskType maskVal, psImageMaskType markVal);
psArray        *psphotFitDBL (pmReadout *readout, pmSource *source, psImageMaskType maskVal, psImageMaskType markVal);

// functions to support simultaneous multi-source fitting
bool            psphotFitSet (pmSource *oneSrc, pmModel *oneModel, char *fitset, pmSourceFitMode mode, psImageMaskType maskVal);

// plotting functions (available if libkapa is installed)
bool            psphotPlotMoments (pmConfig *config, pmFPAview *view, psArray *sources);
bool            psphotPlotPSFModel (pmConfig *config, pmFPAview *view, psArray *sources);
bool            psphotFitInit (int nThreads);
bool            psphotFitSummary (void);

bool            psphotLoadPSF (pmConfig *config, const pmFPAview *view);
bool            psphotLoadPSFReadout (pmConfig *config, const pmFPAview *view, const char *outFilename, const char *inFilename, int index);

bool            psphotSetHeaderNstars (psMetadata *recipe, psArray *sources);
bool            psphotRadialPlot (int *kapa, const char *filename, pmSource *source);
bool            psphotSourcePlots (pmReadout *readout, psArray *sources, psMetadata *recipe);
bool            psphotMosaicSubimage (psImage *outImage, pmSource *source, int Xo, int Yo, int DX, int DY, bool normalize);

bool            psphotMakeResiduals (psArray *sources, psMetadata *recipe, pmPSF *psf, psImageMaskType maskVal);

pmModel        *psphotPSFConvModel (pmReadout *readout, pmSource *source, pmModelType modelType, psImageMaskType maskVal, psImageMaskType markVal, int psfSize);

psKernel       *psphotKernelFromPSF (pmSource *source, int nPix);

// functions related to extended source analysis
bool            psphotRadialProfile (pmSource *source, psMetadata *recipe, float skynoise, psImageMaskType maskVal);
bool            psphotRadialProfilesByAngles (pmSource *source, int Nsec, float Rmax);
float           psphotRadiusFromProfile (pmSource *source, psVector *radius, psVector *flux, float fluxMin, float fluxMax);
bool            psphotRadiiFromProfiles (pmSource *source, float fluxMin, float fluxMax);
bool            psphotEllipticalProfile (pmSource *source, bool RAW_RADIUS);
bool            psphotEllipticalContour (pmSource *source);

// psphotVisual functions
bool            psphotVisualShowImage (pmReadout *readout);
bool            psphotVisualShowBackground (pmConfig *config, const pmFPAview *view, pmReadout *readout);
bool            psphotVisualShowSignificance (psImage *image, float min, float max);
bool            psphotVisualShowPeaks (pmDetections *detections);
bool            psphotVisualShowFootprints (pmDetections *detections);
bool            psphotVisualShowMoments (psArray *sources);
bool            psphotVisualPlotMoments (psMetadata *recipe, psMetadata *analysis, psArray *sources);
bool            psphotVisualShowRoughClass (psArray *sources);
bool            psphotVisualShowPSFStars (psMetadata *recipe, pmPSF *psf, psArray *sources);
bool            psphotVisualShowSatStars (psMetadata *recipe, pmPSF *psf, psArray *sources);
bool            psphotVisualShowPSFModel (pmReadout *readout, pmPSF *psf);
bool            psphotVisualPlotRadialProfile (int myKapa, pmSource *source, psImageMaskType maskVal);
bool            psphotVisualPlotRadialProfiles (psMetadata *recipe, psArray *sources);
bool            psphotVisualShowFlags (psArray *sources);
bool            psphotVisualShowSourceSize (pmReadout *readout, psArray *sources);
bool            psphotVisualShowResidualImage (pmReadout *readout);
bool            psphotVisualPlotApResid (psArray *sources, float mean, float error);
bool            psphotVisualPlotChisq (psArray *sources);
bool            psphotVisualPlotSourceSize (psMetadata *recipe, psMetadata *analysis, psArray *sources);
bool            psphotVisualShowPetrosians (psArray *sources);
bool            psphotVisualEraseOverlays (int channel, char *overlay);

bool psphotPetrosian (pmSource *source, psMetadata *recipe, float skynoise, psImageMaskType maskVal);
bool psphotPetrosianRadialBins (pmSource *source, float radiusMax, float skynoise);
bool psphotPetrosianStats (pmSource *source);

// currently disabled:
// bool            psphotIsophotal (pmSource *source, psMetadata *recipe, psImageMaskType maskVal);
// bool            psphotAnnuli (pmSource *source, psMetadata *recipe, psImageMaskType maskVal);
// bool            psphotKron (pmSource *source, psMetadata *recipe, psImageMaskType maskVal);

// XXX visualization functions related to radial profiles (disabled)
bool psphotPetrosianVisualProfileByAngle (psVector *radius, psVector *flux);
bool psphotPetrosianVisualProfileRadii (psVector *radius, psVector *flux, psVector *radiusBin, psVector *fluxBin, float peakFlux, float RadiusRef);
bool psphotPetrosianVisualEllipticalContour (pmSourceRadialFlux *radFlux, pmSourceExtendedPars *extpars);
bool psphotPetrosianVisualStats (psVector *radBin, psVector *fluxBin,
                               psVector *refRadius, psVector *meanSB,
                               psVector *petRatio, psVector *petRatioErr, psVector *fluxSum,
                               float petRadius, float ratioForRadius,
                               float petFlux, float radiusForFlux);

bool psphotRadialBins (psMetadata *recipe, pmSource *source, float radiusMax, float skynoise);

// structures & functions to support psf-convolved model fitting

// psf-convolved model fitting
bool psphotModelWithPSF_LMM (
    psMinimization *min,
    psImage *covar,
    psVector *params,
    psMinConstraint *constraint,
    pmSource *source,
    const psKernel *psf,
    psMinimizeLMChi2Func func);

psF32 psphotModelWithPSF_SetABX(
    psImage  *alpha,
    psVector *beta,
    const psVector *params,
    const psVector *paramMask,
    pmPCMData *pcm,
    const pmSource *source,
    const psKernel *psf,
    psMinimizeLMChi2Func func);

pmPCMData *pmPCMDataAlloc (
    const psVector *params,
    const psVector *paramMask,
    pmSource *source);

psImage *pmPCMDataSaveImage (pmPCMData *pcm);

int psphotKapaOpen (void);
bool psphotKapaClose (void);
bool psphotImageBackgroundCellHistogram (psVector *values, float mean, float sigma, int ix, int iy);
bool psphotDiagnosticPlots (const pmConfig *config, const char *name, ...);

bool psphotMakeFluxScale (psImage *image, psMetadata *recipe, pmPSF *psf);
bool psphotMakeGrowthCurve (pmReadout *readout, psMetadata *recipe, pmPSF *psf);
bool psphotDumpPSFStars (pmReadout *readout, pmPSFtry *try, float radius, psImageMaskType maskVal, psImageMaskType markVal);

bool psphotLoadSRCTEXT (pmFPA *fpa, pmConfig *config);

bool psphotCheckStarDistribution (psArray *sources, psArray *stars, pmPSFOptions *options);
int psphotSupplementStars (psArray *stars, psArray *sources, psImageBinning *binning, int ix, int iy);

pmConfig *psphotForcedArguments(int argc, char **argv);
bool psphotForcedImageLoop (pmConfig *config);
bool psphotForcedReadout(pmConfig *config, const pmFPAview *view);

pmConfig *psphotMakePSFArguments(int argc, char **argv);
bool psphotMakePSFImageLoop (pmConfig *config);
bool psphotMakePSFReadout(pmConfig *config, const pmFPAview *view);

/**** psphotStack prototypes ****/

pmConfig *psphotStackArguments(int argc, char **argv);
bool psphotStackParseCamera (pmConfig *config);
bool psphotStackImageLoop (pmConfig *config);
bool psphotStackReadout (pmConfig *config, const pmFPAview *view);
bool psphotStackChisqImage (pmConfig *config, const pmFPAview *view);
bool psphotStackChisqImageAddReadout(const pmConfig *config, // Configuration
				     const pmFPAview *view,
				     pmReadout **chiReadout,
				     char *filename, 
				     int index);

bool psphotStackRemoveChisqFromInputs (pmConfig *config);
bool pmFPAfileRemoveSingle(psMetadata *files, const char *name, int num);

psArray *psphotMatchSources (pmConfig *config, const pmFPAview *view);
bool psphotMatchSourcesReadout (psArray *objects, pmConfig *config, const pmFPAview *view, char *filename, int index);
bool psphotMatchSourcesToObjects (psArray *objects, psArray *sources, float RADIUS);

bool psphotFitSourcesLinearStack (pmConfig *config, psArray *objects, bool final);
int pmPhotObjSortBySN (const void **a, const void **b);
int pmPhotObjSortByX (const void **a, const void **b);

#endif
