/*
**********************************************************************
* Copyright (c) 2005 Chris McDonough
* All Rights Reserved.
* This software is subject to the provisions of the Zope Public License,
* Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
* WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
* FOR A PARTICULAR PURPOSE.
**********************************************************************
*/

#include "Python.h"

PyDoc_STRVAR(timeslice__doc__, "timeslice module\n");

static PyObject *
timeslice(PyObject *self, PyObject *args)
{ 
  int period, low, high, x;
  int when;

  if (PyTuple_Size(args) == 1) {
    when = (int)time(NULL);
  }

  if (!PyArg_ParseTuple(args, "i|i:timeslice", &period, &when))
    return NULL;

  if (period <= 0) {
    PyErr_SetString(PyExc_ValueError, "period must be greater than 0");
    return NULL;
  }
  
  low = when - period + 1;
  high = when + 1;
  
  for (x=low; x <= high; x++) {
    if ( (x % period) == 0 ) {
      break;
    }
    
  }
  return Py_BuildValue("i", x);
}

static PyMethodDef methods[] = {
  {"timeslice", timeslice, METH_VARARGS,
    "timeslice(period, [when]) ->\n\
Return an integer representing a the lowest epoch time value\n\
within 'slice' of time based on a divisor of 'period'. 'period' denotes \n\
the number of seconds in a timeslice.  If 'when' is not supplied, it is\n\
 assumed to be the current integer epoch time."},
  {NULL, NULL},
};

PyMODINIT_FUNC
inittimeslice(void)
{
  Py_InitModule3("timeslice", methods, timeslice__doc__);
}

