startRun <- 0
endRun <- 639

runIndex=""

load(file=paste("resDups.Rda",sep=""))
load(file="../individuals.Rda")

pops <- c("AFR","AMR","ASN","EUR")



lengthAll <- 3201157
shift <- 5000
intervallAll <- 10000
over <- intervallAll%/%shift

N1 <- lengthAll%/%shift
endRunAll <- (N1-over+1) # 639

allCount <- 0
allCount1 <- 0

res <- list()


for (posAll in (startRun+1):(endRun+1))  {

start <- (posAll-1)*shift
end <- start + intervallAll

if (end > lengthAll)  {

  end <- lengthAll
}
 
  
pRange <- paste("_",format(start,scientific=FALSE),"_",format(end,scientific=FALSE),sep="")


load(file=paste("resIBD_chr1",pRange,"annot.Rda",sep=""))

noIBD <- length(IBDannot)

if (noIBD>0)  {

for (ibdC in 1:noIBD)  {

allCount <- allCount + 1

if (!dups[allCount]) {

allCount1 <- allCount1 + 1

samples <-  IBDannot[[ibdC]][[8]]
tt <- table(c(pops,indi[samples,3]))
tt <- tt - 1
tss <- sum(tt)
tt <- tt/sum(tt)

res1 <- c(allCount1,allCount,ibdC,posAll,tss,tt)
res[[allCount1]] <- res1



}

cat(allCount," out of 222246\r")

}

}


}



rr <- unlist(res)
l <- length(res1)

PopulationMat <- matrix(rr,nrow=allCount1,ncol=l,byrow=TRUE)

colnames(PopulationMat) <- c("allCount1","allCount","ibdC","posAll","#Samples",pops)
                             

write.table(PopulationMat,file=paste("PopulationMat",runIndex,".txt",sep=""))
            
save(res,PopulationMat,file=paste("PopulationMat",runIndex,".Rda",sep=""))