retrieving original data from phase and magnitude of Fourier transform
You need to change how you're calculating the phase from "atan" to "atan2".  The reason is that atan doesn't work in all quadrants.  More on atan2 here.