#!/usr/bin/Rscript
Sys.setlocale(locale = "ja_JP.eucJP")
ms <- function(file, makeindex = FALSE, silent = FALSE, deletePdfs = FALSE, 
	deleteWorkfiles = FALSE, ...) {
	if (grepl("\\.", file) == FALSE) {
		file <- paste(file, "Rnw", sep = ".")
	}
	#	Sys.setlocale(locale="ja_JP.UTF-8")
	Sys.setlocale(locale = "ja_JP.eucJP")
	Sweave(file, encoding = "euc-jp", ...)
	base <- sub(".(R|S)nw", "", file)
	file <- paste(base, ".tex", sep = "")
	cmd <- sprintf("/Applications/UpTeX.app/teTeX/bin/platex -kanji=euc %s%s", 
		file, ifelse(silent, " | grep -v \"texmf\"", ""))
	repeat {
		system(cmd)
		con <- file(sub(".tex", ".log", file), open = "r", 
			encoding = "euc-jp")
		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) {
		if (makeindex) {
			system(sprintf("~/mbin/makeindex %s", sub(".tex", 
				"", file)))
			system(cmd)
		}
		system(sprintf("/Applications/UpTeX.app/teTeX/bin/dvipdfmx %s", 
			sub(".tex", ".dvi", file)))
	}
	if (deletePdfs) {
		system(sprintf("/bin/rm %s-???.pdf", base))
	}
	if (deleteWorkfiles) {
		system(sprintf("/bin/rm %s.aux %s.dvi %s.log %s.tex %s.toc", 
			base, base, base, base, base))
	}
}
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)
	results <- eval(parse(text = src))
	dev.off()
	header <- sprintf("\\begin{figure}[%s]\n\t\\begin{center}", 
		htbp)
	trailer <- sprintf("\t\\end{center}\n\t\\vspace{%smm}\\caption{%s}\n\t\\label{%s}\n\\end{figure}", 
		rev, caption, label)
	cat(sprintf("%s\n\t\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)
}
arg <- commandArgs()
print(arg)
ms(arg[6])
