Based on mcbytes' and cyanogenmod's code