## Spectrino utilities v1.0

# the spectrino function spnSetPPOpt returns comma list of all options
# some other functions, as spnGetProperty accepts <ALL> for property name
# and return comma list of all properies
# in all these cases the list is packed as string so if you need to
# parse the string to a list, use spnParseList
# e.g. spnParseList(spnSetPPOpt())

spnParseList <- function(str.list){
  sl = unlist(strsplit(str.list,","))
  lst = list()
  for (ss in sl){
    si = unlist(strsplit(ss,"="))
    lst[si[1]] = si[2]
  }
  return(lst)
}

# similar to spnGetGrp but the specs are in columns in a data.frame with spec names as column names

spnGetGrp.asFrame <- function(OnlyChecked,Grp){
  df <- data.frame(t(spnGetGrp(OnlyChecked,Grp)))
  nms <- character()
  chk <- spnGetSpcChecked(Grp)
  for (c in 1:length(chk)){
    if ((chk[c] == 1) || !OnlyChecked)  nms <- c(nms,spnGetSpcName(Grp,c))
  }  
  colnames(df) <- nms
  return (df)
}

# find a index of <sp.name> spec in <grp> group
# if not found then return 0

spnSpcIdx <- function(Grp, sp.name){
  sa = unlist(strsplit(spnGetSpcName(Grp,"*"),","))
  idx = which(sa == sp.name)
  return(idx) 
}

# create spc file in the active spec-group folder and 
# X and Y equal length OR only Y (X = NULL) - prn file
# open.in.active - open in active group
# override - override the file and the spec

spnWriteSpec <- function(Y, X = NULL, sp.name, overwrite.on.disk = TRUE, overwrite.in.group = TRUE){
  idx = spnActGrp(0)
  path = dirname(spnGetGrpName(-idx))
  
  oneCol = is.null(X)
  if (oneCol) ext = ".PRN"
  else ext = ".spc"
  sp.file = paste0(path,"/",sp.name,ext)
  
   # check for file
  if (file.exists(sp.file) & overwrite.on.disk) file.remove(sp.file)
  
  if (oneCol) {
    rpt = list(-1); names(rpt) <- c("Y"); sep = "" 
    rpt$Y = ";First=1"
    write.table(rpt, file=sp.file, append = TRUE, quote = FALSE, sep = sep, row.names = FALSE, col.names = FALSE)
  } else {
    if (length(Y) != length(X)) message("Error in vectors length")
    rpt = list(-1, -1); names(rpt) <- c("X","Y"); sep = "\t" 
  }
 
  size = length(Y)
  for (idx in c(1:size)) {
    rpt$Y = format(Y[idx], digits = 5)
    if (!oneCol) { rpt$X = format(X[idx] , digits = 5) } 
    write.table(rpt, file=sp.file, append = TRUE, quote = FALSE, sep = sep, row.names = FALSE, col.names = FALSE)
  }
   
  # check for spec in active group
  
  if (overwrite.in.group) {
    idx = spnSpcIdx(0,sp.name = sp.name)
    if (idx > 0) spnDelSpc(0,idx)
  } 
  
  cnt = spnOpenSpc(0,sp.file); return (cnt)
}
