added loadState function to load the state from files and correctly close it