#' Cut a multi-state data set at a landmark time point
#' 
#' Given a dataset in long format, for instance generated by
#' \code{\link{msprep}}, this function cuts a multi-state data frame (object of
#' type "msdata") at a landmark time point LM. Administrative censoring can be
#' applied at time \code{cens}, equal for all individuals.
#' 
#' The function has a similar purpose as the \code{cutLM} function in the
#' \code{dynpred} package. Only follow-up after a landmark time point LM is
#' considered, so all subjects who are no longer at risk are removed. Column
#' \code{time} is updated based on the new Tstart and Tstop.
#' 
#' @param msdata An object of class \code{"msdata"}, such as output by
#' \code{\link{msprep}}
#' @param LM The landmark time point at which the cut is to be made
#' @param cens The time point at which administrative censoring is to be
#' applied; if missing, no administrative censoring will be applied
#' @return An object of class \code{"msdata"} again, containing only follow-up
#' data after LM. The data frame contains an extra column \code{Tentry} with
#' the time of entry into the present state.
#' @author Hein Putter \email{H.Putter@@lumc.nl}
#' @references L. C. de Wreede, M. Fiocco, and H. Putter (2011). mstate: An R
#' Package for the Analysis of Competing Risks and Multi-State Models. Journal
#' of Statistical Software 38: 7.
#' @keywords univar
#' @examples
#' 
#' tmat <- trans.illdeath(names=c("Tx","PR","RelDeath"))
#' data(ebmt3) # data from Section 4 of Putter, Fiocco & Geskus (2007)
#' msebmt <- msprep(time=c(NA,"prtime","rfstime"),status=c(NA,"prstat","rfsstat"),
#' 		data=ebmt3,trans=tmat)
#' # Cut at 5 years
#' cutLMms(msebmt, LM=1826)
#' events(cutLMms(msebmt, LM=1826))
#' 
#' @export cutLMms
cutLMms <- function(msdata, LM, cens)
{
  tmat <- attr(msdata, "trans")
  msdata$Tentry <- msdata$Tstart
  msdata <- msdata[msdata$Tstop>LM,]
  msdata$Tstart[msdata$Tstart<LM] <- LM
  if (!missing(cens)) {
    msdata$status[msdata$Tstop>cens] <- 0
    msdata$Tstop[msdata$Tstop>cens] <- cens
    msdata <- msdata[msdata$Tstop>=msdata$Tstart,]
  }
  msdata$time <- msdata$Tstop - msdata$Tstart
  attr(msdata, "trans") <- tmat
  return(msdata)
}
