# TODO: Add comment
# 
# Author: E.Korsching  11.09.2014  2026
###############################################################################


count.code.rows <- function(main.path="/home/user/eclipseR"){
	# this function counts all code lines of all existing R files
	#  in a folder with or without sub-folder structure and
	#  additionally counts the number of characters
	# it assumes an absolute path
	# empty lines are discarded
	#
	# the result is obviously an estimate and not perfect
	
	# ini
	if(main.path==""){ stop("provide an absolute path to the R folder") }
	if(is.na(file.info(main.path)$isdir)){ stop("R folder not existing\n") }
	
	f2 <- function(x){
		code.lines <- 0
		char.count <- 0
		# filter on files with *.R or *.r
		all.r.source <- list.files(path=x, pattern="\\.R$|\\.r$", all.files=F, full.names=T, recursive=T, ignore.case=F, include.dirs=F) #, no..=F)
		all.r.source.len <- length(all.r.source)
		
		# analyse per folder and file
		if(all.r.source.len!=0){
			for(j in 1:all.r.source.len){
				# read text as vector of lines
				cat("\n\nFile ",all.r.source[j],"\n")
				# count characters (without space chars)
				c.c <- 0
				con <- file(all.r.source[j], "r")
				while (T) {
					aline <- readLines(con, n=1)
					if ( length(aline) == 0 ) {
						break
					}
					xch <- nchar(aline)
					rch <- sum(attr(gregexpr("[ ]+", aline)[[1]], which="match.length"))
					if(rch==-1 & xch<10){ ech <- 0 }else if(rch==-1 & xch>=10){ ech <- xch - 10 }else{ ech <- xch - rch }
					cat("\n xch ",xch," rch ",rch," ech ",ech)
					c.c <- c.c + ech
					if(ech>0){ code.lines <- code.lines + 1 }
				}
				close(con)
				
				char.count <- char.count + c.c
			}
		}
		return(c(code.lines, char.count))
	}
	
	code.lines <- 0	# count of code lines
	char.count <- 0	# count of characters including comments
	
	# read in folder structure
	proj.dirs <- list.dirs(path=main.path, full.names=T, recursive=F)
	proj.dirs.len <- length(proj.dirs)
	if(proj.dirs.len==0){
		# no subfolder
		cat("\n no sub-folders in path \n")
		tmp <- f2(main.path)
		code.lines <- tmp[1]
		char.count <- tmp[2]
	}else{
		# subfolders
		for(i in 1:proj.dirs.len){
			tmp <- f2(proj.dirs[i])
			code.lines <- code.lines + tmp[1]
			char.count <- char.count + tmp[2]
		}
	}
	
	cat("\n\n number of code lines : ",code.lines, "\n number of characters : ",char.count, "\n\n")
	return()
}


# count.code.rows(main.path="/home/korschi/on3/eclipseR")

# old version 19.05.2026
# number of code lines :  94569
# number of characters :  3776030

# new version 19.05.2026
# number of code lines :  82445
# number of characters :  3622215





