added tempfile usage, some enhancements