Fixed bugs from original code, still haven't fully tested yet, but it doesn't crash now