Refactor to use tempfiles