#! /usr/bin/Rscript

src <-  "letterTemplate.Snw"

# you could also use read.xls(), but I had some problems with German umlauts there
# of course, a SQL address database would be even cooler
tab <- read.table("adressData.csv", header=T, sep=",", row.names=NULL)

# iterate over the lines in your table
for (x in 1:length(rownames(tab))){
  if(tab$comes[x] != "nein" && x == 7){

    # this here is just much ado about setting the variables
    prename <-  paste(strsplit(as.character(tab$Name[x]),  " " )[[1]][-1], ",", sep="")
    if(tab$isFemale[x])
      opening = paste("Liebe", prename, collapse=" ")
    else
      opening = paste("Lieber", prename, collapse=" ")

    fullName = as.character(tab[x, "Name"])
    fullName = strsplit(fullName, " ")[[1]]
    fullName = paste(fullName[-1], fullName[1], collapse="")
    
    adress1 = as.character(tab[x, "Adresse"])
    adress2 = as.character(tab[x, "Adresse2"])
    
    if(tab$comes[x] == "")
      printP = "PRINT"
    else
      printP = ""

    fileName <-  paste(
                       paste(strsplit(as.character(tab$Name[x]), " ")[[1]], collapse=""),
                       printP,
                       ".tex",
                       collapse="", sep="" )

    # we sweave the file which creates an .tex file and subsequently pdflatex it
    Sweave(src)
    system(paste("mv ", src, fileName))
    system(paste("pdflatex ", fileName , "&& pdflatex " ,fileName))
    
    # maybe you could delete the .tex and intermediate files here...
  }
}