Move common functions to separate file

This way malloc wrappers/error printers can be shared between different
source files.
Move data copying into a function
Copy file using fread/fwrite

This should be a bit faster (not that it really matters).