improved rotation code, added boundary checking