a lot of needed refactoring and cleanup to make this code useable from ladyluck.