/* $Id: hawki_dark_combine.c,v 1.15 2015/11/18 20:07:41 jim Exp $
 *
 * This file is part of the HAWKI 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/18 20:07:41 $
 * $Revision: 1.15 $
 * $Name:  $
 */

/* Includes */

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

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

#include "hawki_utils.h"
#include "hawki_pfits.h"
#include "hawki_dfs.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"

/* Define values for bit mask that flags dummy results */

#define MEANDARK    1
#define DIFFIMG     2
#define STATS_TAB   4

/* Structure definitions */

typedef struct {

    /* Input */

    int         combtype;
    int         scaletype;
    int         xrej;
    float       thresh;
    int         ncells;
    int         prettynames;

    /* Output */

    float            particle_rate;
    float            darkmed;
    float            darkmean;
    float            darkrms;
    float            darkdiff_med;
    float            darkdiff_rms;
    int              nhot;
    float            hotfrac;
    cpl_propertylist *qc;

    /* Bitmasks used to make sure we get all the products we're expecting */

    int               we_expect;
    int               we_get;
} configstruct;

typedef struct {
    cpl_size          *labels;
    cpl_frameset      *darklist;
    casu_fits         **darks;
    int               ndarks;
    casu_fits         **good;
    int               ngood;
    cpl_frame         *master_dark;
    casu_mask         *master_mask;
    cpl_image         *outimage;
    cpl_propertylist  *drs;
    unsigned char     *rejmask;
    unsigned char     *rejplus;
    cpl_image         *diffimg;
    cpl_table         *diffimstats;
} memstruct;

static char hawki_dark_combine_description[] =
"hawki_dark_combine -- HAWKI dark combine recipe.\n\n"
"Combine a list of dark frames into a mean dark frame. Optionally compare \n"
"the output frame to a reference dark frame\n\n"
"The program accepts the following files in the SOF:\n\n"
"    Tag                   Description\n"
"    -----------------------------------------------------------------------\n"
"    %-21s A list of raw dark images\n"
"    %-21s Optional reference dark frame\n"
"    %-21s Optional master bad pixel map or\n"
"    %-21s Optional master confidence map\n"
"If no reference dark frame is made available, then no comparison will be\n"
"done. This means there will be no output difference image or stats table. If\n"
"neither a bad pixel mask or a master confidence map is specified all stats\n"
"are done assuming all pixels are good.\n";

/* Function prototypes */

static int hawki_dark_combine_create(cpl_plugin *);
static int hawki_dark_combine_exec(cpl_plugin *);
static int hawki_dark_combine_destroy(cpl_plugin *);
static int hawki_dark_combine(cpl_parameterlist *, cpl_frameset *) ;
static int hawki_dark_combine_save(cpl_frameset *framelist, 
                                   cpl_parameterlist *parlist, int isfirst,
                                   memstruct *ps, configstruct *cs,
                                   cpl_frame **product_frame_mean_dark,
                                   cpl_frame **product_frame_diffimg,
                                   cpl_frame **product_frame_diffimg_stats);
static void hawki_dark_combine_dummy_products(memstruct *ps, configstruct *cs);
static void hawki_dark_combine_hotpix(memstruct *ps, configstruct *cs);
static void hawki_dark_combine_normal(int jext, float exptime, memstruct *ps,
                                      configstruct *cs);
static int hawki_dark_combine_lastbit(int jext, cpl_frameset *framelist,
                                      cpl_parameterlist *parlist,
                                      int isfirst, memstruct *ps,
                                      configstruct *cs,
                                      cpl_frame **product_frame_mean_dark,
                                      cpl_frame **product_frame_diffimg,
                                      cpl_frame **product_frame_diffimg_stats);
static void hawki_dark_combine_init(memstruct *ps);
static void hawki_dark_combine_tidy(memstruct *ps, int level);

/**@{*/

