ProbBins <- function(ano, fcyr, thr, quantile=TRUE) { 
  
  # Compute probabilistic bins (qt) of a forecast (fcyr) relative to
  # the forecast climatology over the whole period of anomalies
  # excluding the selected forecast year (fcyr).
  #
  # Args:
  #   ano: Array of anomalies from Ano.
  #   fcyr: Number of the forecast year of the anomalies.
  #   thr:  values used to bin the anomalies
  #   quantile: if quantile=T indicates in thr yoy indtroduces the
  #             thresholds to compute the quantiles but if quantile=F in thr 
  #             are introduced fix thresholds
  #
  # Returns:
  #    Probabilistic forecast information (1 or 0) at each grid point with
  #    dimensions c(length(thr+1),nmod/nexp/nobs, nmemb/nparam, nsfcyr, nltime, 
  #    nlat, nlon)
  #
  # History
  #  1.0 # 2013 (F. Lienert) # Original Code
  #  2.0 # 2014-03 (N. Gonzalez and V. Torralba
  #        <veronica.torralba@ic3.cat>) debugging
  
  # define dimensions
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  nexp<-dim(ano)[1]
  nmemb<-dim(ano)[2]
  nsdates<-dim(ano)[3]
  nlts<-dim(ano)[4]
  nlon <- dim(ano)[5]
  nlat <- dim(ano)[6]
  nfcyr<-length(fcyr)
  
  
  # separate forecast and hindcast
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  hind<-array(ano[,,-(fcyr),,,],dim=c(nexp,nmemb,nsdates-nfcyr,nlts,nlat,nlon))
  fore<-array(ano[1,,fcyr,,,],dim=c(nexp,nmemb,nfcyr,nlts,nlat,nlon))
  
  # the members and startdates are combined in one dimension
  sample<- array(hind,dim=c(nexp,nmemb*(nsdates-nfcyr),nlts,nlat,nlon))
  sample_fore <- array(fore,dim=c(nexp,nmemb*(nfcyr),nlts,nlat,nlon))
  
  # quantiles for each grid point and experiment
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  if (quantile==TRUE){
    qum<-apply(sample,c(1,3,4,5),FUN=quantile,probs=thr,na.rm=TRUE,names=FALSE,type=8) # dim=[length(thr)+1,nexp,nlts,nlat,nlon]
  }else{
    qum<-array(thr,dim=c(length(thr),nexp,nlts,nlat,nlon))
  }
    
  # defines a function to get the counts of an histogram for each forecast year and member 
  counts<-function(dat,cat,nm,nsd,mi,ma){
    quant<-dat[1:(cat-1)]
    brk<-c(mi,quant,ma)
    an<-array(dat[cat:((nm*nsd)+(cat-1))],dim=c(nm,nsd))
    PB<-apply(an,c(1,2),function(x,brks) hist(x,breaks=brks,plot=F)$counts,brks=brk)  
  }
  
  # the information of the thresholds and anomalies are combined to use apply
  
  data<-abind(aperm(qum,c(2,1,3,4,5)),sample_fore,along=2)
  
  # PBF:Probabilistic bins of a forecast.
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  # This array contains zeros and ones that indicate the category where your forecast is. 
  # e.g.(1,0,0) forecast is in first category  
  # The binary information is obtained for each experiment and grid point
  
  PBF<-aperm(array(apply(data,c(1,3,4,5),FUN=counts,cat=length(thr)+1,nm=nmemb,nsd=nfcyr,mi=min(ano),ma=max(ano)),
                   dim=c(length(thr)+1,nmemb,nfcyr,nexp,nlts,nlat,nlon)),c(1,4,2,3,5,6,7))
  
  
  return(PBF)
}
