Final version. Kinda crappy and hackish, but... it works