/* $Id: vimos_ima_standard.c,v 1.31 2015/11/27 12:15:33 jim Exp $
 *
 * This file is part of the VIMOS Pipeline
 * Copyright (C) 2015 European Southern Observatory
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * $Author: jim $
 * $Date: 2015/11/27 12:15:33 $
 * $Revision: 1.31 $
 * $Name:  $
 */

/* Includes */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <libgen.h>
#include <string.h>

#include <cpl.h>
#include <math.h>

#include "vmutils.h"
#include "vimos_imaging_utils.h"
#include "vimos_pfits.h"
#include "vimos_dfs.h"
#include "vimos_mods.h"
#include "vimos_var.h"
#include "casu_utils.h"
#include "casu_stats.h"
#include "casu_fits.h"
#include "casu_mask.h"
#include "casu_wcsutils.h"
#include "casu_mods.h"

/* Structure definitions */

typedef struct {

    /* Input */

    int         preview_only;
    int         minphotom;
    int         prettynames;
    int         cdssearch_astrom;
    int         cdssearch_photom;
    int         savemstd;
    int         ignore_fringe;
    char        *cacheloc;
    float       magerrcut;

    /* Source catalogue extraction parameters */

    int         src_cat_ipix;
    float       src_cat_thresh;
    int         src_cat_icrowd;
    float       src_cat_rcore;
    int         src_cat_nbsize;

} configstruct;

typedef struct {
    cpl_size         *labels;
    cpl_size         *labels2;
    cpl_frame        *master_bias;
    cpl_frame        *master_dark;
    cpl_frame        *master_twilight_flat;
    cpl_frame        *master_conf;
    cpl_frame        *master_fringe;
    cpl_frame        *master_fringe_var;
    cpl_frame        *readgain;
    casu_mask        *mask;
    cpl_frame        *phottab;
    cpl_table        *tphottab;
    cpl_frameset     *science_frames;
    cpl_frame        **product_frames_simple;
    cpl_frame        **product_frames_vars;
    cpl_frame        **product_frames_cats;
    cpl_frame        **product_frames_mstd_a;
    cpl_frame        **product_frames_mstd_p;
    float            *gaincors;
    char             *catpath_a;
    char             *catname_a;
    char             *catpath_p;
    char             *catname_p;
    cpl_frame        *schlf_n;
    cpl_frame        *schlf_s;
    casu_fits        *dummyfits;

    /* Level 1 stuff */

    casu_fits        *fbias;
    casu_fits        *fdark;
    casu_fits        *fflat;
    casu_fits        *fconf;
    casu_fits        *ffringe;
    casu_fits        *ffringe_var;

    int              nscience;
    casu_fits        *sci_fits[VIMOS_NEXTN];
    casu_fits        *sci_vars[VIMOS_NEXTN];
    casu_tfits       *sci_cats[VIMOS_NEXTN];
    casu_tfits       *sci_mstd_a[VIMOS_NEXTN];
    casu_tfits       *sci_mstd_p[VIMOS_NEXTN];

} memstruct;

/* List of data products types */

enum {SIMPLE_FILE,
      SIMPLE_VAR,
      SIMPLE_CAT,
      MSTDS_ASTROM,
      MSTDS_PHOTOM
};

/* Recipe name */

#define VIMOS_RECIPENAME "vimos_ima_standard"

/* Function prototypes */

static int vimos_ima_standard_create(cpl_plugin *) ;
static int vimos_ima_standard_exec(cpl_plugin *) ;
static int vimos_ima_standard_destroy(cpl_plugin *) ;
static int vimos_ima_standard(cpl_parameterlist *, cpl_frameset *) ;

static int vimos_std_save_simple(casu_fits *obj, cpl_frameset *framelist,
                                 cpl_parameterlist *parlist, 
                                 cpl_frame *template, int isfirst,
                                 const char *tag, char *fname, char *cname,
                                 char *assoc, char *photosys,
                                 cpl_frame **product_frame);
static int vimos_std_save_cat(casu_tfits *obj, cpl_frameset *framelist,
                              cpl_parameterlist *parlist, 
                              cpl_frame *template, int isfirst,
                              const char *tag, char *fname, char *cname,
                              char *photosys, cpl_frame **product_frame);
static void vimos_std_product_name(char *template, int producttype, 
                                   int nametype, int fnumber, char *outfname);

static void vimos_std_init(memstruct *ps);
static void vimos_std_tidy(memstruct *ps, int level);

static char vimos_ima_standard_description[] =
"vimos_ima_standard -- VIMOS standard star recipe.\n\n"
"Take a list of standard frames and correct them to remove bias, dark\n"
"and flat field signatures. Optionally defringe the reddest filter\n"
"images. Astrometrically and photometrically calibrate the individual\n"
"images, but do no stacking\n\n"
"The program accepts the following files in the SOF:\n\n"
"    Tag                   Description\n"
"    -----------------------------------------------------------------------\n"
"    %-21s A list of raw standard images\n"
"    %-21s A master bias frame\n"
"    %-21s A master dark frame\n"
"    %-21s A master flat frame\n"
"    %-21s A master confidence map\n"
"    %-21s A master fringe map (optional)\n"
"    %-21s A master fringe variance map (optional)\n"
"    %-21s A master readgain table\n"
"    %-21s A master 2MASS index for astrometry or\n"
"    %-21s A master PPMXL index for astrometry or\n"
"    %-21s A master APASS index for astrometry or\n"
"    %-21s A master local catalogue index for astrometry\n"
"    %-21s A master APASS index for photometry or\n"
"    %-21s A master local catalogue index for photometry\n"
"    %-21s A photometric calibration table\n"
"    %-21s Northern Schlegel Map\n"
"    %-21s Southern Schlegel Map\n"
"All of these are required unless specified otherwise."
"\n";

/**@{*/

/**
    \ingroup recipelist
    \defgroup vimos_ima_standard vimos_ima_standard
    \brief VIMOS standard recipe

    \par Name: 
        vimos_ima_standard
    \par Purpose: 
        Reduce a full pawprint of VIMOS standard data
    \par Description: 
        A single sequence of VIMOS standard data in a single filter is 
        corrected for instrumental signature. The images are not stacked.
        All images are astrometrically calibrated using a standard astrometric
        catalogue and photometrically calibrated using either the APASS
        catalogue or a local catalogue.
    \par Language:
        C
    \par Parameters:
        - General reduction parameters:
            - \b preview_only (bool): If set we only get a preview of the reduction
            - \b minphotom (int): The minimum number of standards for photometry
            - \b prettynames (bool): True if we're using nice file names       
            - \b savemstd (bool) True if we're going to save the matched 
                 standards catalogues for astrometry and photometry
            - \b cdssearch_astrom (string): Use CDS for astrometric standards?
                - none: Use no CDS catalogues. Use local catalogues instead
                - 2mass: 2MASS PSC
                - usnob: USNOB catalogue
                - ppmxl: PPMXL catalogue
                - wise: WISE catalogue
            - \b cdssearch_photom (string): Use CDS for photometric standards?
                - none: Use no CDS catalogues. Use local catalogues instead
                - apass: APASS catalogue
            - \b ignore_fringe (bool): Flag to ignore a provided fringe frame
            - \b cacheloc (string): A directory where we can put the standard
                 star cache
            - \b magerrcut (float): A cut in the magnitude error for 
                 photometric standard stars
        - Parameters for source detection on exposure frames:
            - \b src_cat_ipix (int): The minimum allowable size of an object
            - \b src_cat_thresh (float): The detection threshold in sigma above sky
            - \b src_cat_icrowd (int): If set then the deblending software will be used
            - \b src_cat_rcore (float): The core radius in pixels
            - \b src_cat_nbsize (int): The smoothing box size for background map estimation        
    \par Input File Types:
        The following list gives the file types that can appear in the SOF
        file. The word in bold is the DO category value.
        - \b STD (required): A list of raw standard images for processing
        - \b MASTER_BIAS (required): A master bias frame. This is needed 
             for the bias correction of the input images.
        - \b MASTER_DARK (required): A master dark frame. This is needed 
             for the dark correction of the input images.
        - \b MASTER_TWILIGHT_FLAT (required): A master twilight flat frame
             appropriate for the filter used in the science observations.
             This is used to remove the flat field effects from the science
             frames and also for the detector level gain correction.
        - \b MASTER_FRINGE (optional): A master fringe map
        - \b MASTER_FRINGE_VAR (optional): A master fringe variance map
        - \b MASTER_READGAIN (required): A master read/gain table
        - \b MASTER_CONF (required): A master confidence map 
             appropriate for the filter used in the science observations.
             This is used for weighting and to mark bad pixels.
        - \b MASTER_2MASS_CATLAOGUE_ASTROM or \b MASTER_PPMXL_CATALOGUE_ASTROM
             or \b MASTER_APASS_CATALOGUE_ASTROM or \b MASTER_LOCCAT_ASTROM
             (required): A master standard star catalogue for astrometry
        - \b MASTER_APASS_CATALOGUE_PHOTOM or \b MASTER_LOCCAT_PHOTOM
             (required): A master standard star catalogue for photometry
        - \b SCHLEGEL_MAP_NORTH (required): The Northern Schlegel dust map
        - \b SCHLEGEL_MAP_SOUTH (required): The Southern Schlegel dust map
    \par Output Products:
        The following list gives the output data products that are generated
        by this recipe. The word in bold gives the DPR CATG keyword value for
        each product:
        - The instrumentally corrected and astrometerically calibrated 
          individual science exposures. (\b BASIC_CALIBRATED_STD).
        - The variance maps for the calibrated individual science
          exposures. (\b BASIC_VAR_MAP_STD).
        - The source catalogue for a calibrated input image
          (\b OBJECT_CATALOGUE_STD).
        - A matched standards catalogue for astrometry, if desired
          (\b MATCHSTD_ASTROM)
        - A matched standards catalogue for photometry, if desired
          (\b MATCHSTD_PHOTOM)
    \par Output QC Parameters:
        - \b SATURATION
             The saturation level in ADUs.
        - \b MEAN_SKY
             The mean level of the background sky over the image in ADUs.
        - \b SKY_NOISE
             The RMS of the background sky over the image in ADUs
        - \b IMAGE_SIZE
             The average size of stellar images on the image in pixels
        - \b ELLIPTICITY
             The average ellipticity of stellar images on the image
        - \b POSANG
             The average position angle in degrees from North towards East.
             NB: this value only makes sense if the ellipticity is significant
        - \b APERTURE_CORR
             The aperture correction for an aperture of radius rcore.
        - \b NOISE_OBJ
             The number of noise objects found in the image
        - \b MAGZPT
             The photometric zero point
        - \b MAGZERR
             The internal error in the photometric zero point
        - \b MAGNZPT
             The number of stars used to determine the magnitude zero point
        - \b MAGNCUT
             The number of stars cut from magnitude zero point calculation
        - \b SKYBRIGHT
             The sky brightness in mag/arcsec**2
        - \b LIMITING_MAG
             The limiting magnitude for this image for a 5 sigma detection.
        - \b WCS_DCRVAL1
             The offset of the equatorial coordinate represented by CRVAL1 
             from the raw frame to the reduced one (degrees).
        - \b WCS_DCRVAL2
             The offset of the equatorial coordinate represented by CRVAL2
             from the raw frame to the reduced one (degrees).
        - \b WCS_DTHETA
             The change in the WCS coordinate system rotation from the raw
             to the reduced frame (degrees)
        - \b WCS_SCALE
             The scale of the pixels in the reduced frames in arcseconds per
             pixel
        - \b WCS_SHEAR
             The shear of the astrometric solution in the form of the 
             difference between the rotation of the x solution and the rotation
             of the y solution (abs(xrot) - abs(yrot) in degrees)
        - \b WCS_RMS
             The average error in the WCS fit (arcsec)
    \par Notes
        None.
    \par Fatal Error Conditions:
        - NULL input frameset
        - Input frameset headers incorrect meaning that RAW and CALIB frame
          can't be distinguished
        - No standard frames in the input frameset
        - No master bias, dark, flat or confidence map frame in input frameset
        - Unable to save data products
        - Unable to load images
    \par Non-Fatal Error Conditions:
        - None
    \par Conditions Leading To Dummy Products:
        - Master calibration images flagged as dummys
        - Detector for the current image is flagged as dead in all 
          standard images
        - Failure of one of the processing steps
    \par Author:
        Jim Lewis, CASU
    \par Code Reference: 
        vimos_ima_standard.c
*/

