/**************************************************************

sky.c (C-Munipack project)
Copyright (C) 2003 David Motl, dmotl@volny.cz

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.

**************************************************************/

#include <stdlib.h>

#include "comfun.h"
#include "robmean.h"
#include "cmpack_common.h"
#include "cmpack_phot.h"
#include "phot.h"
#include "phfun.h"
#include "sky.h"

int Sky(CmpackPhotFrame *frame)
{
	int top = frame->border.top, left = frame->border.left;
	int bottom = cmpack_image_height(frame->image) - frame->border.bottom - 1;
	int right = cmpack_image_width(frame->image) - frame->border.right - 1;
	
	frame->skymod = frame->skysig = 0;

	if (left<=right && top<=bottom) {
		/* Median computation */
		double *ccd = (double*)cmpack_image_data(frame->image);
		double *tmp = cmpack_malloc((right-left+1)*(bottom-top+1)*sizeof(double));
		double datalo = frame->datalo, datahi = frame->datahi;
		int x, y, rowwidth = cmpack_image_width(frame->image), pixels = 0;
		for (y=top; y<=bottom; y++) {
			for (x=left; x<=right; x++) {
				double value = ccd[x+y*rowwidth];
				if (value>datalo && value<datahi)
					tmp[pixels++] = value;
			}
		}
		if (pixels>0) 
			cmpack_robustmean(pixels, tmp, &frame->skymod, &frame->skysig);
		cmpack_free(tmp);
	}
	return 0;
}
