#' Sees how many years have changed between a YLT and an adjusted YLT
#'
#' @description
#' Because they are longylts, requires the number of years.
#'
#' @param longylt1				A data frame containing longylt1
#' @param longylt2				A data frame containing longylt2
#' @param nyearsinylt			nyearsinylt
#' @param maxchange				How high to count when looking at how many years have
#' n more events. The default value of 5 is probably fine.
#'
#' @returns
#' Prints changes to the screen
#'
#' @author
#' Stephen Jewson \email{stephen.jewson@@gmail.com}
#'
#' @example man/examples/example_591_ylt_diagnostics_nchanges.R
#'
#' @export
ylt_diagnostics_nchanges=function(longylt1,longylt2,nyearsinylt=0,maxchange=5){

# 1: look at how many years have different numbers of events
	shortylt1=ylt_long2short(longylt1,nyearsinylt)
	shortylt2=ylt_long2short(longylt2,nyearsinylt)

	nyears1=length(shortylt1$year)
	nyears2=length(shortylt2$year)
	if(nyears1!=nyears2){
		message("Stopping in ylt_diagnostics_nchanges because the two longylts have different lengths.\n")
		stop()
	}

	message("ylt length = ",nyears1)
	count_same=0
	count_fewer=0
	count_more=0
	count_fewerj=numeric(maxchange)
	count_morej	=numeric(maxchange)
	for (i in 1:nyears1){
		nevents_in_year1=shortylt1$nevents_in_year[i]
		nevents_in_year2=shortylt2$nevents_in_year[i]
		diff=nevents_in_year2-nevents_in_year1
		if(diff==0)	count_same	=count_same+1
		if(diff<0)	count_fewer=count_fewer+1
		if(diff>0)	count_more	=count_more+1
		for (j in 1:maxchange){
			if(diff==-j)count_fewerj[j]=count_fewerj[j]+1
			if(diff== j)count_morej [j]=count_morej	[j]+1
		}
	}
	fewermorej=data.frame(c(1:maxchange),count_fewerj,count_morej)
	colnames(fewermorej)=c("n","nyears with n fewer","nyears with n more")
	message("test 1: number of years with the same number of events = ",count_same)
	message("test 2: number of years with fewer events = ",count_fewer)
	message("test 3: number of years with more events = ",count_more)

# 2 look at how many years have exactly the same events
	count_same_events=0
	for (i in 1:nyears1){
		same=TRUE
		nevents_in_year1=shortylt1$nevents_in_year[i]
		nevents_in_year2=shortylt2$nevents_in_year[i]
		if(nevents_in_year1!=nevents_in_year2)same=FALSE
		i0=shortylt2$longylt_start_row[i]
		i1=i0+shortylt2$nevents_in_year[i]-1
		if(!is.na(i0)){
			origins=longylt2$origin[i0:i1]
			added=c("added") %in% origins
			if(added)same=FALSE
		}
		if(same)count_same_events=count_same_events+1
	}

	message("test 4: number of years with exactly the same events = ",count_same_events)
	message("test 5: number of years with n fewer or more events...")
	print(fewermorej,row.names=FALSE)
}