/**
    \ingroup recipelist
    \defgroup hawki_dark_combine hawki_dark_combine
    \brief Combine a list of darks to form a mean dark frame

    \par Name: 
        hawki_dark_combine
    \par Purpose: 
        Combine a list of darks to form a mean dark frame. 
    \par Description: 
        A list of darks with the same exposure parameters is combined with 
        rejection to form a mean dark. If a reference dark is supplied, then
        a difference image is formed between it and the combined result from
        the current frame list. This difference image can be useful for
        looking at the evolution of the structure of the dark current and the
        reset anomaly with time. The median value of the difference image as
        well as the RMS in each cell is written to a difference image 
        statistics table. The inclusion of either a master confidence map
        or a bad pixel mask can aid in masking out bad pixels when doing
        these stats. Otherwise all pixels will be considered to be good.
    \par Language:
        C
    \par Parameters:
        - \b combtype (string): Determines the type of combination that is 
          done to form the output map. Can take the following values:
            - median: The output pixels are medians of the input pixels
            - mean: The output pixels are means of the input pixels
        - \b scaletype (string): Determines how the input data are scaled 
             or offset before they are combined. Can take the following values:
            - none: No scaling of offsetting
            - additive: All input frames are biassed additively to bring their
              backgrounds to a common mean.
        - \b xrej (int): If set, then an extra rejection cycle will be run. 
        - \b thresh (float): The rejection threshold in numbers of sigmas.
        - \b ncells (int): If a difference image statistics table is being 
          done, then this is the number of cells in which to divide each
          readout channel. The value should be a power of 2, up to 64.
        - \b prettynames (bool): If set then a descriptive file name will
          be used for the output products. Otherwise the standard ESO 
          'predictable' name will be used.
    \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 CATG value.
        - \b DARK (required): A list of raw dark images for combining
        - \b REFERENCE_DARK (optional): A library reference dark frame.
             If this is given, then a difference image will be formed and some 
             basic statistics run on it.
        - \b MASTER_BPM or \b MASTER_CONF (optional): If either is given, then
             it will be used to mask out bad pixels during and statistical 
             analysis that is done.
    \par Output Products:
        The following list gives the output data products that are generated
        by this recipe. The word in bold gives the PRO CATG keyword value for
        each product:
        - The output mean/median dark frame, formed by either a mean or median
          combination of the input raw frames with rejection (\b MASTER_DARK).
        - The output difference image, formed by subtracting the input reference
          dark frame from the newly generated mean/median dark frame. This is 
          only done if a reference dark frame is specified from the outset
          (\b DIFFIMG_DARK).
        - The output difference image statistics table. The exact columns 
          contained in this file are described at length the accompanying
          documentation (\b DIFFIMG_STATS_DARK).
    \par Output QC Parameters:
        - \b DARK MED
            The median value of the combined dark frame.
        - \b DARK MEAN
            The mean value of the combined dark frame.
        - \b DARK RMS
            The RMS value of the mean dark frame.
        - \b DARKDIFF_MED
            The median of the dark difference image
        - \b DARKDIFF_RMS
            The RMS of the dark difference image
        - \b PARTICLE_RATE
            The average number of cosmic ray hits per pixel per second 
            per frame.
        - \b NBADPIX
            The number of hot pixels on the mean frame
        - \b BADFRAC
            The fraction of pixels on the mean frame that are hot
        - \b RAW MEAN MEAN
            The mean of the raw image means
        - \b RAW MEAN MEDIAN
            The mean of the raw image medians
        - \b RAW RMS MEAN
            The RMS of the raw image means
        - \b RON MEAN
            The mean of the pairwise READNOISE estimates
        - \b RON MED
            The median of the pairwise READNOISE estimates
        - \b RON STDEV
            The RMS of the pairwise READNOISE estimates
        - \b RONi
            The pairwise READNOISE estimate for the ith pair
    \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 dark frames in the input frameset
        - Unable to save data products
    \par Non-Fatal Error Conditions:
        - Exposure time missing from header. Assumed to be 1 second.
        - No reference dark. No difference image formed.
        - No master bad pixel or confidence map. All pixels considered to be 
          good.
    \par Conditions Leading To Dummy Products:
        - Dark frame image extensions wouldn't load.
        - The detector for the current image extension is flagged dead
        - Combination routine failed
        - Reference dark frame image extension won't load or is flagged as 
          a dummy
    \par Author:
        Jim Lewis, CASU
    \par Code Reference: 
        hawki_dark_combine.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,hawki_dark_combine_description,
                   HAWKI_DARK_RAW,HAWKI_REF_DARK,HAWKI_CAL_BPM,
                   HAWKI_CAL_CONF);

    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    HAWKI_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "hawki_dark_combine",
                    "HAWKI dark combination recipe",
                    alldesc,
                    "Jim Lewis",
                    "jrl@ast.cam.ac.uk",
                    hawki_get_license(),
                    hawki_dark_combine_create,
                    hawki_dark_combine_exec,
                    hawki_dark_combine_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 hawki_dark_combine_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 the parameters. First the combination type */

    p = cpl_parameter_new_enum("hawki.hawki_dark_combine.combtype",
                               CPL_TYPE_STRING,
                               "Combination algorithm",
                               "hawki.hawki_dark_combine",
                               "median",2,"median","mean");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"combtype");
    cpl_parameterlist_append(recipe->parameters,p);

    /* The requested scaling */

    p = cpl_parameter_new_enum("hawki.hawki_dark_combine.scaletype",
                               CPL_TYPE_STRING,
                               "Scaling algorithm",
                               "hawki.hawki_dark_combine",
                               "additive",2,"none","additive");
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"scaletype");
    cpl_parameterlist_append(recipe->parameters,p);
    
    /* Extra rejection cycle */

    p = cpl_parameter_new_value("hawki.hawki_dark_combine.xrej",
                                CPL_TYPE_BOOL,
                                "True if using extra rejection cycle",
                                "hawki.hawki_dark_combine",
                                TRUE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"xrej");
    cpl_parameterlist_append(recipe->parameters,p);

    /* Rejection threshold */

    p = cpl_parameter_new_range("hawki.hawki_dark_combine.thresh",
                                CPL_TYPE_DOUBLE,
                                "Rejection threshold in sigma above background",
                                "hawki.hawki_dark_combine",5.0,1.0e-6,1.0e10);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"thresh");
    cpl_parameterlist_append(recipe->parameters,p);

    /* How many cells to divide each data channel */

    p = cpl_parameter_new_enum("hawki.hawki_dark_combine.ncells",
                               CPL_TYPE_INT,
                               "Number of cells for data channel stats",
                               "hawki.hawki_dark_combine",8,7,1,2,4,8,
                               16,32,64);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"ncells");
    cpl_parameterlist_append(recipe->parameters,p);     

    /* Flag to use pretty output product file names */

    p = cpl_parameter_new_value("hawki.hawki_dark_combine.prettynames",
                                CPL_TYPE_BOOL,
                                "Use pretty output file names?",
                                "hawki.hawki_dark_combine",FALSE);
    cpl_parameter_set_alias(p,CPL_PARAMETER_MODE_CLI,"prettynames");
    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 hawki_dark_combine_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(hawki_dark_combine(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 hawki_dark_combine_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 hawki_dark_combine(cpl_parameterlist *parlist, 
                              cpl_frameset *framelist) {
    const char *fctid="hawki_dark_combine";
    const char *fname;
    int j,retval,status,live,nx,ny,isfirst,ndit;
    cpl_size nlab;
    long i,npts;
    float exptime,*data,fval,med,rnorm;
    double dval;
    casu_fits *ff;
    cpl_parameter *p;
    cpl_propertylist *plist;
    cpl_frame *product_frame_mean_dark,*product_frame_diffimg;
    cpl_frame *product_frame_diffimg_stats;
    cpl_image *diff;
    cpl_vector *vqc_mean,*vqc_median,*vqc_ron;
    unsigned char *bpm;
    memstruct ps;
    configstruct cs;

    /* 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 */

    cs.we_expect = 0;
    cs.we_get = 0;
    hawki_dark_combine_init(&ps);
    cs.we_expect |= MEANDARK;

    /* Get the parameters */

    p = cpl_parameterlist_find(parlist,"hawki.hawki_dark_combine.combtype");
    cs.combtype = (strcmp(cpl_parameter_get_string(p),"median") ? 2 : 1);
    p = cpl_parameterlist_find(parlist,"hawki.hawki_dark_combine.scaletype");
    cs.scaletype = (strcmp(cpl_parameter_get_string(p),"additive") ? 0 : 1);
    p = cpl_parameterlist_find(parlist,"hawki.hawki_dark_combine.xrej");
    cs.xrej = cpl_parameter_get_bool(p);
    p = cpl_parameterlist_find(parlist,"hawki.hawki_dark_combine.thresh");
    cs.thresh = (float)cpl_parameter_get_double(p);
    p = cpl_parameterlist_find(parlist,"hawki.hawki_dark_combine.ncells");
    cs.ncells = cpl_parameter_get_int(p);
    p = cpl_parameterlist_find(parlist,"hawki.hawki_dark_combine.prettynames");
    cs.prettynames = (cpl_parameter_get_bool(p) ? 1 : 0);

    /* Sort out raw from calib frames */

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

    /* Get a list of the frame labels */ 

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

    /* Get the dark frames */

    if ((ps.darklist = casu_frameset_subgroup(framelist,ps.labels,nlab,
                                              HAWKI_DARK_RAW)) == NULL) {
        cpl_msg_error(fctid,"Cannot find dark frames in input frameset");
        hawki_dark_combine_tidy(&ps,0);
        return(-1);
    }
    ps.ndarks = cpl_frameset_get_size(ps.darklist);

    /* Get the exposure time from the first dark frame in the list */

    fname = cpl_frame_get_filename(cpl_frameset_get_position(ps.darklist,0));
    plist = cpl_propertylist_load(fname,0);
    if (hawki_pfits_get_exptime(plist,&exptime) != CASU_OK) {
        cpl_msg_warning(fctid,"Unable to get exposure time for %s",fname);
        exptime = 1.0;
    }
    cpl_propertylist_delete(plist);

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

    if ((ps.master_dark = casu_frameset_subgroup_1(framelist,ps.labels,nlab,
                                                   HAWKI_REF_DARK)) == NULL) {
        cpl_msg_info(fctid,"No reference dark found -- no difference image will be formed");
    } else {
        cs.we_expect |= DIFFIMG;
        cs.we_expect |= STATS_TAB;
    }
        
    /* Check to see if there is a master bad pixel map. If there isn't one 
       then look for a confidence map */

    ps.master_mask = casu_mask_define(framelist,ps.labels,nlab,HAWKI_CAL_CONF,
                                      HAWKI_CAL_BPM);

    /* Get some space for the good frames */

    ps.good = cpl_malloc(ps.ndarks*sizeof(casu_fits *));

    /* Now loop for all the extensions... */

    for (j = 1; j <= HAWKI_NEXTN; j++) {
        status = CASU_OK;
        cs.we_get = 0;
        isfirst = (j == 1);

        /* Load up the images. If they won't load then signal a major error,
           create some dummy products and save them. */

        ps.darks = casu_fits_load_list(ps.darklist,CPL_TYPE_FLOAT,j);
        if (ps.darks == NULL) {
            cpl_msg_info(fctid,
                         "Extension %" CPL_SIZE_FORMAT " darks wouldn't load",
                         (cpl_size)j);
            retval = hawki_dark_combine_lastbit(j,framelist,parlist,isfirst,&ps,
                                                &cs,&product_frame_mean_dark,
                                                &product_frame_diffimg,
                                                &product_frame_diffimg_stats);
            if (retval != 0) 
                return(-1);
            continue;
        }

        /* Are any of these dark frames good? */

        ps.ngood = 0;
        for (i = 0; i < ps.ndarks; i++) {
            ff = ps.darks[i];
            hawki_pfits_get_detlive(casu_fits_get_ehu(ff),&live);
            if (! live) {
                cpl_msg_info(fctid,"Detector flagged dead %s",
                             casu_fits_get_fullname(ff));
                casu_fits_set_error(ff,CASU_FATAL);
            } else {
                ps.good[ps.ngood] = ff;
                ps.ngood += 1;
            }
        }        

        /* If there are no good images, then signal that we need to 
           create some dummy products and move on */

        if (ps.ngood == 0) {
            cpl_msg_info(fctid,"All images flagged bad for this extension");
            retval = hawki_dark_combine_lastbit(j,framelist,parlist,isfirst,&ps,
                                                &cs,&product_frame_mean_dark,
                                                &product_frame_diffimg,
                                                &product_frame_diffimg_stats);
            if (retval != 0) 
                return(-1);
            continue;
        }
        
        /* Load the master mask extension */

        nx = (int)cpl_image_get_size_x(casu_fits_get_image(ps.good[0]));
        ny = (int)cpl_image_get_size_y(casu_fits_get_image(ps.good[0]));
        hawki_pfits_get_ndit(casu_fits_get_ehu(ps.good[0]),&ndit);
        retval = casu_mask_load(ps.master_mask,j,nx,ny);
        if (retval == CASU_FATAL) {
            cpl_msg_info(fctid,
                         "Unable to load mask image %s[%" CPL_SIZE_FORMAT "]",
                         casu_mask_get_filename(ps.master_mask),(cpl_size)j);
            cpl_msg_info(fctid,"Forcing all pixels to be good from now on");
            casu_mask_force(ps.master_mask,nx,ny);
        }

        /* Get some stats for the QC */

        cs.qc = cpl_propertylist_new();
        bpm = casu_mask_get_data(ps.master_mask);
        vqc_mean = cpl_vector_new((cpl_size)ps.ngood);
        vqc_median = cpl_vector_new((cpl_size)ps.ngood);
        vqc_ron = cpl_vector_new((cpl_size)ps.ngood);
        npts = nx*ny;
        //key = cpl_malloc(16);
        rnorm = 1.48*sqrt((double)ndit)/CPL_MATH_SQRT2;
        for (i = 0; i < ps.ngood; i++) {
            data = cpl_image_get_data_float(casu_fits_get_image(ps.good[i]));
            dval = (double)casu_med(data,bpm,npts);
            cpl_vector_set(vqc_median,(cpl_size)i,dval);
            dval = (double)casu_mean(data,bpm,npts);
            cpl_vector_set(vqc_mean,(cpl_size)i,dval);
            if (i == ps.ngood -1) 
                diff = cpl_image_subtract_create(casu_fits_get_image(ps.good[i]),
                                                 casu_fits_get_image(ps.good[0]));
            else
                diff = cpl_image_subtract_create(casu_fits_get_image(ps.good[i]),
                                                 casu_fits_get_image(ps.good[i+1]));
            data = cpl_image_get_data_float(diff);
            casu_medmad(data,bpm,npts,&med,&fval);
            fval *= rnorm;
            cpl_vector_set(vqc_ron,(cpl_size)i,(double)fval);
            char * key = cpl_sprintf("ESO QC RON%ld", (i+1));
            //(void)snprintf(key,16,"ESO QC RON%" CPL_SIZE_FORMAT,(cpl_size)(i+1));
            cpl_propertylist_append_double(cs.qc,key,(double)fval);
            cpl_propertylist_set_comment(cs.qc,key,"Readnoise estimate from pair");
            cpl_free(key);
            cpl_image_delete(diff);
        }

        dval = cpl_vector_get_mean(vqc_mean);
        cpl_propertylist_append_double(cs.qc,"ESO QC RAW MEAN MEAN",dval);
        cpl_propertylist_set_comment(cs.qc,"ESO QC RAW MEAN MEAN",
                                     "Mean of raw image means");
        dval = cpl_vector_get_mean(vqc_median);
        cpl_propertylist_append_double(cs.qc,"ESO QC RAW MEAN MEDIAN",dval);
        cpl_propertylist_set_comment(cs.qc,"ESO QC RAW MEAN MEDIAN",
                                     "Mean of raw image medians");
        dval = cpl_vector_get_stdev(vqc_mean);
        cpl_propertylist_append_double(cs.qc,"ESO QC RAW RMS MEAN",dval);
        cpl_propertylist_set_comment(cs.qc,"ESO QC RAW RMS MEAN",
                                     "RMS of raw image means");
        dval = cpl_vector_get_mean(vqc_ron);
        cpl_propertylist_append_double(cs.qc,"ESO RON MEAN",dval);
        cpl_propertylist_set_comment(cs.qc,"ESO RON MEAN",
                                     "Mean of readnoise estimates");
        dval = cpl_vector_get_median(vqc_ron);
        cpl_propertylist_append_double(cs.qc,"ESO RON MED",dval);
        cpl_propertylist_set_comment(cs.qc,"ESO RON MED",
                                     "Median of readnoise estimates");
        dval = cpl_vector_get_stdev(vqc_ron);
        cpl_propertylist_append_double(cs.qc,"ESO RON STDEV",dval);
        cpl_propertylist_set_comment(cs.qc,"ESO RON STDEV",
                                     "RMS of readnoise estimates");
        cpl_vector_delete(vqc_ron);
        cpl_vector_delete(vqc_mean);
        cpl_vector_delete(vqc_median);
            
        /* Call the combine module. If it fails, then signal that
           all products will be dummies */

        cpl_msg_info(fctid,"Doing combination for extension %" CPL_SIZE_FORMAT,
                     (cpl_size)j);
        (void)casu_imcombine(ps.good,NULL,ps.ngood,cs.combtype,cs.scaletype,
                             cs.xrej,cs.thresh,"EXPTIME",&(ps.outimage),NULL,
                             &(ps.rejmask),&(ps.rejplus),&(ps.drs),&status);
        if (status == CASU_OK) {
            cs.we_get |= MEANDARK;
            hawki_dark_combine_hotpix(&ps,&cs);
            hawki_dark_combine_normal(j,exptime,&ps,&cs);

        } 

        /* Create any dummies and save the products */

        retval = hawki_dark_combine_lastbit(j,framelist,parlist,isfirst,&ps,
                                            &cs,&product_frame_mean_dark,
                                            &product_frame_diffimg,
                                            &product_frame_diffimg_stats);
        cpl_propertylist_delete(cs.qc);
        if (retval != 0) 
            return(-1);
    }
    hawki_dark_combine_tidy(&ps,0);
    return(0);
}


/*---------------------------------------------------------------------------*/
/**
  @brief    The recipe data products are saved here
  @param    framelist    The input frame list
  @param    parlist      The input recipe parameter list
  @param    isfirst      Set if this is the first extension to be saved
  @param    ps           The memory structure defined in the main routine
  @param    cs           The configuration structure defined in the main routine
  @param    product_frame_mean_dark   The frame for the mean dark product
  @param    product_frame_diffimg     The frame for the difference image product
  @param    product_frame_diffimg_stats The frame for the diffimg stats table
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int hawki_dark_combine_save(cpl_frameset *framelist, 
                                   cpl_parameterlist *parlist, int isfirst,
                                   memstruct *ps, configstruct *cs,
                                   cpl_frame **product_frame_mean_dark,
                                   cpl_frame **product_frame_diffimg,
                                   cpl_frame **product_frame_diffimg_stats) {
    cpl_propertylist *plist,*elist,*p;
    int status,ndit,night,i;
    float dit,dit2;
    const char *fctid = "hawki_dark_combine_save";
    const char *esoout[] = {"darkcomb.fits","darkdiff.fits","darkdifftab.fits"};
    const char *prettypfx[] = {"dark","darkdiff","darkdifftab"};
    char outfile[3][BUFSIZ],dateobs[81];
    const char *recipeid = "hawki_dark_combine";

    /* Get info to make pretty names if requested. */

    for (i = 0; i < 3; i++) 
        strcpy(outfile[i],esoout[i]);
    if (cs->prettynames) {
        plist = casu_fits_get_phu(ps->darks[0]);
        if (hawki_pfits_get_dateobs(plist,dateobs) != CASU_OK ||
            hawki_pfits_get_dit(plist,&dit) != CASU_OK || 
            hawki_pfits_get_ndit(plist,&ndit) != CASU_OK) {
            cpl_msg_warning(fctid,"Missing header information. Reverting to predictable names");
        } else {
            night = casu_night_from_dateobs(dateobs);
            dit2 = 0.01*(float)((int)(100.0*dit + 0.5));
            for (i = 0; i < 3; i++) 
                (void)sprintf(outfile[i],"%s_%8d_%g_%d.fits",prettypfx[i],
                              night,dit2,ndit);
        }
    }

    /* If we need to make a PHU then do that now. */

    if (isfirst) {

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

        *product_frame_mean_dark = cpl_frame_new();
        cpl_frame_set_filename(*product_frame_mean_dark,outfile[0]);
        cpl_frame_set_tag(*product_frame_mean_dark,HAWKI_PRO_DARK);
        cpl_frame_set_type(*product_frame_mean_dark,CPL_FRAME_TYPE_IMAGE);
        cpl_frame_set_group(*product_frame_mean_dark,CPL_FRAME_GROUP_PRODUCT);
        cpl_frame_set_level(*product_frame_mean_dark,CPL_FRAME_LEVEL_FINAL);

        /* Base the header on the first image in the input framelist */

        plist = casu_fits_get_phu(ps->darks[0]);
        hawki_dfs_set_product_primary_header(plist,*product_frame_mean_dark,
                                             framelist,parlist,
                                             recipeid,"PRO-1.15",
                                             NULL,0);

        /* 'Save' the PHU image */                         

        if (cpl_image_save(NULL,outfile[0],CPL_TYPE_UCHAR,plist,
                           CPL_IO_DEFAULT) != CPL_ERROR_NONE) {
            cpl_msg_error(fctid,"Cannot save product PHU");
            cpl_frame_delete(*product_frame_mean_dark);
            return(-1);
        }
        cpl_frameset_insert(framelist,*product_frame_mean_dark);

        /* Create a new product frame object for the difference image */

        if (cs->we_expect & DIFFIMG) {
            *product_frame_diffimg = cpl_frame_new();
            cpl_frame_set_filename(*product_frame_diffimg,outfile[1]);
            cpl_frame_set_tag(*product_frame_diffimg,HAWKI_PRO_DIFFIMG_DARK);
            cpl_frame_set_type(*product_frame_diffimg,CPL_FRAME_TYPE_IMAGE);
            cpl_frame_set_group(*product_frame_diffimg,CPL_FRAME_GROUP_PRODUCT);
            cpl_frame_set_level(*product_frame_diffimg,CPL_FRAME_LEVEL_FINAL);

              /* Base the header on the first image in the input framelist */

            plist = casu_fits_get_phu(ps->darks[0]);
            hawki_dfs_set_product_primary_header(plist,*product_frame_diffimg,
                                                 framelist,parlist,
                                                 recipeid,
                                                 "PRO-1.15",NULL,0);

            /* 'Save' the PHU image */                         

            if (cpl_image_save(NULL,outfile[1],CPL_TYPE_UCHAR,plist,
                               CPL_IO_DEFAULT) != CPL_ERROR_NONE) {
                cpl_msg_error(fctid,"Cannot save product PHU");
                cpl_frame_delete(*product_frame_diffimg);
                return(-1);
            }
            cpl_frameset_insert(framelist,*product_frame_diffimg);
        }

        /* Create a new product frame object for the difference image stats 
           table */

        if (cs->we_expect & STATS_TAB) {
            *product_frame_diffimg_stats = cpl_frame_new();
            cpl_frame_set_filename(*product_frame_diffimg_stats,outfile[2]);
            cpl_frame_set_tag(*product_frame_diffimg_stats,
                              HAWKI_PRO_DIFFIMG_DARK_STATS);
            cpl_frame_set_type(*product_frame_diffimg_stats,
                               CPL_FRAME_TYPE_TABLE);
            cpl_frame_set_group(*product_frame_diffimg_stats,
                                CPL_FRAME_GROUP_PRODUCT);
            cpl_frame_set_level(*product_frame_diffimg_stats,
                                CPL_FRAME_LEVEL_FINAL);

              /* Base the header on the first image in the input framelist */

            plist = casu_fits_get_phu(ps->darks[0]);
            hawki_dfs_set_product_primary_header(plist,
                                                 *product_frame_diffimg_stats,
                                                 framelist,parlist,
                                                 recipeid,
                                                 "PRO-1.15",NULL,0);

            /* Fiddle with the extension header now */

            elist = casu_fits_get_ehu(ps->darks[0]);
            p = cpl_propertylist_duplicate(elist);
            casu_merge_propertylists(p,ps->drs);
            casu_merge_propertylists(p,cs->qc);
            if (! (cs->we_get & STATS_TAB))
                casu_dummy_property(p);
              hawki_dfs_set_product_exten_header(p,*product_frame_diffimg_stats,
                                                 framelist,parlist,
                                                 recipeid,
                                                 "PRO-1.15",NULL);
            status = CASU_OK;
            casu_removewcs(p,&status);

            /* And finally save the difference image stats table */

            if (cpl_table_save(ps->diffimstats,plist,p,outfile[2],
                               CPL_IO_DEFAULT) != CPL_ERROR_NONE) {
                cpl_msg_error(fctid,"Cannot save product table extension");
                cpl_frame_delete(*product_frame_diffimg_stats);
                cpl_propertylist_delete(p);
                return(-1);
            }
            cpl_propertylist_delete(p);
            cpl_frameset_insert(framelist,*product_frame_diffimg_stats);
        }
    }

    /* Get the extension property list */

    plist = casu_fits_get_ehu(ps->darks[0]);
    cpl_propertylist_update_int(plist,"ESO PRO DATANCOM",ps->ngood);

    /* Fiddle with the header now */

    casu_merge_propertylists(plist,ps->drs);
    casu_merge_propertylists(plist,cs->qc);
    p = cpl_propertylist_duplicate(plist);
    if (! (cs->we_get & MEANDARK))
        casu_dummy_property(p);
    hawki_dfs_set_product_exten_header(p,*product_frame_mean_dark,
                                       framelist,parlist,
                                       recipeid,"PRO-1.15",NULL);
                
    /* Now save the mean dark image extension */

    cpl_propertylist_update_float(p,"ESO QC DARK MED",
                                  cs->darkmed);
    cpl_propertylist_set_comment(p,"ESO QC DARK MED",
                                 "Median of master dark frame");
    cpl_propertylist_update_float(p,"ESO QC DARK MEAN",
                                  cs->darkmean);
    cpl_propertylist_set_comment(p,"ESO QC DARK MEAN",
                                 "Mean of master dark frame");
    cpl_propertylist_update_float(p,"ESO QC DARK STDEV",
                                  cs->darkrms);
    cpl_propertylist_set_comment(p,"ESO QC DARK STDEV",
                                 "RMS of mean dark frame");
    cpl_propertylist_update_float(p,"ESO QC PARTICLE_RATE",
                                  cs->particle_rate);
    cpl_propertylist_set_comment(p,"ESO QC PARTICLE_RATE",
                                 "[N/(detector*sec)] Particle rate");
    cpl_propertylist_update_int(p,"ESO QC DARK NBADPIX",
                                cs->nhot);
    cpl_propertylist_set_comment(p,"ESO QC DARK NBADPIX",
                                 "Number of hot pixels");
    cpl_propertylist_update_float(p,"ESO QC BADFRAC",
                                  cs->hotfrac);
    cpl_propertylist_set_comment(p,"ESO QC BADFRAC","Hot pixel fraction"); 
    status = CASU_OK;
    casu_removewcs(p,&status);
    if (cpl_image_save(ps->outimage,outfile[0],CPL_TYPE_FLOAT,p,
                       CPL_IO_EXTEND) != CPL_ERROR_NONE) {
        cpl_msg_error(fctid,"Cannot save product image extension");
        cpl_propertylist_delete(p);
        return(-1);
    }
    cpl_propertylist_delete(p);

    /* Now save the dark difference image extension */

    if (cs->we_expect & DIFFIMG) {
        p = cpl_propertylist_duplicate(plist);
        if (! (cs->we_get & DIFFIMG))
            casu_dummy_property(p);;
        cpl_propertylist_update_float(p,"ESO QC DARKDIFF_MED",
                                      cs->darkdiff_med);
        cpl_propertylist_set_comment(p,"ESO QC DARKDIFF_MED",
                                     "Median of dark difference image");
        cpl_propertylist_update_float(p,"ESO QC DARKDIFF_RMS",
                                      cs->darkdiff_rms);
        cpl_propertylist_set_comment(p,"ESO QC DARKDIFF_RMS",
                                     "RMS of dark difference image");
        hawki_dfs_set_product_exten_header(p,*product_frame_diffimg,
                                           framelist,parlist,
                                           recipeid,
                                           "PRO-1.15",NULL);
        casu_removewcs(p,&status);
        if (cpl_image_save(ps->diffimg,outfile[1],CPL_TYPE_FLOAT,p,
                           CPL_IO_EXTEND) != CPL_ERROR_NONE) {
            cpl_msg_error(fctid,"Cannot save product image extension");
            cpl_propertylist_delete(p);
            return(-1);
        }
        cpl_propertylist_delete(p);
    }

    /* Now any further difference image stats tables */

    if (! isfirst && (cs->we_expect & STATS_TAB)) {
        p = cpl_propertylist_duplicate(plist);
        if (! (cs->we_get & STATS_TAB))
            casu_dummy_property(p);
        hawki_dfs_set_product_exten_header(p,*product_frame_diffimg_stats,
                                           framelist,parlist,
                                           recipeid,
                                           "PRO-1.15",NULL);
        status = CASU_OK;
        casu_removewcs(p,&status);
        if (cpl_table_save(ps->diffimstats,NULL,p,outfile[2],CPL_IO_EXTEND)
                           != CPL_ERROR_NONE) {
              cpl_msg_error(fctid,"Cannot save product table extension");
            cpl_propertylist_delete(p);
             return(-1);
        }        
        cpl_propertylist_delete(p);
    }

    return(0);
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Fill undefined products with dummy products
  @param    ps           The memory structure defined in the main routine
  @param    cs           The configuration structure defined in the main routine */
/*---------------------------------------------------------------------------*/

static void hawki_dark_combine_dummy_products(memstruct *ps, configstruct *cs) {

    /* See if you even need to be here */

    if (cs->we_get == cs->we_expect)
        return;

    /* We always expect a mean frame. If we don't have one, then create
       a dummy */

    if (! (cs->we_get & MEANDARK)) {
        ps->outimage = casu_dummy_image(ps->darks[0]);

        /* Set up the QC parameters */
    
        cs->particle_rate = 0.0;
        cs->darkmed = 0.0;
        cs->darkmean = 0.0;
        cs->darkrms = 0.0;
        cs->nhot = 0;
        cs->hotfrac = 0.0;
    }

    /* Do the difference image */

    if ((cs->we_expect & DIFFIMG) && ! (cs->we_get & DIFFIMG)) {
        cs->darkdiff_med = 0.0;
        cs->darkdiff_rms = 0.0;
        ps->diffimg = casu_dummy_image(ps->darks[0]);
    }

    /* If a difference image stats table is required, then do that now */

    if ((cs->we_expect & STATS_TAB) && ! (cs->we_get & STATS_TAB))
        ps->diffimstats = hawki_create_diffimg_stats(0);

    return;
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Work out the number of hot pixels
  @param    ps           The memory structure defined in the main routine
  @param    cs           The configuration structure defined in the main routine */
/*---------------------------------------------------------------------------*/

static void hawki_dark_combine_hotpix(memstruct *ps, configstruct *cs) {
    int i,nx,ny,nh,nhot,j;
    long npts;
    cpl_image *im;
    unsigned char *bpm;
    float med,mad,lowcut,highcut,*data;
    casu_fits *f;

    /* Get some workspace to hold the bad pixel mask */

    im = casu_fits_get_image(ps->good[0]);
    nx = (int)cpl_image_get_size_x(im);
    ny = (int)cpl_image_get_size_y(im);
    npts = (long)(nx*ny);
    bpm = cpl_calloc(npts,sizeof(*bpm));

    /* Create a difference image for each of the good frames */

    for (i = 0; i < ps->ngood; i++) {
        f = casu_fits_duplicate(ps->good[i]);
        im = casu_fits_get_image(f);
        cpl_image_subtract(im,ps->outimage);
        
        /* Work out the stats of the difference image. Define a lower and
           upper cut. NB: a lower cut is needed since we are doing stats
           on a difference image and hot pixels will appear as either 
           bright or dark. Dead pixels will probably correct properly and
           hence shouldn't be flagged using this procedure. */

        data = cpl_image_get_data_float(im);
        casu_medmad(data,NULL,npts,&med,&mad);
        lowcut = med - 1.48*mad*(cs->thresh);
        highcut = med + 1.48*mad*(cs->thresh);
        for (j = 0; j < npts; j++) 
            if (data[j] > highcut || data[j] < lowcut)
                bpm[j] += 1;

        /* Get rid of temporary image */

        casu_fits_delete(f);
    }

    /* Define a pixel as hot so long as it is discordant on at least half of 
       the frames */

    nh = (ps->ngood + 1)/2;
    nhot = 0;
    for (j = 0; j < npts; j++)
        if (bpm[j] >= nh)
            nhot++;

    /* Clean up... */

    cpl_free(bpm);
        
    /* Set QC parameters */

    cs->nhot = nhot;
    cs->hotfrac = (float)nhot/(float)npts;
}


/*---------------------------------------------------------------------------*/
/**
  @brief    Normalise the dark frame and create diff image and stats table
  @param    jext         the extension number
  @param    exptime      the exposure time
  @param    ps           The memory structure defined in the main routine
  @param    cs           The configuration structure defined in the main routine */
/*---------------------------------------------------------------------------*/

static void hawki_dark_combine_normal(int jext, float exptime, memstruct *ps,
                                      configstruct *cs) {

    int nx,ny,ndiff,ncells;
    long npi,i;
    unsigned char *bpm;
    float med,sig,*idata,grms,gdiff;
    casu_fits *mdimage;
    const char *fctid="hawki_dark_combine_normal";

    /* Load up the bad pixel mask */

    nx = (int)cpl_image_get_size_x(ps->outimage);
    ny = (int)cpl_image_get_size_y(ps->outimage);
    npi = nx*ny;
    cs->particle_rate = 0;
    bpm = casu_mask_get_data(ps->master_mask);

    /* Now find out how many 'good' pixels were rejected for
       being too high during the combination phase */

    ndiff = 0;
    for (i = 0; i < npi; i++)
        if ((ps->rejplus)[i] > 0 && bpm[i] == 0)
            ndiff += (ps->rejplus)[i];
    cs->particle_rate = (float)ndiff/(exptime*(float)(ps->ndarks));

    /* Work out the RMS of the mean dark frame */

    idata = cpl_image_get_data(ps->outimage);
    casu_medmad(idata,bpm,npi,&med,&sig);
    sig *= 1.48;
    cs->darkmed = med;
    cs->darkrms = sig;
    casu_meansig(idata,bpm,npi,&med,&sig);
    cs->darkmean = med;

    /* Load up the master dark */

    if (ps->master_dark != NULL) {
        mdimage = casu_fits_load(ps->master_dark,CPL_TYPE_FLOAT,jext);
        if (mdimage == NULL) 
            cpl_msg_info(fctid,
                         "Master dark extension %" CPL_SIZE_FORMAT " won't load",
                         (cpl_size)jext);
        else if (casu_is_dummy(casu_fits_get_ehu(mdimage))) {
            cpl_msg_info(fctid,
                         "Master dark extension %" CPL_SIZE_FORMAT " is a dummy!",
                         (cpl_size)jext);
            freefits(mdimage);
        }
    } else 
        mdimage = NULL;

    /* Form the difference image. */

    cs->darkdiff_med = 0.0;
    cs->darkdiff_rms = 0.0;
    ncells = cs->ncells;
    hawki_difference_image(casu_fits_get_image(mdimage),ps->outimage,bpm,
                           ncells,1,&gdiff,&grms,&(ps->diffimg),
                           &(ps->diffimstats));
    freefits(mdimage);
    casu_mask_clear(ps->master_mask);
    cs->darkdiff_med = gdiff;
    cs->darkdiff_rms = grms;
    if (ps->diffimg != NULL)
        cs->we_get |= DIFFIMG;
    if (ps->diffimstats != NULL)
        cs->we_get |= STATS_TAB;
    return;
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Do make dummys and save
  @param    jext         the image extension in question
  @param    framelist    the input frame list
  @param    parlist      the input recipe parameter list
  @param    isfirst      TRUE if this is the first extension
  @param    ps           The memory structure defined in the main routine
  @param    cs           The configuration structure defined in the main routine
  @param    product_frame_mean_dark   The frame for the mean dark product
  @param    product_frame_diffimg     The frame for the difference image product  @param    product_frame_diffimg_stats The frame for the diffimg stats table
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/

static int hawki_dark_combine_lastbit(int jext, cpl_frameset *framelist,
                                      cpl_parameterlist *parlist,
                                      int isfirst, memstruct *ps,
                                      configstruct *cs,
                                      cpl_frame **product_frame_mean_dark,
                                      cpl_frame **product_frame_diffimg,
                                      cpl_frame **product_frame_diffimg_stats) {
    int retval;
    const char *fctid="hawki_dark_combine_lastbit";

    /* Make whatever dummy products you need */

    hawki_dark_combine_dummy_products(ps,cs);

    /* Save everything */

    cpl_msg_info(fctid,"Saving products for extension %" CPL_SIZE_FORMAT,
                 (cpl_size)jext);
    retval = hawki_dark_combine_save(framelist,parlist,isfirst,ps,cs,
                                     product_frame_mean_dark,
                                     product_frame_diffimg,
                                     product_frame_diffimg_stats);
    if (retval != 0) {
        hawki_dark_combine_tidy(ps,0);
        return(-1);
    }

    /* Free some stuff up */

    hawki_dark_combine_tidy(ps,1);
    return(0);
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Initialise the pointers in the memory structure
  @param    ps           The memory structure defined in the main routine
 */
/*---------------------------------------------------------------------------*/

static void hawki_dark_combine_init(memstruct *ps) {
    ps->labels = NULL;
    ps->darklist = NULL;
    ps->darks = NULL;
    ps->ndarks = 0;
    ps->good = NULL;
    ps->ngood = 0;
    ps->master_dark = NULL;
    ps->master_mask = NULL;
    ps->outimage = NULL;
    ps->drs = NULL;
    ps->rejmask = NULL;
    ps->rejplus = NULL;
    ps->diffimg = NULL;
    ps->diffimstats = NULL;
}

/*---------------------------------------------------------------------------*/
/**
  @brief    Free any allocated workspace in the memory structure
  @param    ps           The memory structure defined in the main routine
  @param    level        The level of tidying. 
 */
/*---------------------------------------------------------------------------*/

static void hawki_dark_combine_tidy(memstruct *ps, int level) {

    freeimage(ps->outimage);
    freefitslist(ps->darks,ps->ndarks);
    freepropertylist(ps->drs);
    freeimage(ps->diffimg);
    freetable(ps->diffimstats);
    freespace(ps->rejmask);
    freespace(ps->rejplus);
    if (level == 1)
        return;
    freespace(ps->labels);
    freeframeset(ps->darklist);
    freespace(ps->good);
    freeframe(ps->master_dark);
    freemask(ps->master_mask);
}

/**@}*/
/*

$Log: hawki_dark_combine.c,v $
Revision 1.15  2015/11/18 20:07:41  jim
Fixed so that no WCS keywords get into the images

Revision 1.14  2015/10/20 11:53:51  jim
Fixed problem with QC in the diffimage table

Revision 1.13  2015/09/23 19:16:38  jim
fixed QC

Revision 1.12  2015/09/11 09:31:20  jim
Changed parameter declarations from _value to _range where appropriate

Revision 1.11  2015/08/07 13:07:06  jim
Fixed copyright to ESO

Revision 1.10  2015/03/02 10:50:44  jim
change in error message

Revision 1.9  2015/01/29 12:03:01  jim
Modified comments. Modified command line arguments to use strings for
enums where that makes sense. Also removed some support routines to
hawki_utils.c

Revision 1.8  2014/12/11 12:24:08  jim
lots of upgrades

Revision 1.7  2014/04/09 11:08:21  jim
Get rid of a couple of compiler moans

Revision 1.6  2014/03/26 16:07:29  jim
Cosmetic changes

Revision 1.5  2013/11/21 09:38:14  jim
detabbed

Revision 1.4  2013/11/07 10:05:59  jim
Fixed calls to tidy routine

Revision 1.3  2013-10-24 09:32:40  jim
prettynames added

Revision 1.2  2013-08-29 17:30:26  jim
Altered to remove remaining globals

Revision 1.1.1.1  2013-08-27 12:07:48  jim
Imported


*/
