Hideous code, but works efficiently