Do the magnetometer calibration independently, following the tutorials linked below, and add the scaling and offset subtraction into any code you like.
Advanced procedure: Tutorial: How to calibrate a compass (and accelerometer) with Arduino | Underwater Arduino Data Loggers
Simpler approach: Simple Magnetic Calibration | Adafruit SensorLab - Magnetometer Calibration | Adafruit Learning System