#define PY_SSIZE_T_CLEAN
#include <Python.h>

#include "cmunipack.h"
#include "ccdfileclass.h"

PyObject *cmpack_error(int code);
PyObject *err_closed(void);

typedef struct {
    PyObject_HEAD
	CmpackMasterBias *f;
} MasterBias;

static PyObject *
MasterBias_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    MasterBias *self = (MasterBias*)type->tp_alloc(type, 0);
	if (self != NULL)
		self->f = NULL;
    return (PyObject *)self;
}

static void
MasterBias_dealloc(MasterBias* self)
{
	if (self->f)
		cmpack_mbias_destroy(self->f);
    self->ob_base.ob_type->tp_free((PyObject*)self);
}

static int
MasterBias_init(MasterBias *self, PyObject *args, PyObject *kwds)
{
	int res, format = CMPACK_BITPIX_AUTO;
	double minvalue = 0.0, maxvalue = 65535.0;
	CmpackBorder b;
	PyObject *output, *border = NULL;

	static char *kwlist[] = {"output", "format", "border", "minvalue", "maxvalue", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|iO!dd", kwlist, &CCDFileType, &output, 
		&format, &PyTuple_Type, &border, &minvalue, &maxvalue))
        return -1;

	if (!self->f) {
		self->f = cmpack_mbias_init();
		if (!self->f) {
			PyErr_SetString(PyExc_MemoryError, "Memory allocation error");
			return -1;
		}
	}
	res = cmpack_mbias_open(self->f, ((CCDFile*)output)->f);
	if (res!=0) {
		cmpack_error(res);
		return -1;
	}
	cmpack_mbias_set_bitpix(self->f, format);
	if (border) {
		if (!PyArg_ParseTuple(border, "iiii", &b.left, &b.top, &b.right, &b.bottom)) 
			return -1;
		cmpack_mbias_set_border(self->f, &b);
	}
	cmpack_mbias_set_minvalue(self->f, minvalue);
	cmpack_mbias_set_maxvalue(self->f, maxvalue);
	return 0;
}

static PyObject *
MasterBias_flush(MasterBias *self, PyObject *args)
{
	if (self->f) {
		int res = cmpack_mbias_close(self->f);
		self->f = NULL;
		if (res!=0)
			return cmpack_error(res);
	}
	Py_RETURN_NONE;
}

static PyObject *
MasterBias_border(MasterBias *self, void *data)
{
	CmpackBorder b;
	cmpack_mbias_get_border(self->f, &b);
	return Py_BuildValue("iiii", b.left, b.top, b.right, b.bottom);
}

static PyObject *
MasterBias_format(MasterBias *self, void *data)
{
	return PyLong_FromLong(cmpack_mbias_get_bitpix(self->f));
}

static PyObject *
MasterBias_minvalue(MasterBias *self, void *data)
{
	return PyFloat_FromDouble(cmpack_mbias_get_minvalue(self->f));
}

static PyObject *
MasterBias_maxvalue(MasterBias *self, void *data)
{
	return PyFloat_FromDouble(cmpack_mbias_get_maxvalue(self->f));
}

static PyObject *
MasterBias_add(MasterBias *self, PyObject *param)
{
	int res;

	if (!CCDFile_Check(param)) {
		/* Other types */
		PyErr_SetString(PyExc_TypeError, "Frame should be a CCDFile object.");
		return NULL;
	}

	res = cmpack_mbias_read(self->f, ((CCDFile*)param)->f);
	if (res!=0) {
		cmpack_error(res);
		return NULL;
	}
	Py_RETURN_NONE;
}

static PyGetSetDef MasterBias_getset[] = {
	{"format", (getter)MasterBias_format, NULL,
	"Image border size in pixels"},
	{"border", (getter)MasterBias_border, NULL, 
	"Image border size in pixels"},
	{"minvalue", (getter)MasterBias_minvalue, NULL, 
	"Threshold for \"invalid\" pixel values"},
	{"maxvalue", (getter)MasterBias_maxvalue, NULL, 
	"Threshold for \"overexposed\" pixels"},
	{NULL}
};

static PyMethodDef MasterBias_methods[] = {
	{"flush", (PyCFunction)MasterBias_flush, METH_NOARGS,
	"Close file"},
	{"add", (PyCFunction)MasterBias_add, METH_O,
	"Add a frame"},
    {NULL}  /* Sentinel */
};

PyTypeObject MasterBiasType = {
    PyObject_HEAD_INIT(NULL)
    .tp_name = "cmpack.MasterBias",          /*tp_name*/
    .tp_basicsize = sizeof(MasterBias),           /*tp_basicsize*/
    .tp_dealloc = (destructor)MasterBias_dealloc,           /*tp_dealloc*/
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,        /*tp_flags*/
    .tp_doc = "MasterBias correction",        /* tp_doc */
    .tp_methods = MasterBias_methods,           /* tp_methods */
    .tp_getset = MasterBias_getset,            /* tp_getset */
    .tp_init = (initproc)MasterBias_init,      /* tp_init */
    .tp_new = MasterBias_new                 /* tp_new */
};
