#!/usr/local/bin/Rscript --vanilla
ms <- function(file, silent = TRUE, ...) {
	if (grepl("\\.", file) == FALSE) {
		file <- paste(file, "Rnw", sep = ".")
	}
	Sys.setlocale(locale = "ja_JP.UTF-8")
	Sweave(file, encoding = "utf-8")
	base <- sub(".(R|S)nw", "", file)
	file <- paste(base, ".tex", sep = "")
	dir <- "/Applications/UpTeX.app/Contents/Resources/TEX/texbin"
	cmd <- sprintf("%s/ptex2pdf -u -l -s %s%s", dir, file, ifelse(silent, " | grep -v \"texmf\"", ""))
	repeat {
		system(cmd)
		con <- file(sub(".tex", ".log", file), open = "r", encoding = "utf-8")
		log <- readLines(con)
		close(con)
		no.error <- TRUE
		if (sum(grepl("Emergency stop", log)) > 0) {
			no.error <- FALSE
			break
		}
		if (sum(grepl("Rerun to get", log)) == 0) 
			break
	}
	if (no.error) {
		system(sprintf("%s/dvipdfmx -V 5 %s", dir, sub(".tex", ".dvi", file)))
	}
}
xfigure <- function(src, caption = "caption", fn, label = fn, 
	base = "figure", size = 320, width = size * 6/320, height = 2/3, 
	mgp = c(1.8, 0.6, 0), mar = c(3, 3, 1, 1), rev = -3, htbp = "htbp") {
	height <- width * height
	pdf(sprintf("%s/%s.pdf", base, fn), width = width, height = height)
	par(mgp = mgp, mar = mar)
	parsed <- parse(text = src)
	results <- eval(parsed)
	dev.off()
	header <- sprintf("\\begin{figure}[%s]\n\t\\centering", 
		htbp)
	trailer <- sprintf("\t\\vspace{%smm}\\caption{%s}\n\t\\label{%s}\n\\end{figure}", 
		rev, caption, label)
	cat(sprintf("%s\n\t\\includegraphics[bb=0 0 %sin %sin, clip, width=%sbp]{%s/%s.pdf}\n%s\n", 
		header, width, height, size, base, fn, trailer), fill = TRUE)
       invisible(results)
}
grDevices::pdf.options(family="Japan1")
arg <- commandArgs()
ms(arg[7])
warn <- warnings()
if (length(warn)) head(warn, 2)
