#!/bin/bash
 
TM_TMPDIR=$(mktemp -d)
 
PDFNAME=$(osascript -e 'tell app "SystemUIServer"' -e activate -e 'return POSIX path of (choose file name with prompt "Name the PDF:" default name "'"${TM_FILENAME%.*}"'.pdf" default location the path to desktop)' -e 'end tell')

if [[ $? != 0 ]]; then
    osascript -e 'tell app "TextMate" to activate' &>/dev/null &
	rm -rf "$TM_TMPDIR"
    exit
fi

pdflatex -output-directory "$TM_TMPDIR" -jobname "latex-job" "$TM_FILEPATH"

mv "$TM_TMPDIR/latex-job.pdf" "$PDFNAME"
rm -rf "$TM_TMPDIR"
 
open "$PDFNAME"