Fixed temp file lock problem, refactoring