Here I describe how to get the orientation of the device with respect to the horizontal plane and the magnetic North. It is just 1 line of code to get the magnetic heading from the orientation (rotation matrix).
Take the accelerometer and magnetometer readings a and m as 3 dimensional vectors. The a x m cross-product points to either East or West regardless of the orientation of the phone. Whether the cross product points to East or West depends on your sign conventions (upwards is positive or negative) and the handedness of your coordinate system (left- or right-handed).
You might want to apply at least a simple moving average to your data before computing the cross-product.
In general, it is not a good idea to use roll, pitch and yaw, so please don't. Anyway, you do not need it.
The accelerometer reading a, the cross-product a x m, and the cross-product of accelerometer reading and the cross-product a x (a x m) gives you 3 pair-wise perpendicular vectors. Make them unit vectors by multiplying them with the reciprocal of their respective length. These 3 unit vectors will given you a rotation matrix.
The rotation matrix is equivalent to the orientation of the device. In my application, the magnetic heading was atan2(R[Y][Y], R[Y][X])
where R is the rotation matrix. You might have to take different elements of the rotation matrix and perhaps change signs, depending on the conventions you follow.
If the API of the device provides the rotation matrix then it is just on line of code to get the magnetic heading.