Resolve memory leak in noiseprofile and add additional proper error handling

This patch resolves the memory leak of inv_hist in the main function. In addition I took some time to rewrite some other functions by adding proper error handling regarding memory allocation and I/O errors to them, but it still needs to be tested again.