## this script computes the areas of Halimeda tuna segments based on their outline morphometric data 

## works fine with R, ver. 4.0.2, and compatible versions of the packages uploaded below

## the script was designed for the study of Jiri Neustupa and Yvonne Nemcova entitled "..."

## uploading necessary libraries and setting the working directory for upload and saving the files
library(geomorph) ; library(pracma)
setwd("c:/R_prac/")


## data input  original TPS files [decimal DOTS, not commas!]

d<-readland.tps(file = "CW_IMPV.tps", readcurves = TRUE)
dd<-two.d.array(d)

write.table(dd, file = "outline.txt", append = TRUE, quote = FALSE, sep = " ", eol = "\n", na = "NA", dec = ".", row.names = FALSE, col.names = FALSE, qmethod = c("escape", "double"))

cm<-read.table(file="outline.txt")
pocetsloupcu<-ncol(cm) ; pocetobjektu<-nrow(cm)
cm2<-arrayspecs(cm,80,2)
cm3<-gpagen(cm2)
cm4<-two.d.array(cm3$coords)


## computation of area using the function "polyarea"

a<-1
while (a<pocetobjektu+1) {

CM<-cm[a,]
aa<-1
x<-NULL ; Y<-NULL
while (aa<pocetsloupcu+1) {
x<-c(x,CM[aa]) ; Y<-c(Y,CM[aa+1])
aa<-aa+2 }

x2<-as.data.frame(x) ; Y2<-as.data.frame(Y)
x3<-as.matrix(x2) ; Y3<-as.matrix(Y2)
x4<-as.vector(x3) ; Y4<-as.vector(Y3)

area<-polyarea(x4,Y4) ; area2<-abs(area)
write(area2,file="areas2.txt",ncolumns=1,append=TRUE)
a<-a+1 }


## this is the part converting areas to squared milimeters
# the scaling values (in green) need to be measured and adjusted!

areas<-read.table(file="areas2.txt")
a<-1 ; f5<-NULL
while (a<pocetobjektu+1) {
t1<-(areas[a,]*2)/1024
ff<-c(t1)
fff<-as.data.frame(ff) ; ffff<-t(fff) ; f5<-rbind(f5,ffff)
a<-a+1 }
write.table(f5, file="vysledny_A.txt", row.names=FALSE, col.names=FALSE, append=FALSE)

file.remove("outline.txt") ; file.remove("areas2.txt")