/* Function code */

/*---------------------------------------------------------------------------*/
/**
  @brief    Build the list of available plugins, for this module.
  @param    list    the plugin list
  @return   0 if everything is ok

  This function is exported.
 */
/*---------------------------------------------------------------------------*/

int cpl_plugin_get_info(cpl_pluginlist *list) {
    cpl_recipe  *recipe = cpl_calloc(1,sizeof(*recipe));
    cpl_plugin  *plugin = &recipe->interface;
    char alldesc[SZ_ALLDESC];
    (void)snprintf(alldesc,SZ_ALLDESC,vimos_ima_standard_description,
                   VIMOS_STD_OBJECT_RAW,VIMOS_CAL_BIAS,VIMOS_CAL_DARK,
                   VIMOS_CAL_TWILIGHT_FLAT,VIMOS_CAL_CONF,VIMOS_CAL_FRINGE,
                   VIMOS_CAL_FRINGE_VAR,VIMOS_CAL_READGAIN,VIMOS_CAL_2MASS_A,
                   VIMOS_CAL_PPMXL_A,VIMOS_CAL_APASS_A,VIMOS_CAL_LOCCAT_A,
                   VIMOS_CAL_APASS_P,VIMOS_CAL_LOCCAT_P,VIMOS_CAL_PHOTTAB,
                   VIMOS_CAL_SCHL_N,VIMOS_CAL_SCHL_S);

    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    VIMOS_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "vimos_ima_standard",
                    "Standard field processing for imaging",
                    alldesc,
                    "Jim Lewis",
                    "jrl@ast.cam.ac.uk",
                    vimos_get_license(),
                    vimos_ima_standard_create,
                    vimos_ima_standard_exec,
                    vimos_ima_standard_destroy);

    cpl_pluginlist_append(list,plugin);

    return(0);
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options
  @param    plugin  the plugin
  @return   0 if everything is ok

  Create the recipe instance and make it available to the application using the
  interface.
 */
/*---------------------------------------------------------------------------*/

static int vimos_ima_standard_create(cpl_plugin *plugin) {
    cpl_recipe      *recipe;
    cpl_parameter   *p;

    /* Get the recipe out of the plugin */

    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE)
        recipe = (cpl_recipe *)plugin;
    else 
        return(-1);

    /* Create the parameters list in the cpl_recipe object */

    recipe->parameters = cpl_parameterlist_new();

    /* Fill in flag to just print out how the data will be processed and 
       then exit */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.preview_only",
                                CPL_TYPE_BOOL,"Preview only?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"preview_only");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in flag to just print out how the data will be processed and 
       then exit */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.minphotom",
                                CPL_TYPE_INT,
                                "Minimum stars for photometry solution",
                                "vimos.vimos_ima_standard",1,1,100000);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"minphotom");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in flag to decide whether use predictable names or nice
       names based on input file names */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.prettynames",
                                CPL_TYPE_BOOL,"Use pretty product names?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"prettynames");
    cpl_parameterlist_append(recipe->parameters,p);
 
    /* Fill in flag to use save the matched standard catalogues */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.savemstd",
                                CPL_TYPE_BOOL,
                                "Save matched standard catalogues?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"savemstd");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Flag to decide how we get the astrometric standard star information. If 
       none, then use the local catalogues specified in the sof. If not none, 
       then use one of the selection of catalogues available from CDS */

    p = cpl_parameter_new_enum("vimos.vimos_ima_standard.cdssearch_astrom",
                               CPL_TYPE_STRING,
                               "CDS astrometric catalogue",
                               "vimos.vimos_ima_standard",
                               "none",5,"none","2mass","usnob","ppmxl","wise");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"cdssearch_astrom");
    cpl_parameterlist_append(recipe->parameters,p);

    /* The same for photometric standards */

    p = cpl_parameter_new_enum("vimos.vimos_ima_standard.cdssearch_photom",
                               CPL_TYPE_STRING,
                               "CDS photometric catalogue",
                               "vimos.vimos_ima_standard",
                               "none",2,"none","apass");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"cdssearch_photom");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Flag to ignore the provided fringe frame */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.ignore_fringe",
                                CPL_TYPE_BOOL,"Ignore provided fringe frame?",
                                "vimos.vimos_ima_standard",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"ignore_fringe");
    cpl_parameterlist_append(recipe->parameters,p);

   /* ***Special parameters for object detection*** */

    /* Fill in the minimum object size */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_ipix",
                                CPL_TYPE_INT,
                                "Minimum pixel area for each detected object",
                                "vimos.vimos_ima_standard",5,1,100000);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_ipix");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in the detection threshold parameter */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_thresh",
                                CPL_TYPE_DOUBLE,
                                "Detection threshold in sigma above sky",
                                "vimos.vimos_ima_standard",2.5,1.0e-6,
                                1.0e10);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_thresh");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in flag to use deblending software or not */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.src_cat_icrowd",
                                CPL_TYPE_BOOL,"Use deblending?",
                                "vimos.vimos_ima_standard",TRUE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_icrowd");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in core radius */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_rcore",
                                CPL_TYPE_DOUBLE,"Value of Rcore in pixels",
                                "vimos.vimos_ima_standard",5.0,1.0e-6,
                                1024.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_rcore");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Fill in background smoothing box size */

    p = cpl_parameter_new_range("vimos.vimos_ima_standard.src_cat_nbsize",
                                CPL_TYPE_INT,"Background smoothing box size",
                                "vimos.vimos_ima_standard",128,1,2048);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"src_cat_nbsize");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Location for standard star cache */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.cacheloc",
                                CPL_TYPE_STRING,
                                "Location for standard star cache",
                                "vimos.vimos_ima_standard",".");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"cacheloc");
    cpl_parameterlist_append(recipe->parameters,p);  

    /* A cut in the magnitude error */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.magerrcut",
                                CPL_TYPE_DOUBLE,
                                "A cut in the magnitude error",
                                "vimos.vimos_ima_standard",100.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"magerrcut");
    cpl_parameterlist_append(recipe->parameters,p);  


    /* STD stars with magnitudes BRIGHTER than this are removed. */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.lthr_mag",
                                CPL_TYPE_DOUBLE,
                                "STD stars with magnitudes BRIGHTER than this are removed.",
                                "vimos.vimos_ima_standard",15.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"lthr_mag");
    cpl_parameterlist_append(recipe->parameters,p);

    /* STD stars with magnitudes FAINTER than this are removed. */

    p = cpl_parameter_new_value("vimos.vimos_ima_standard.hthr_mag",
                                CPL_TYPE_DOUBLE,
                                "STD stars with magnitudes FAINTER than this are removed.",
                                "vimos.vimos_ima_standard",32.0);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"hthr_mag");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Get out of here */

    return(0);
}
        
