
#'@title Converts doy or dwy into a factor that is used to bin data
#'
#'@description Converts a series of a variable such as day of year into numbered bins. 
#'Whenever the number of bins does not divide in 365 evenly a 
#'message showing the number of bins created and the number of days 
#'added to the last bin is provided. 
#'
#'Simply put, \code{ch_slice} is used to convert doy into a 
#'factor which is a number of bins per year. A year can be converted into any 
#'number of bins; slice does it based upon a number of days. So when you send it 
#'an array of doy it slices that into bins of the desired width. For example, 
#'if the step is 5. They 365/5 gives 73 bins and because of leap years there might 
#'be one extra day added every four years to the final bin.
#'
#' To illustrate for a bin of 5 days:
#' doy:
#'   1  2  3  4  5  6  7  8  9 10 11  12
#' Bin:
#'   1  1  1  1  1  2  2  2  2  2  3   3
#'
#' @param doy A vector of the day of calendar year for the dataset
#' @param step Width of bin in days
#'
#' @author Paul Whitfield, Kevin Shook
#' @return Returns a vector of bin numbers that is used as a factor for each day 
#' in the dataset and provides a message indicating the handling of partial bins
#' @export
#' 
#'
#' @seealso \code{\link{ch_binned_MannWhitney}} 
#'
#' @examples
#' doy <- c(1:365)
#' # first 30 days are 1, 31-60 are 2 etc
#' dice <- ch_slice(doy, 30)
#' plot(doy, dice)

ch_slice <- function(doy, step) {
  limit <- floor(366 / step)
  period <- floor((doy + step - 1) / step)
  
  extra <- 366 - limit * step
  
  period <- pmin(period, limit)

  llevels <- as.character(c(1:limit))
  period <- factor(period, levels = llevels)
  
  message(paste("Bins =", limit, " The number of extra points in last bin is up to ", 
              extra, " per year"))
  return(period)
}