reorganized code to reduce casting and typechecking