## we are accepting XML-formed requeste via pipe.

run <- TRUE

## main loop
waiter <- function(port=31415) {
  ## sock$host foreign host
  n <- 1
                                        # socket + listen + accept
                                        #  while(run) {
  sock <- make.socket(host="localhost", port=port, server=TRUE)
  on.exit(close.socket(sock))
  print(sock)
  rinn <- read.socket(sock,loop=TRUE)
  print("read")
  x <- handle(rinn)
  print(sprintf("x: %d",length(x)))
  y <- paste(paste(header(x),collapse=""),"\r\n",sep="")
  print(sprintf("y: %d",length(y)))
 # print(y)
  write.socket(sock, y)
  print("fin")
  close.socket(sock)
                                        # }
}

## adds a html-header around function
# todo
header <- function(x) {
  print(sprintf("header: %d",length(x)))
  return(x)
}

handle <- function(str,sock) {
  require(XML)
  x <- substr(str,49,60)
  n <- substr(str,61,64)
  x <- as.double(paste("0",x,sep="x"))
  n <- as.double(paste("0",n,sep="x"))

  print("handle1")
  M <- matrix(NA,nrow=3,ncol=12)
  M[1,] <- sapply(1:12*2,function(i) as.double(paste("0",substr(str,(i-1),(i)),sep="x")))/8
  M[2,] <- sapply(13:24*2,function(i) as.double(paste("0",substr(str,(i-1),(i)),sep="x")))/7
  M[3,] <- c(rep(0,4),sapply(1:8,function(i) as.double(paste("0",substr(str,i*2+47,i*2+48),sep="x"))))/11

  print("handle2")
 
  
  ## plot  
  ## do something
  #req <- xmlTreeParse(str, asText=TRUE)

  ## put a function into str
  st <- paste(paste("(",paste(M[1,],paste(paste("(x", 1:12,sep="**"),")",sep=""),sep="*"),")",sep=""),collapse="+")
  print("handle3")
  cur <- curve.to.jpg(st,TRUE)
  print("handle4")
  return(cur)
}


tmpfilename <- function(file=NULL, basedir="/tmp/", ending=".jpg") {
  ## ToDo
  i <- 1
  if(!is.null(file)) {
    print("file name given")
    paste(basedir,file,ending,sep="")
  } else {
    file <- tempfile(tmpdir=basedir)
  }
  return(file)
}


curve.to.jpg <- function(str,tofile=TRUE) {
  print(str)
  fl <- tmpfilename(str)
  print("file")
  jpeg(file=fl)
  p <- parse(text=paste("curve(",str,")",sep=""),n=NULL)
  print("parse")
  eval(p)
  print("eval")
  dev.off()
  cn<- file(fl,open="rb")
  r <- c()
  pic <- c()
  print("reread")
  while(length(r <- readBin(cn,"raw",1024)) > 0) 
    pic <- c(pic,r)
  close(cn)
  print("ping")
  return(pic)
}

### useful functions
## encodeString Encode Character Vector as for Printing
## paste: concatenate strings 


