#'ReproduceTime
#' 
#'@author Carmen Alvarez-Castro, \email{carmen.alvarez-castro@cmcc.it}
#'
#'@description Reproduce the time depending of the calendar days to be used for 
#' model projections, seasonal forecast data and reanalysis
#'
#'@param ical numer of days in the calendar (ical=366 if it counts leap-years)
#'       yr1 starting year of the study
#'       yr2 last year of the study
#'@import 
#'
#'@return time           numerical value with the format yyyymmdd
#'        conv.time     combination in a list of months, years, and days of the period
#'
#'@example
# yr1=2005
# yr2=2007
# ical=366
# seas=c(6,7,8,9,10,11)
# time=ReproduceTime(ical,yr1,yr2,seasonal=TRUE)

#
is.leapyear=function(year){
  return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0))
}
ReproduceTime=function(ical,yr1,yr2,seasonal=FALSE){
  if(ical==366){
    year=c()
    month=c()
    day=c()
    monthdum=c(rep(1,31),rep(2,28),rep(3,31),rep(4,30),rep(5,31),rep(6,30),
               rep(7,31),rep(8,31),rep(9,30),rep(10,31),rep(11,30),rep(12,31))
    monthdumB=c(rep(1,31),rep(2,29),rep(3,31),rep(4,30),rep(5,31),rep(6,30),
                rep(7,31),rep(8,31),rep(9,30),rep(10,31),rep(11,30),rep(12,31))
    daydum=c((1:31),(1:28),(1:31),(1:30),(1:31),(1:30),(1:31),(1:31),(1:30),(1:31),(1:30),(1:31))
    daydumB=c((1:31),(1:29),(1:31),(1:30),(1:31),(1:30),(1:31),(1:31),(1:30),(1:31),(1:30),(1:31))
    yr=c(yr1:yr2)
    bi=c(1:(yr2-yr1+1))
    for(i in 1:(yr2-yr1+1)){
      if (is.leapyear(yr[i])==TRUE){
        bi[i]=yr[i]
        year=c(year,rep(yr[i],length=length(monthdumB)))
        month=c(month,monthdumB)
        day=c(day,daydumB)
      }
      else{
        bi[i]=NaN
        year=c(year,rep(yr[i],length=length(monthdum)))
        month=c(month,monthdum)
        day=c(day,daydum)}
    }
    month=array(month[1:(length(month))])
    day=array(day[1:(length(day))])
    year=array(year[1:(length(year))])
  }
  if(ical==365){
    year=c()
    month=c()
    day=c()
    monthdum=c(rep(1,31),rep(2,28),rep(3,31),rep(4,30),rep(5,31),rep(6,30),
               rep(7,31),rep(8,31),rep(9,30),rep(10,31),rep(11,30),rep(12,31))
    daydum=c((1:31),(1:28),(1:31),(1:30),(1:31),(1:30),(1:31),(1:31),(1:30),(1:31),(1:30),(1:31))
    yr=c(yr1:yr2)
    for(i in 1:(yr2-yr1+1)){
      year=c(year,rep(yr[i],length=length(monthdum)))
      month=c(month,monthdum)
      day=c(day,daydum)}
    month=array(month[1:(length(month))])
    day=array(day[1:(length(day))])
    year=array(year[1:(length(year))])
  }
  if (ical==360){
    ndyear=360
    nmyear=12
    lmo=1:12
    nyear=yr2-yr1+1
    day=rep(1:30,times=nmyear*nyear)
    month=rep(rep(lmo,each=30),times=nyear)
    year=rep(yr1:yr2,each=ndyear)
  }
  time=array((year)*10000+month*100+day)
  
  if(seasonal==TRUE){
  ISEAS=which(month %in% seas)
  time=time[ISEAS]
  year=year[ISEAS]
  month=month[ISEAS]
  day=day[ISEAS]
  }
  return(list(year=year,month=month,day=day,time=time))
}# end of reproduction of the time
