Not proud of this code, but it works fine AFAIK