/* 
 * This file is part of the FORS Library
 * Copyright (C) 2002-2010 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */

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

#include <vector>
#include <numeric>

#include <fors_image.h>

#include <moses.h>

#include <cpl.h>    

#include "fors_saturation.h"

//Returns the percentage of saturated pixels in an image
double fors_saturation_img_satper(const fors_image * image)
{
    cpl_image * data;
    cpl_mask * non_saturated;
    double lo_cut = 0.5;
    double hi_cut = 65534.5;
    double saturated_percentage;
    
    data = image->data;
    
    non_saturated = cpl_mask_threshold_image_create(
            data, lo_cut, hi_cut);

    saturated_percentage = (cpl_image_get_size_x(data) * 
            cpl_image_get_size_y(data) - 
            cpl_mask_count(non_saturated)) * 100.0 / 
                    (cpl_image_get_size_x(data) * 
                            cpl_image_get_size_y(data));

    cpl_mask_delete(non_saturated); non_saturated = NULL;

    return saturated_percentage;
}

//Returns the mean percentage of saturated pixels in an image list
double fors_saturation_imglist_satper(fors_image_list * imglist)
{
    int nimg = fors_image_list_size(imglist);
    double saturated;
    const fors_image * img = fors_image_list_first_const(imglist);
    std::vector<double> sat_percent;
    for (int i =0; i< nimg; i ++) 
    {
        double saturated_one;

        saturated_one = fors_saturation_img_satper(img);

        sat_percent.push_back(saturated_one);

        img = fors_image_list_next_const(imglist);
    }

    /* Compute overall percentage as mean of each percentage.
       Valid because input frames have same size. */
    saturated = std::accumulate(sat_percent.begin(), sat_percent.end(), 0.0) / 
            sat_percent.size();
    
    return saturated;
}

