added typechecking, some new functions, and tidied up code a bit