refactoring to prepare for event system

additionally: fixed NameError
reduced redundant code

put code to read file, split it and close file into helper function