--Applescript direct
-- Script to invoke TeXCount <http://folk.uio.no/einarro/Comp/texwordcount.html>
-- and produce a PDF that gets opened in TeXShop
-- Ramon Figueroa-Centeno (March 11, 2009)

property PDF : false

tell application "TeXShop"
	
	set the front_document to the front document
	set FILEPATH to path of the front_document
	set basename to do shell script "basename " & quoted form of FILEPATH & " .tex"
	set dirname to do shell script "dirname " & quoted form of FILEPATH
	set PDFfile to (dirname & "/" & basename & "-count.pdf")
	set HTMLfile to (dirname & "/" & basename & "-count.html")
	
	-- If the front document is not saved dump its 
	-- content to a temporary file and use that
	if the front_document is modified then
		set myButton to button returned of (display dialog "You need to save changes to your document!" buttons {"Cancel ", "Save"} default button 2 with icon caution)
		if myButton is "Cancel " then
			return
		else
			try
				save the front document
				delay 1
			on error
				return
			end try
		end if
	end if
	-- If the front document is saved then make a symbolic
	-- link to it in the /tmp directory. This way we avoid
	-- the "bug" (feature) in texcount that takes a file with
	-- spaces in its name name and takes it as a list of files
	-- even in quoted form or with escaped spaces.
	set texpath to the path of the front_document
	set symlinkpath to do shell script "mktemp /tmp/XXXXXXXX"
	do shell script "rm " & symlinkpath
	do shell script "ln -s " & (quoted form of texpath) & " " & symlinkpath
	set texpath to symlinkpath
	--set TMP to texpath
	
	-- Run TeXCount to generate an HTML file
	set TeXcount to "/usr/texbin/texcount -html -inc -v "
	do shell script TeXcount & texpath & " > " & texpath & ".html"
	
	-- Replace the name of the temporary file we are using to 
	-- the name of the current TeX window inside the TeXCount
	-- HTML output
	set ugly to do shell script "perl -e \"print quotemeta ('" & texpath & "');\""
	set beautiful to the name of the front document
	do shell script "sed -i 's/" & ugly & "/" & beautiful & "/g' " & texpath & ".html"
	
	
	if not PDF then
		do shell script "mv " & texpath & ".html " & HTMLfile
		-- Open the HTML file with the TeXCount output
		do shell script "open " & HTMLfile
	else
		-- Convert HTML file to a PDF file
		set convert to "/System/Library/Printers/Libraries/convert -f "
		do shell script convert & texpath & ".html" & " -o " & quoted form of texpath & ".pdf"
		
		do shell script "mv " & texpath & ".pdf " & PDFfile
		-- Open PDF in TeXShop
		do shell script "open -a TeXShop " & PDFfile
		
		do shell script "rm " & texpath & ".html"
		
	end if
	
	-- Delete the files/symlinks created by this script
	do shell script "rm " & texpath
	
end tell