/*---------------------------------------------------------------------------*/
/**
  @brief    Execute the plugin instance given by the interface
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int vimos_ima_standard_exec(cpl_plugin *plugin) {
    cpl_recipe  *recipe;

    /* Get the recipe out of the plugin */

    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE)
        recipe = (cpl_recipe *)plugin;
    else 
        return(-1);

    return(vimos_ima_standard(recipe->parameters,recipe->frames));
}
                                
/*---------------------------------------------------------------------------*/
/**
  @brief    Destroy what has been created by the 'create' function
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int vimos_ima_standard_destroy(cpl_plugin *plugin) {
    cpl_recipe *recipe ;

    /* Get the recipe out of the plugin */

    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE)
        recipe = (cpl_recipe *)plugin;
    else 
        return(-1);

    cpl_parameterlist_delete(recipe->parameters);
    return(0);
}

/*---------------------------------------------------------------------------*/
/**
  @brief    The recipe data reduction part is implemented here 
  @param    parlist     the parameters list
  @param    framelist   the frames list
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int vimos_ima_standard(cpl_parameterlist *parlist, 
                                  cpl_frameset *framelist) {
    const char *fctid="vimos_ima_standard";
    configstruct cs;
    memstruct ps;
    cpl_parameter *p;
    cpl_size nlab,nlab2;
    int nfail,status,i,j,isfirst,n,match;
    float gaincor_fac,texp,gain,readnoise,fac;
    cpl_frame *catindex_a,*catindex_p,*frm,*tmpl;
    cpl_frameset *chiplist;
    cpl_image *dummyim;
    cpl_propertylist *pp;
    casu_fits *ff,*ffv;
    casu_tfits *tab;
    cpl_table *t,*stdscat,*dummytab;
    char filt[16],projid[16],*fname,bname[BUFSIZ],*junk1,*junk2,*pcat;
    char *vimos_names[VIMOS_NEXTN],*assoc,photosys[8];

    /* Check validity of input frameset */

    if (framelist == NULL || cpl_frameset_get_size(framelist) <= 0) {
        cpl_msg_error(fctid,"Input framelist NULL or has no input data");
        return(-1);
    }

    /* Initialise some things */

    vimos_std_init(&ps);

    /* Get the parameters */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.preview_only");
    cs.preview_only = cpl_parameter_get_bool(p);
    p = cpl_parameterlist_find(parlist,"vimos.vimos_ima_standard.minphotom");
    cs.minphotom = cpl_parameter_get_int(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.prettynames");
    cs.prettynames = (cpl_parameter_get_bool(p) ? 1 : 0);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.savemstd");
    cs.savemstd = cpl_parameter_get_bool(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.cdssearch_astrom");
    if (! strcmp(cpl_parameter_get_string(p),"none")) 
        cs.cdssearch_astrom = 0;
    else if (! strcmp(cpl_parameter_get_string(p),"2mass")) 
        cs.cdssearch_astrom = 1;
    else if (! strcmp(cpl_parameter_get_string(p),"usnob")) 
        cs.cdssearch_astrom = 2;
    else if (! strcmp(cpl_parameter_get_string(p),"ppmxl")) 
        cs.cdssearch_astrom = 3;
    else if (! strcmp(cpl_parameter_get_string(p),"wise")) 
        cs.cdssearch_astrom = 5;
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.cdssearch_photom");
    if (! strcmp(cpl_parameter_get_string(p),"none")) 
        cs.cdssearch_photom = 0;
    else if (! strcmp(cpl_parameter_get_string(p),"apass")) 
        cs.cdssearch_photom = 6;
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.ignore_fringe");
    cs.ignore_fringe = cpl_parameter_get_bool(p);

    /* Object detection special parameters */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_ipix");
    cs.src_cat_ipix = cpl_parameter_get_int(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_thresh");
    cs.src_cat_thresh = (float)cpl_parameter_get_double(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_icrowd");
    cs.src_cat_icrowd = cpl_parameter_get_bool(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_rcore");
    cs.src_cat_rcore = (float)cpl_parameter_get_double(p);
    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.src_cat_nbsize");
    cs.src_cat_nbsize = cpl_parameter_get_int(p);

    /* Cache location */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.cacheloc");
    cs.cacheloc = (char *)cpl_parameter_get_string(p);

    /* Magnitude error cut */

    p = cpl_parameterlist_find(parlist,
                               "vimos.vimos_ima_standard.magerrcut");
    cs.magerrcut = (float)cpl_parameter_get_double(p);

    p = cpl_parameterlist_find(parlist, "vimos.vimos_ima_standard.lthr_mag");
    const float lthr_mag = (float)cpl_parameter_get_double(p);

    p = cpl_parameterlist_find(parlist, "vimos.vimos_ima_standard.hthr_mag");
    const float hthr_mag = (float)cpl_parameter_get_double(p);

    /* Sort out raw from calib frames */

    if (vimos_dfs_set_groups(framelist) != CASU_OK) {
        cpl_msg_error(fctid,"Cannot identify RAW and CALIB frames");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Label the input frames */

    if ((ps.labels = cpl_frameset_labelise(framelist,casu_compare_tags,
                                           &nlab)) == NULL) {
        cpl_msg_error(fctid,"Cannot labelise the input frames");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Get the input science frames */

    nfail = 0;
    if ((ps.science_frames = 
         casu_frameset_subgroup(framelist,ps.labels,nlab,
                                VIMOS_STD_OBJECT_RAW)) == NULL) {
        cpl_msg_error(fctid,"No science images to process!");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    /* nfail += vimos_std_testfrms(ps.science_frames,1,1,1); */

    /* Now labelise the input frameset so that we separate them by the
       observation time. This links the four detectors together */

    if ((ps.labels2 = cpl_frameset_labelise(ps.science_frames,
                                            vimos_compare_tpl_start,
                                            &nlab2)) == NULL) {
        cpl_msg_error(fctid,"Cannot labelise the science frames");
        vimos_std_tidy(&ps,0);
        return(-1);
    }


    /* See what chip set this is */

    if (vimos_load_names(cpl_frameset_get_position(ps.science_frames,0),
                         vimos_names) != CASU_OK) {
        cpl_msg_error(fctid,"Cannot get the name set");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Check to see if there is a master bias frame */

    if ((ps.master_bias = 
         casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                  VIMOS_CAL_BIAS)) == NULL) {
        cpl_msg_error(fctid,"No master bias found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_dark,VIMOS_NEXTN,1,0);
        
    /* Check to see if there is a master dark frame */

    if ((ps.master_dark = 
         casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                  VIMOS_CAL_DARK)) == NULL) {
        cpl_msg_error(fctid,"No master dark found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_dark,VIMOS_NEXTN,1,0);
                
    /* Check to see if there is a master twilight flat frame */

    if ((ps.master_twilight_flat = 
         casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                  VIMOS_CAL_TWILIGHT_FLAT)) == NULL) {
        cpl_msg_error(fctid,"No master twilight flat found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_twilight_flat,VIMOS_NEXTN,1,0);

    /* Get the gain corrections */

    status = CASU_OK;
    if (casu_gaincor_calc(ps.master_twilight_flat,&i,&(ps.gaincors),
                          &status) != CASU_OK) {
        cpl_msg_error(fctid,"Error calculating gain corrections");
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Check to see if there is a master confidence map. */

    if ((ps.master_conf = 
        casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                 VIMOS_CAL_CONF)) == NULL) {
        cpl_msg_error(fctid,"No master confidence map file found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.master_conf,VIMOS_NEXTN,1,0);
    ps.mask = casu_mask_define(framelist,ps.labels,nlab,VIMOS_CAL_CONF,
                               "NONE");

    /* Look for a master fringe map. It's not a problem if it doesn't 
       exist */

    ps.master_fringe = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                VIMOS_CAL_FRINGE);
    if (ps.master_fringe != NULL)
        nfail += vimos_testfrm_1(ps.master_fringe,VIMOS_NEXTN,1,0);

    /* Look for a master fringe variance map. It's not a problem if it doesn't 
       exist */

    ps.master_fringe_var = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                    VIMOS_CAL_FRINGE_VAR);
    if (ps.master_fringe_var != NULL)
        nfail += vimos_testfrm_1(ps.master_fringe_var,VIMOS_NEXTN,1,0);

   /* Check to see if there is a master read/gain table */

    if ((ps.readgain = 
        casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                 VIMOS_CAL_READGAIN)) == NULL) {
        cpl_msg_error(fctid,"No master readgain table file found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testrdgn(ps.master_conf,ps.readgain);

    /* Is the 2mass/ppmxl index file specified for astrom? */

    catindex_a = NULL;
    if (cs.cdssearch_astrom == 0) {
        if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                   VIMOS_CAL_2MASS_A)) == NULL) {
            if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                       VIMOS_CAL_PPMXL_A)) == NULL) {
                if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                           VIMOS_CAL_APASS_A)) == NULL) {
                    if ((catindex_a = casu_frameset_subgroup_1(framelist,ps.labels,
                                                               nlab,VIMOS_CAL_LOCCAT_A)) == NULL) {
        
                        cpl_msg_error(fctid,
                                      "No astrometric standard catalogue found -- cannot continue");
                        vimos_std_tidy(&ps,0);
                        return(-1);
                    }
                }
            }
        }
        nfail += vimos_testfrm_1(catindex_a,1,0,0);
    } else {
        (void)casu_getstds_cdslist(cs.cdssearch_astrom,&junk1,&junk2,&status);
        freespace(junk1);
        freespace(junk2);
        if (status != CASU_OK) {
            status = CASU_OK;
            nfail++;
        }
    }

    /* Is the 2mass/ppmxl index file specified for photom? */

    catindex_p = NULL;
    if (cs.cdssearch_photom == 0) {
        if ((catindex_p = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                   VIMOS_CAL_APASS_P)) == NULL) {
            if ((catindex_p = casu_frameset_subgroup_1(framelist,ps.labels,
                                                       nlab,VIMOS_CAL_LOCCAT_P)) == NULL) {
                cpl_msg_error(fctid,
                              "No photometric standard catalogue found -- cannot continue");
                vimos_std_tidy(&ps,0);
                return(-1);
            }
        }
        nfail += vimos_testfrm_1(catindex_p,1,0,0);
        pp = cpl_propertylist_load(cpl_frame_get_filename(catindex_p),1);
        if (cpl_propertylist_has(pp,"EXTNAME")) {
            pcat = cpl_strdup((char *)cpl_propertylist_get_string(pp,"EXTNAME"));
        } else {
            cpl_msg_error(fctid,"No extension name in %s",
                          cpl_frame_get_filename(catindex_p));
            nfail++;
        }
        cpl_propertylist_delete(pp);
    } else {
        (void)casu_getstds_cdslist(cs.cdssearch_photom,&pcat,&junk2,&status);
        freespace(junk2);
        if (status != CASU_OK) {
            status = CASU_OK;
            nfail++;
        }
    }
        
    /* Check to see if there is a photometric table */

    if ((ps.phottab = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                               VIMOS_CAL_PHOTTAB)) == NULL) {
        cpl_msg_error(fctid,"No photometric table found");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    n = cpl_frame_get_nextensions(ps.phottab);
    nfail += vimos_testfrm_1(ps.phottab,n,0,0);

    /* Check the photometric table to see if it contains information 
       about the photometric source we want to use */

    match = 0;
    for (i = 1; i <= n; i++) {
        pp = cpl_propertylist_load(cpl_frame_get_filename(ps.phottab),i);
        if (cpl_propertylist_has(pp,"EXTNAME") &&
            strcmp(pcat,cpl_propertylist_get_string(pp,"EXTNAME")) == 0) {
            if (cpl_propertylist_has(pp,"PHOTOSYS")) {
                strncpy(photosys,cpl_propertylist_get_string(pp,"PHOTOSYS"),8);
            } else {
                cpl_msg_error(fctid,
                              "Photcal table missing PHOTOSYS information in extension %d",i);
                cpl_propertylist_delete(pp);
                break;
            }
            ps.tphottab = cpl_table_load(cpl_frame_get_filename(ps.phottab),
                                         i,0);
            cpl_propertylist_delete(pp);
            match = 1;
            break;
        }
        cpl_propertylist_delete(pp);
    }
    if (! match) {
        cpl_msg_error(fctid,"Photcal table has no information on %s",pcat);
        nfail++;
    }
    freespace(pcat);

    /* Is the Northern Schlegel file specified? */

    if ((ps.schlf_n = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                               VIMOS_CAL_SCHL_N)) == NULL) {
        cpl_msg_error(fctid,"Schlegel North map not found -- cannot continue");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.schlf_n,0,1,0);

    /* Is the Southern Schlegel file specified? */

    if ((ps.schlf_s = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                               VIMOS_CAL_SCHL_S)) == NULL) {
        cpl_msg_error(fctid,"Schlegel South map not found -- cannot continue");
        vimos_std_tidy(&ps,0);
        return(-1);
    }
    nfail += vimos_testfrm_1(ps.schlf_s,0,1,0);

    /* Check the cache location is writable */

    if (access(cs.cacheloc,R_OK+W_OK+X_OK) != 0) {
        cpl_msg_error(fctid,"Cache location %s inacessible",cs.cacheloc);
        nfail++;
    }

    /* Ok if any of this failed, then get out of here. This makes it a bit 
       simpler later on since we now know that all of the specified files 
       have the correct number of extensions and will load properly */

    if (nfail > 0) {
        cpl_msg_error(fctid,
                      "There are %" CPL_SIZE_FORMAT " input file errors -- cannot continue",
                      (cpl_size)nfail);
        freeframe(catindex_a);
        freeframe(catindex_p);
        vimos_std_tidy(&ps,0);
        return(-1);
    }

    /* Get catalogue parameters */

    if (cs.cdssearch_astrom == 0) {
        if (casu_catpars(catindex_a,&(ps.catpath_a),
                         &(ps.catname_a)) == CASU_FATAL) {
            vimos_std_tidy(&ps,0);
            cpl_frame_delete(catindex_a);
            return(-1);
        }
        cpl_frame_delete(catindex_a);
    } else {
        ps.catpath_a = NULL;
        ps.catname_a = NULL;
    }
    if (cs.cdssearch_photom == 0) {
        if (casu_catpars(catindex_p,&(ps.catpath_p),
                         &(ps.catname_p)) == CASU_FATAL) {
            vimos_std_tidy(&ps,0);
            cpl_frame_delete(catindex_p);
            return(-1);
        }
        cpl_frame_delete(catindex_p);
    } else {
        ps.catpath_p = NULL;
        ps.catname_p = NULL;
    }

    /* Print out some stuff if you want a preview */

    if (cs.preview_only) {
        fprintf(stdout,"This is a paw group with %" CPL_SIZE_FORMAT " files\n",
                cpl_frameset_get_size(ps.science_frames));
        frm = cpl_frameset_get_position(ps.science_frames,0);
        ff = casu_fits_load(frm,CPL_TYPE_FLOAT,cpl_frame_get_nextensions(frm));
        pp = casu_fits_get_phu(ff);
        (void)vimos_pfits_get_filter(pp,filt);
        (void)vimos_pfits_get_projid(pp,projid);
        freefits(ff);

        fprintf(stdout,"Filter: %8s, Project: %s\n",filt,projid);
        fprintf(stdout,"Bias: %s\n",cpl_frame_get_filename(ps.master_bias));
        fprintf(stdout,"Dark: %s\n",cpl_frame_get_filename(ps.master_dark));
        fprintf(stdout,"Flat: %s\n",
                cpl_frame_get_filename(ps.master_twilight_flat));
        fprintf(stdout,"CPM: %s\n",cpl_frame_get_filename(ps.master_conf));
        if (ps.master_fringe != NULL && ! cs.ignore_fringe) {
            fprintf(stdout,"Fringe: %s\n",
                    cpl_frame_get_filename(ps.master_fringe));
        } else {
            fprintf(stdout,"No defringing to be done\n");
        }
        n = cpl_frameset_get_size(ps.science_frames);
        for (j = 0; j < n; j++) {
            frm = cpl_frameset_get_position(ps.science_frames,j);
            fprintf(stdout,"%s\n",cpl_frame_get_filename(frm));
        }
        if (cs.cdssearch_astrom != 0) {
            p = cpl_parameterlist_find(parlist,
                                       "vimos.vimos_ima_standard.cdssearch_astrom");
            fprintf(stdout,"Astrometry will be done using CDS catalogue: %s\n",
                    cpl_parameter_get_string(p));
        } else {
            fprintf(stdout,"Astrometry will be done using local catalogue %s in %s\n",
                    ps.catname_a,ps.catpath_a);
        }
        if (cs.cdssearch_photom != 0) {
            p = cpl_parameterlist_find(parlist,
                                       "vimos.vimos_ima_standard.cdssearch_photom");
            fprintf(stdout,"Photometry will be done using CDS catalogue: %s\n",
                    cpl_parameter_get_string(p));
        } else {
            fprintf(stdout,"Photometry will be done using local catalogue %s in %s\n",
                    ps.catname_p,ps.catpath_p);
        }        vimos_std_tidy(&ps,0);
        return(0);
    }

    /* Get some workspace for the product frames */

    ps.nscience = nlab2;
    ps.product_frames_simple = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_vars = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_cats = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_mstd_a = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    ps.product_frames_mstd_p = cpl_malloc(ps.nscience*sizeof(cpl_frame *));
    for (i = 0; i < ps.nscience; i++) {
        ps.product_frames_simple[i] = NULL;
        ps.product_frames_vars[i] = NULL;
        ps.product_frames_cats[i] = NULL;
        ps.product_frames_mstd_a[i] = NULL;
        ps.product_frames_mstd_p[i] = NULL;
    }

    /* Create a dummy in case we need it */

    dummyim = cpl_image_new(1,1,CPL_TYPE_FLOAT);
    ps.dummyfits = casu_fits_wrap(dummyim,NULL,NULL,NULL);
    casu_dummy_property(casu_fits_get_phu(ps.dummyfits));
    casu_dummy_property(casu_fits_get_ehu(ps.dummyfits));

    /* Loop for each of the observation labels. If there are no missing 
       files, then this should be four separate images that will 
       ultimately be combined into a single output MEF */

    for (i = 0; i < nlab2; i++) {
        chiplist = vimos_get_obs_frameset(ps.science_frames,ps.labels2,
                                          nlab2,(cpl_size)i,vimos_names);
        tmpl = NULL;
        
        /* Now loop for each detector. Check that it's not a dummy */

        cpl_msg_info(fctid,"Stage 1 corrections %d of %d",i+1,(int)nlab2);
        for (j = 0; j < VIMOS_NEXTN; j++) {
            frm = cpl_frameset_get_position(chiplist,(cpl_size)j);
            if (strncmp(cpl_frame_get_tag(frm),"DUMMY",5) == 0) {
                ps.sci_fits[j] = casu_fits_duplicate(ps.dummyfits);
                ps.sci_vars[j] = casu_fits_duplicate(ps.dummyfits);
                dummytab = casu_dummy_catalogue(2);
                ps.sci_cats[j] = casu_tfits_wrap(dummytab,NULL,NULL,NULL);
                casu_dummy_property(casu_tfits_get_phu(ps.sci_cats[j]));
                casu_dummy_property(casu_tfits_get_ehu(ps.sci_cats[j]));
                ps.sci_mstd_a[j] = NULL;
                ps.sci_mstd_p[j] = NULL;
                continue;
            }
            if (tmpl == NULL) 
                tmpl = frm;
            ff = casu_fits_load(frm,CPL_TYPE_FLOAT,
                                cpl_frame_get_nextensions(frm));

            /* Right, we want to 2d correct. So load the calib files */

            ps.fbias = casu_fits_load(ps.master_bias,CPL_TYPE_FLOAT,j+1);
            ps.fdark = casu_fits_load(ps.master_dark,CPL_TYPE_FLOAT,j+1);
            ps.fflat = casu_fits_load(ps.master_twilight_flat,
                                      CPL_TYPE_FLOAT,j+1);
            ps.fconf = casu_fits_load(ps.master_conf,CPL_TYPE_INT,j+1);
            casu_mask_load(ps.mask,j+1,
                           (int)cpl_image_get_size_x(casu_fits_get_image(ps.fconf)),
                           (int)cpl_image_get_size_y(casu_fits_get_image(ps.fconf)));
            if (ps.master_fringe != NULL && ! cs.ignore_fringe) {
                ps.ffringe = casu_fits_load(ps.master_fringe,CPL_TYPE_FLOAT,
                                            j+1);
                if (ps.master_fringe_var != NULL) 
                    ps.ffringe_var = casu_fits_load(ps.master_fringe_var,
                                                    CPL_TYPE_FLOAT,j+1);
            } else {
                ps.ffringe = NULL;
                ps.ffringe_var = NULL;
            }

            /* Gain corrections are in the same order as vimos_names so 
               there's no trouble making sure we have the right one... */

            gaincor_fac = (ps.gaincors)[j];

            /* Get the readnoise and gain estimates */

            vimos_getrdgn(ps.readgain,casu_fits_get_extname(ps.fflat),
                              &readnoise,&gain);

            /* Loop for each image and do the stage 1 corrections. */

            status = CASU_OK;
            vimos_biascor(ff,ps.fbias,1,1,&status);
            vimos_pfits_get_exptime(casu_fits_get_ehu(ff),&texp);
            casu_darkcor(ff,ps.fdark,texp,&status);
            ffv = vimos_var_create(ff,ps.mask,readnoise,gain);
            casu_flatcor(ff,ps.fflat,&status);
            vimos_var_div_im(ffv,ps.fflat);
            casu_gaincor(ff,gaincor_fac,&status);
            vimos_var_divk(ffv,gaincor_fac);
            casu_fits_set_error(ff,status);
            cpl_propertylist_update_float(casu_fits_get_ehu(ff),"READNOIS",
                                          readnoise);
            cpl_propertylist_set_comment(casu_fits_get_ehu(ff),"READNOIS",
                                         "[ADU] Read noise used in reduction");
            cpl_propertylist_update_float(casu_fits_get_ehu(ff),"GAIN",
                                          gain);
            cpl_propertylist_set_comment(casu_fits_get_ehu(ff),"GAIN",
                                         "[e-/ADU] gain used in reduction");

            /* Do the defringing if we want it */
        
            if (ps.ffringe != NULL && ! cs.ignore_fringe) {
                casu_defringe(&ff,1,&(ps.ffringe),1,ps.mask,512,&status);
                if (ps.ffringe_var != NULL) {
                    fac = cpl_propertylist_get_float(casu_fits_get_ehu(ff),
                                                     "ESO DRS FRNGSC1");
                    vimos_var_scaledsubt(ffv,ps.ffringe_var,fac);
                }
            }
           
            /* Do the catalogue extraction and WCS fit */

            (void)casu_imcore(ff,ps.fconf,cs.src_cat_ipix,cs.src_cat_thresh,
                              cs.src_cat_icrowd,cs.src_cat_rcore,
                              cs.src_cat_nbsize,6,2.0,&tab,gain,&status);
            if (status == CASU_OK) {
                vimos_wcsfit(&ff,&tab,1,ps.catname_a,
                             ps.catpath_a,cs.cdssearch_astrom,cs.cacheloc,
                             cs.savemstd,j+1,&(ps.sci_mstd_a[j]));
                vimos_copywcs(casu_fits_get_ehu(ff),casu_fits_get_ehu(ffv));
                (void)casu_getstds(casu_fits_get_ehu(ff),1,ps.catpath_p,
                                   ps.catname_p,cs.cdssearch_photom,
                                   cs.cacheloc,&stdscat,&status);
                vimos_pfits_get_filter(casu_fits_get_phu(ff),filt);
            } else {
                t = casu_dummy_catalogue(2);
                tab = casu_tfits_wrap(t,NULL,
                                      cpl_propertylist_duplicate(casu_fits_get_phu(ff)),
                                      cpl_propertylist_duplicate(casu_fits_get_ehu(ff)));
                casu_tfits_set_status(tab,CASU_FATAL);
                stdscat = NULL;
                if (cs.savemstd) 
                    ps.sci_mstd_a[j] = casu_tfits_wrap(casu_dummy_catalogue(2),
                                                       tab,NULL,NULL);
                else
                    ps.sci_mstd_a[j] = NULL;
            }
            if (stdscat != NULL) {
                (void)casu_matchstds(casu_tfits_get_table(tab),
                                     stdscat,300.0,&t,&status);
                ps.sci_mstd_p[j] = casu_tfits_wrap(t,NULL,
                                                   cpl_propertylist_duplicate(casu_fits_get_phu(ff)),
                                                   cpl_propertylist_duplicate(casu_fits_get_ehu(ff)));
            } else {
                ps.sci_mstd_p[j] = NULL;
            }
            freetable(stdscat);
            (ps.sci_fits)[j] = ff;
            (ps.sci_vars)[j] = ffv;
            (ps.sci_cats)[j] = tab;
            
            /* Clean up and go on to the next extension */

            vimos_std_tidy(&ps,2);
        }

        /* Now do the photometric calibration */

        status = CASU_OK;
        vimos_pfits_get_filter(casu_fits_get_phu(ps.sci_fits[0]),filt);
        const int n_removed_stars = casu_remove_mag_outside_range(ps.sci_mstd_p, VIMOS_NEXTN, filt, ps.tphottab, lthr_mag, hthr_mag);
        if(n_removed_stars == -1)
        {
            cpl_msg_error(fctid,"Cannot filter stars in magnitude range");
            vimos_std_tidy(&ps,0);
            return(-1);
        }
        cpl_msg_info(cpl_func, "Removed %i stars outside magnitue range %f %f",
                     n_removed_stars, lthr_mag, hthr_mag);
        casu_photcal_extinct(ps.sci_fits,ps.sci_mstd_p,ps.sci_cats,VIMOS_NEXTN,
                             filt,ps.tphottab,cs.minphotom,ps.schlf_n,
                             ps.schlf_s,"EXPTIME","ESO TEL AIRM START",
                             cs.magerrcut,&status);

        /* Check whether there is at least one star used for the photometric
           zeropoints */
        int magnzptall = cpl_propertylist_get_int(casu_fits_get_ehu(ps.sci_fits[0]),"ESO DRS MAGNZPTALL");
        if(magnzptall == 0)
        {
            cpl_msg_error(cpl_func, "No photometric stars could be found "
                          "among all VIMOS chips");
            vimos_std_tidy(&ps,0);
            return(-1);
        }

        /* Now save the products */

        status = CASU_OK;
        cpl_msg_info(fctid,"Saving products");
        for (j = 1; j <= VIMOS_NEXTN; j++) {
            isfirst = (j == 1);

            /* Save the variance map */

            assoc = NULL;
            if (j == 1) {
                fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                vimos_std_product_name(fname,SIMPLE_VAR,cs.prettynames,i+1,
                                       bname);
                freespace(fname);
            } else {
                strcpy(bname,
                       cpl_frame_get_filename((ps.product_frames_vars)[i]));
            }
            if (vimos_std_save_simple((ps.sci_vars)[j-1],framelist,parlist,
                                      tmpl,isfirst,VIMOS_PRO_VAR_STD,bname,
                                      vimos_names[j-1],assoc,photosys,
                                      ps.product_frames_vars+i) != CASU_OK) {
                cpl_msg_error(fctid,"Unable to save product %s[%d]",bname,j);
                cpl_frameset_delete(chiplist);
                vimos_std_tidy(&ps,0);
                return(-1);
            }

            /* Save the image */

            if (j == 1) {
                fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                vimos_std_product_name(fname,SIMPLE_FILE,cs.prettynames,i+1,
                                       bname);
                freespace(fname);
                assoc = cpl_strdup(cpl_frame_get_filename(ps.product_frames_vars[i]));
            } else {
                strcpy(bname,
                       cpl_frame_get_filename((ps.product_frames_simple)[i]));
            }
            if (vimos_std_save_simple((ps.sci_fits)[j-1],framelist,parlist,
                                      tmpl,isfirst,VIMOS_PRO_SIMPLE_STD,
                                      bname,vimos_names[j-1],assoc,photosys,
                                      ps.product_frames_simple+i) != CASU_OK) {
                cpl_msg_error(fctid,"Unable to save product %s[%d]",bname,j);
                cpl_frameset_delete(chiplist);
                vimos_std_tidy(&ps,0);
                return(-1);
            }
            if (j == 1)
                freespace(assoc);

            /* Save the catalogues */

            if (j == 1) {
                fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                vimos_std_product_name(fname,SIMPLE_CAT,cs.prettynames,i+1,
                                       bname);
                freespace(fname);
            } else {
                strcpy(bname,
                       cpl_frame_get_filename((ps.product_frames_cats)[i]));
            }
            if (vimos_std_save_cat((ps.sci_cats)[j-1],framelist,parlist,
                                   frm,isfirst,VIMOS_PRO_OBJCAT_STD,
                                   bname,vimos_names[j-1],photosys,
                                   ps.product_frames_cats+i) != CASU_OK) {
                cpl_msg_error(fctid,"Unable to save product %s[%d]",bname,j);
                cpl_frameset_delete(chiplist);
                vimos_std_tidy(&ps,0);
                return(-1);
            }

            /* Save the matched standards catalogues if you want to  */

            if (cs.savemstd) {
                if (j == 1) {
                    fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                    vimos_std_product_name(fname,MSTDS_ASTROM,cs.prettynames,
                                           i+1,bname);
                    freespace(fname);
                } else {
                    strcpy(bname,
                           cpl_frame_get_filename((ps.product_frames_mstd_a)[i]));
                }
                if (vimos_std_save_cat(ps.sci_mstd_a[j-1],framelist,parlist,
                                       frm,isfirst,VIMOS_PRO_MATCHSTD_ASTROM,
                                       bname,vimos_names[j-1],photosys,
                                       ps.product_frames_mstd_a+i) != CASU_OK) {
                    cpl_msg_error(fctid,"Unable to save product %s[%d]",
                                  bname,j);
                    cpl_frameset_delete(chiplist);
                    vimos_std_tidy(&ps,0);
                    return(-1);
                }
                if (j == 1) {
                    fname = cpl_strdup(cpl_frame_get_filename(tmpl));
                    vimos_std_product_name(fname,MSTDS_PHOTOM,cs.prettynames,
                                           i+1,bname);
                    freespace(fname);
                } else {
                    strcpy(bname,
                           cpl_frame_get_filename((ps.product_frames_mstd_p)[i]));
                }
                if (vimos_std_save_cat(ps.sci_mstd_p[j-1],framelist,parlist,
                                       frm,isfirst,VIMOS_PRO_MATCHSTD_PHOTOM,
                                       bname,vimos_names[j-1],photosys,
                                       ps.product_frames_mstd_p+i) != CASU_OK) {
                    cpl_msg_error(fctid,"Unable to save product %s[%d]",
                                  bname,j);
                    cpl_frameset_delete(chiplist);
                    vimos_std_tidy(&ps,0);
                    return(-1);
                }
            }
        }
        cpl_frameset_delete(chiplist);
        vimos_std_tidy(&ps,1);
    }

    /* Get out of here */

    vimos_std_tidy(&ps,0);
    return(0);
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_save_simple
    \par Purpose:
        Save the simple image products
    \par Description:
        An extension of a simple image product is saved here
    \par Language:
        C
    \param obj
        The casu_fits structure for the image to be saved
    \param framelist
        The input recipe frameset
    \param parlist
        The input recipe parameter list
    \param template
        A template to be used in the cpl saving routine
    \param isfirst
        Set of this is the first extension to be written to the file
    \param tag
        The product tag for the saved file
    \param fname
        The output file name
    \param cname
        The detector name
    \param assoc
        The name of the associated files for the simple images
    \param photosys
        The photometric system
    \param product_frame
        The output product frame
    \retval CASU_OK if everything is ok
    \retval CASU_FATAL if something failed
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static int vimos_std_save_simple(casu_fits *obj, cpl_frameset *framelist,
                                 cpl_parameterlist *parlist, 
                                 cpl_frame *template, int isfirst,
                                 const char *tag, char *fname, char *cname,
                                 char *assoc, char *photosys,
                                 cpl_frame **product_frame) {
    cpl_propertylist *plist;
    int isdummy;
    float texp;
    char filt[32];
    const char *fctid = "vimos_std_save_simple";

    /* Get some information about this guy */

    isdummy = (casu_fits_get_status(obj) != CASU_OK);

    /* If we need to make a PHU then do that now based on the first frame
       in the input frame list. Get rid of the file if it already exists */

    if (isfirst) {
        if (access(fname,F_OK)) 
            remove(fname);

        /* Create a new product frame object and define some tags */

        *product_frame = cpl_frame_new();
        cpl_frame_set_filename(*product_frame,fname);

        /* Tag the product */

        cpl_frame_set_tag(*product_frame,tag);
        cpl_frame_set_type(*product_frame,CPL_FRAME_TYPE_IMAGE);
        cpl_frame_set_group(*product_frame,CPL_FRAME_GROUP_PRODUCT);
        cpl_frame_set_level(*product_frame,CPL_FRAME_LEVEL_FINAL);

        /* Set some PhaseIII parameters */

        plist = casu_fits_get_phu(obj);
        cpl_propertylist_update_string(plist,"RADECSYS","ICRS");
        cpl_propertylist_update_string(plist,"ORIGIN","ESO-PARANAL");
        cpl_propertylist_set_comment(plist,"ORIGIN",
                                     "European Southern Observatory");
        cpl_propertylist_update_string(plist,"TELESCOP","ESO-VLT-U3");
        cpl_propertylist_set_comment(plist,"TELESCOP","ESO telescope name");
        cpl_propertylist_update_string(plist,"INSTRUME","VIMOS");
        cpl_propertylist_set_comment(plist,"INSTRUME","Instrument used");
        cpl_propertylist_update_string(plist,"OBSTECH","IMAGE");
        cpl_propertylist_set_comment(plist,"OBSTECH","Observation Technique");
        cpl_propertylist_update_string(plist,"IMATYPE","PAWPRINT");
        cpl_propertylist_update_bool(plist,"ISAMP",1);
        cpl_propertylist_set_comment(plist,"ISAMP",
                                     "TRUE if image represents partially sampled sky");
        cpl_propertylist_update_bool(plist,"SINGLEXP",1);
        cpl_propertylist_set_comment(plist,"SINGLEXP",
                                     "TRUE if resulting from a single exposure");
        cpl_propertylist_update_string(plist,"PROV1",
                                       cpl_propertylist_get_string(plist,"ARCFILE"));
        cpl_propertylist_set_comment(plist,"PROV1","Originating raw science file");
        cpl_propertylist_update_int(plist,"NCOMBINE",1);
        cpl_propertylist_set_comment(plist,"NCOMBINE","Number of input images");
        if (strcmp(tag,VIMOS_PRO_SIMPLE_STD) == 0) {
            cpl_propertylist_update_string(plist,"PRODCATG","SCIENCE.MEFIMAGE");
            cpl_propertylist_set_comment(plist,"PRODCATG","Data product category");
            cpl_propertylist_update_string(plist,"ASSON1",assoc);
            cpl_propertylist_set_comment(plist,"ASSON1","Associated file");
            cpl_propertylist_update_string(plist,"ASSOC1","ANCILLARY.VARMAP");
            cpl_propertylist_set_comment(plist,"ASSOC1","Associated file category");
        } else {
            cpl_propertylist_erase(plist,"PRODCATG");
            cpl_propertylist_erase(plist,"ASSON1");
            cpl_propertylist_erase(plist,"ASSOC1");
        }
        vimos_pfits_get_filter(plist,filt);
        cpl_propertylist_update_string(plist,"FILTER",filt);
        cpl_propertylist_set_comment(plist,"FILTER","Filter used in observation"); 
        cpl_propertylist_erase_regexp(plist,"FILTER[0-9]+",0);
        vimos_pfits_get_exptime(plist,&texp);
        cpl_propertylist_update_double(plist,"EXPTIME",(double)texp);
        cpl_propertylist_update_double(plist,"TEXPTIME",(double)texp);
        cpl_propertylist_update_double(plist,"MJD-END",
                                       cpl_propertylist_get_double(plist,"MJD-OBS") +
                                       (double)texp/86400.0);
        cpl_propertylist_set_comment(plist,"MJD-END","End of observations");
        cpl_propertylist_update_string(plist,"PROG_ID",
                                       cpl_propertylist_get_string(plist,"ESO OBS PROG ID"));
        cpl_propertylist_set_comment(plist,"PROG_ID","ESO programme identification");
        cpl_propertylist_update_int(plist,"OBID1",
                                    cpl_propertylist_get_int(plist,"ESO OBS ID"));
        cpl_propertylist_set_comment(plist,"OBID1","Observation block ID");
        cpl_propertylist_update_bool(plist,"M_EPOCH",0);
        cpl_propertylist_set_comment(plist,"M_EPOCH",
                                     "TRUE if resulting from multiple epochs");
        cpl_propertylist_update_string(plist,"REFERENC","");
        cpl_propertylist_set_comment(plist,"REFERENC","Bibliographic Reference");
        if (cpl_propertylist_get_bool(casu_fits_get_ehu(obj),"ZPFUDGED")) {
            cpl_propertylist_update_string(plist,"FLUXCAL","UNCALIBRATED");
        } else {
            cpl_propertylist_update_string(plist,"FLUXCAL","ABSOLUTE");
        }
        cpl_propertylist_set_comment(plist,"FLUXCAL",
                                     "Certifies the validity of PHOTZP");
        cpl_propertylist_update_double(plist,"DIT",(double)texp);
        cpl_propertylist_set_comment(plist,"DIT","Detector integration time");

        /* Set up the PHU header */

        vimos_dfs_set_product_primary_header(plist,*product_frame,framelist,
                                             parlist,VIMOS_RECIPENAME,
                                             "PRO-1.15",template,1);

        /* 'Save' the PHU image */                         

        if (cpl_image_save(NULL,fname,CPL_TYPE_UCHAR,plist,CPL_IO_DEFAULT) != 
            CPL_ERROR_NONE) {
            cpl_msg_error(fctid,"Cannot save product PHU");
            cpl_frame_delete(*product_frame);
            return(CASU_FATAL);
        }
        cpl_frameset_insert(framelist,*product_frame);
    }

    /* Get the extension property list */

    plist = casu_fits_get_ehu(obj);
    if (isdummy)
        casu_dummy_property(plist);

    /* Add some PhaseIII stuff */

    cpl_propertylist_update_string(plist,"BUNIT","ADU");
    cpl_propertylist_set_comment(plist,"BUNIT","Physical unit of array values");
    cpl_propertylist_update_string(plist,"PHOTSYS",photosys);
    cpl_propertylist_set_comment(plist,"PHOTSYS","Photometric System");

    /* Fiddle with the header now */

    cpl_propertylist_update_string(plist,"EXTNAME",cname);
    vimos_dfs_set_product_exten_header(plist,*product_frame,framelist,parlist,
                                       VIMOS_RECIPENAME,"PRO-1.15",template);
    if (cpl_image_save(casu_fits_get_image(obj),fname,CPL_TYPE_FLOAT,plist,
                       CPL_IO_EXTEND) != CPL_ERROR_NONE) {
        cpl_msg_error(fctid,"Cannot save product image extension -- %s",
                      cpl_error_get_message());
        return(CASU_FATAL);
    }

    /* Get out of here */

    return(CASU_OK);
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_save_cat
    \par Purpose:
        Save the simple image products
    \par Description:
        An extension of a simple image product is saved here
    \par Language:
        C
    \param obj
        The casu_tfits structure for the catalogue to be saved
    \param framelist
        The input recipe frameset
    \param parlist
        The input recipe parameter list
    \param template
        A template to be used in the cpl saving routine
    \param isfirst
        Set of this is the first extension to be written to the file
    \param tag
        The product tag for the saved file
    \param fname
        The output file name
    \param cname
        The detector name
    \param photosys
        The photometric system
    \param product_frame
        The output product frame
    \retval CASU_OK if everything is ok
    \retval CASU_FATAL if something failed
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static int vimos_std_save_cat(casu_tfits *obj, cpl_frameset *framelist,
                              cpl_parameterlist *parlist, 
                              cpl_frame *template, int isfirst,
                              const char *tag, char *fname, char *cname,
                              char *photosys, cpl_frame **product_frame) {
    cpl_propertylist *plist;
    int isdummy;
    char filt[32];
    float texp;
    const char *fctid = "vimos_std_save_cat";

    /* Get some information about this guy */

    isdummy = (casu_tfits_get_status(obj) != CASU_OK);

    /* If we need to make a PHU then do that now based on the first frame
       in the input frame list. Get rid of the file if it already exists */

    if (isfirst) {
        if (access(fname,F_OK)) 
            remove(fname);

        /* Create a new product frame object and define some tags */

        *product_frame = cpl_frame_new();
        cpl_frame_set_filename(*product_frame,fname);

        /* Tag the output frame */

        cpl_frame_set_tag(*product_frame,tag);
        cpl_frame_set_type(*product_frame,CPL_FRAME_TYPE_IMAGE);
        cpl_frame_set_group(*product_frame,CPL_FRAME_GROUP_PRODUCT);
        cpl_frame_set_level(*product_frame,CPL_FRAME_LEVEL_FINAL);

        /* Phase III headers */

        plist = casu_tfits_get_phu(obj);
        if (strcmp(tag,VIMOS_PRO_OBJCAT_STD) == 0) {
            cpl_propertylist_update_string(plist,"RADECSYS","ICRS");
            cpl_propertylist_update_string(plist,"ORIGIN","ESO-PARANAL");
            cpl_propertylist_set_comment(plist,"ORIGIN",
                                         "European Southern Observatory");
            cpl_propertylist_update_string(plist,"TELESCOP","ESO-VLT-U3");
            cpl_propertylist_set_comment(plist,"TELESCOP","ESO telescope name");
            cpl_propertylist_update_string(plist,"INSTRUME","VIMOS");
            cpl_propertylist_set_comment(plist,"INSTRUME","Instrument used");
            cpl_propertylist_update_string(plist,"PRODCATG","SCIENCE.SRCTBL");
            cpl_propertylist_set_comment(plist,"PRODCATG","Data product category");
            cpl_propertylist_update_string(plist,"OBSTECH","IMAGE");
            cpl_propertylist_set_comment(plist,"OBSTECH","Observation Technique");
            cpl_propertylist_update_string(plist,"PROG_ID",
                                           cpl_propertylist_get_string(plist,"ESO OBS PROG ID"));
            cpl_propertylist_set_comment(plist,"PROG_ID","ESO programme identification");
            cpl_propertylist_update_int(plist,"OBID1",
                                        cpl_propertylist_get_int(plist,"ESO OBS ID"));
            cpl_propertylist_set_comment(plist,"OBID1","Observation block ID");
            cpl_propertylist_set_bool(plist,"M_EPOCH",0);
            cpl_propertylist_set_comment(plist,"M_EPOCH",
                                         "TRUE if resulting from multiple epochs");
            cpl_propertylist_update_string(plist,"REFERENC","");
            cpl_propertylist_set_comment(plist,"REFERENC","Bibliographic Reference");
            vimos_pfits_get_filter(plist,filt);
            cpl_propertylist_update_string(plist,"FILTER",filt);
            cpl_propertylist_set_comment(plist,"FILTER","Filter used in observation"); 
            cpl_propertylist_erase_regexp(plist,"FILTER[0-9]+",0);
            vimos_pfits_get_exptime(plist,&texp);
            cpl_propertylist_update_double(plist,"EXPTIME",(double)texp);
            cpl_propertylist_update_double(plist,"TEXPTIME",(double)texp);
            cpl_propertylist_update_double(plist,"MJD-END",
                                           cpl_propertylist_get_double(plist,"MJD-OBS") +
                                           (double)texp/86400.0);
            cpl_propertylist_set_comment(plist,"MJD-END","End of observations");

            cpl_propertylist_update_bool(plist,"M_EPOCH",0);
            cpl_propertylist_set_comment(plist,"M_EPOCH",
                                         "TRUE if resulting from multiple epochs");
            cpl_propertylist_update_string(plist,"PROV1",
                                           cpl_propertylist_get_string(plist,"ARCFILE"));
            cpl_propertylist_set_comment(plist,"PROV1",
                                         "Originating raw science file");
            cpl_propertylist_update_string(plist,"IMATYPE","PAWPRINT");
            cpl_propertylist_update_bool(plist,"ISAMP",1);
            cpl_propertylist_set_comment(plist,"ISAMP",
                                         "TRUE if image represents partially sampled sky");
            cpl_propertylist_erase(plist,"ASSON1");
            cpl_propertylist_erase(plist,"ASSOC1");
        }

        /* Set up output headers */

        vimos_dfs_set_product_primary_header(plist,*product_frame,framelist,
                                             parlist,VIMOS_RECIPENAME,
                                             "PRO-1.15",template,1);

        /* 'Save' the PHU image */                         

        if (cpl_image_save(NULL,fname,CPL_TYPE_UCHAR,plist,CPL_IO_DEFAULT) != 
            CPL_ERROR_NONE) {
            cpl_msg_error(fctid,"Cannot save product PHU");
            cpl_frame_delete(*product_frame);
            return(CASU_FATAL);
        }
        cpl_frameset_insert(framelist,*product_frame);
    }

    /* Get the extension property list */

    plist = casu_tfits_get_ehu(obj);
    if (isdummy)
        casu_dummy_property(plist);

    /* Fiddle with the header now */

    cpl_propertylist_update_string(plist,"PHOTSYS",photosys);
    cpl_propertylist_set_comment(plist,"PHOTSYS","Photometric System");
    cpl_propertylist_erase(plist,"BUNIT");
    cpl_propertylist_update_string(plist,"EXTNAME",cname);
    vimos_dfs_set_product_exten_header(plist,*product_frame,framelist,parlist,
                                       VIMOS_RECIPENAME,"PRO-1.15",template);
    if (cpl_table_save(casu_tfits_get_table(obj),NULL,plist,fname,
                       CPL_IO_EXTEND) != CPL_ERROR_NONE) {
        cpl_msg_error(fctid,"Cannot save product table extension -- %s",
                      cpl_error_get_message());
        return(CASU_FATAL);
    }

    /* Get out of here */

    return(CASU_OK);
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_product_name
    \par Purpose:
        Set up an output product file name
    \par Description:
        An output file name is defined based on a template name,  a
        'predictable' name or a temporary file name.
    \par Language:
        C
    \param template
        If the pretty file name option is used or if this is a temporary
        file name, then the this will be used as a reference name.
    \param producttype
        The type of product you are writing out. These are enumerated above.
    \param nametype
        This is: 0 -> predictable names, 1 -> pretty names based on input
        file names or 2 -> temporary file names.
    \param fnumber
        If the predictable file names are going to be used, then this is 
        a number that is appended to a file name root.
    \param outfname
        The output file name
    \return
        Nothing
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static void vimos_std_product_name(char *template, int producttype, 
                                   int nametype, int fnumber, char *outfname) {
    const char *esonames[] = {"exp_","exp_var_","exp_cat_","exp_mstd_a_",
                              "exp_mstd_p_"};
    const char *suffix[] = {"_ex","_ex_var","_ex_cat","_ex_mstd_a",
                            "_ex_mstd_p"};
    char *fname,*bname,*dot;

    /* If the name type is the ESO predictable sort, then it's easy. Just
       use the esonames defined above and append the correct number */

    switch (nametype) {
    case 0:
        (void)sprintf(outfname,"%s%d.fits",esonames[producttype],fnumber);
        break;

    /* If this is a temporary file, then just append tmp_ to the template
       name and return that */

    case 2:
        fname = cpl_strdup(template);
        bname = basename(fname);
        (void)sprintf(outfname,"tmp_%s",bname);
        freespace(fname);
        break;

    /* Ok, we want a pretty name... */

    case 1:
        fname = cpl_strdup(template);
        bname = basename(fname);
        (void)sprintf(outfname,"%s",bname);
        dot = strrchr(outfname,'.');
        (void)sprintf(dot,"%s.fits",suffix[producttype]);
        freespace(fname);
        break;

    /* something else ?? */

    default:
        (void)strcpy(outfname,"");
        break;
    }
    return;
}   

/**@}*/

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_init
    \par Purpose:
        Initialise pointers in the global memory structure.
    \par Description:
        Initialise pointers in the global memory structure.
    \par Language:
        C
    \param ps
        The memory structure
    \return
        Nothing
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static void vimos_std_init(memstruct *ps) {
    int i;

    /* Level 0 stuff */

    ps->labels = NULL;
    ps->labels2 = NULL;
    ps->master_bias = NULL;
    ps->master_dark = NULL;
    ps->master_twilight_flat = NULL;
    ps->master_conf = NULL;
    ps->master_fringe = NULL;
    ps->master_fringe_var = NULL;
    ps->readgain = NULL;
    ps->mask = NULL;
    ps->phottab = NULL;
    ps->tphottab = NULL;
    ps->science_frames = NULL;
    ps->product_frames_simple = NULL;
    ps->product_frames_vars = NULL;
    ps->product_frames_cats = NULL;
    ps->product_frames_mstd_a = NULL;
    ps->product_frames_mstd_p = NULL;
    ps->gaincors = NULL;
    ps->catpath_a = NULL;
    ps->catname_a = NULL;
    ps->catpath_p = NULL;
    ps->catname_p = NULL;
    ps->schlf_n = NULL;
    ps->schlf_s = NULL;
    ps->dummyfits = NULL;

    /* Level 1 stuff */

    ps->nscience = 0;
    for (i = 0; i < VIMOS_NEXTN; i++) {
        ps->sci_fits[i] = NULL;
        ps->sci_vars[i] = NULL;
        ps->sci_cats[i] = NULL;
        ps->sci_mstd_a[i] = NULL;
        ps->sci_mstd_p[i] = NULL;
    }

    /* Level 2 stuff */

    ps->fbias = NULL;
    ps->fdark = NULL;
    ps->fflat = NULL;
    ps->fconf = NULL;
    ps->ffringe = NULL;
    ps->ffringe_var = NULL;
}

/*---------------------------------------------------------------------------*/
/**
    \par Name:
        vimos_std_tidy
    \par Purpose:
        Free allocated workspace in the global memory structure
    \par Description:
        Free allocated workspace in the global memory structure. The tidy works
        on two levels. Level 1 is for items that are usually cleared up after
        each extension is processed. Level 2 is for cleaning up the whole
        recipe
    \par Language:
        C
    \param ps
        The memory structure
    \param level
        The level of the tidy to be done. 1: Tidy up after finishing an 
        extension, 0: Tidy up after finishing the recipe.
    \return
        Nothing
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

static void vimos_std_tidy(memstruct *ps, int level) {
    int i;

    /* Level 2 stuff */

    freefits(ps->fbias); 
    freefits(ps->fdark); 
    freefits(ps->fflat); 
    freefits(ps->fconf);
    freefits(ps->ffringe);
    freefits(ps->ffringe_var);

    if (level == 2) 
        return; 

    /* Level 1 stuff */

    ps->nscience = 0;
    for (i = 0; i < VIMOS_NEXTN; i++) {
        freefits(ps->sci_fits[i]);
        freefits(ps->sci_vars[i]);
        freetfits(ps->sci_cats[i]);
        freetfits(ps->sci_mstd_a[i]);
        freetfits(ps->sci_mstd_p[i]);
    }
    if (level == 1)
        return;
    
    /* Level 0 stuff */

    freespace(ps->labels);
    freespace(ps->labels2);
    freeframe(ps->master_bias);
    freeframe(ps->master_dark);
    freeframe(ps->master_twilight_flat);
    freeframe(ps->master_conf);
    freeframe(ps->master_fringe);
    freeframe(ps->master_fringe_var);
    freeframe(ps->readgain);
    freemask(ps->mask);
    freeframe(ps->phottab);
    freetable(ps->tphottab);
    freeframeset(ps->science_frames);
    freespace(ps->product_frames_simple);    /* NB: We only have to delete */
    freespace(ps->product_frames_cats);      /* the arrays and not the frames */
    freespace(ps->product_frames_vars);      /* as these get passed back */
    freespace(ps->product_frames_mstd_a);    /* to esorex */
    freespace(ps->product_frames_mstd_p);
    freespace(ps->gaincors);
    freespace(ps->catpath_a);
    freespace(ps->catname_a);
    freespace(ps->catpath_p);
    freespace(ps->catname_p);
    freeframe(ps->schlf_n);
    freeframe(ps->schlf_s);
    freefits(ps->dummyfits);
}

/*

$Log: vimos_ima_standard.c,v $
Revision 1.31  2015/11/27 12:15:33  jim
detabbed some lines

Revision 1.30  2015/11/19 12:44:44  jim
Fixed to remove offending keywords to keep ASG happy

Revision 1.29  2015/10/22 12:13:49  jim
A few touchups

Revision 1.28  2015/10/20 11:54:50  jim
removed landolt

Revision 1.27  2015/09/22 15:10:07  jim
fixed typo

Revision 1.26  2015/09/15 10:39:26  jim
Fixed so that variance arrays get same wcs as their science images

Revision 1.25  2015/09/11 09:48:16  jim
changed declaration of some parameters to ranges where appropriate

Revision 1.24  2015/08/07 13:07:15  jim
Fixed copyright to ESO

Revision 1.23  2015/07/29 09:19:53  jim
Fixed inconsistency in file naming in ugly mode

Revision 1.22  2015/07/02 12:30:15  jim
Fixed so that we get the correct value of FLUXCAL now...

Revision 1.21  2015/06/29 10:36:19  jim
photosys now comes from photcal table header

Revision 1.20  2015/06/08 09:46:31  jim
Added phase3 headers

Revision 1.19  2015/05/21 07:48:27  jim
Fixed bug where error was thrown if the photcal tab had more than one
extension

Revision 1.18  2015/05/13 12:00:07  jim
Added defringing

Revision 1.17  2015/05/01 09:02:22  jim
Modified to pass detector name information differently so that Mac compiler
doesn't gripe

Revision 1.16  2015/04/30 12:25:23  jim
Fixed manpage info

Revision 1.15  2015/03/13 10:22:59  jim
Fixed some compiler warnings

Revision 1.14  2015/03/10 13:37:14  jim
Another leak

Revision 1.13  2015/03/10 12:45:53  jim
More leaks

Revision 1.12  2015/03/10 11:06:39  jim
Fixed the way tidy works

Revision 1.11  2015/02/14 12:39:11  jim
Now allow the user to save matched standards catalogues

Revision 1.10  2015/01/29 12:10:23  jim
Modified comments, some command line arguments are now strings where it
makes sense to do so, some support routines moved to vimos_utils.c

Revision 1.9  2014/12/17 13:01:31  jim
Commented out testfrms on science images for the moment

Revision 1.8  2014/12/12 21:40:16  jim
changed so there is no inverse variance anymore

Revision 1.7  2014/12/11 12:27:28  jim
new version

Revision 1.6  2014/05/07 05:49:45  jim
Fixed product frame bug

Revision 1.5  2014/05/07 05:24:26  jim
Bug fixed where confidence map was still being read as integer

Revision 1.4  2014/05/06 15:55:28  jim
Fixed problem with cdssearch

Revision 1.3  2014/05/06 07:35:19  jim
modified to use new casu_getstds, to use readgain table and to create
modified confidence maps

Revision 1.2  2013/11/21 09:39:08  jim
detabbed

Revision 1.1  2013/11/04 05:55:17  jim
new entry


*/
