Rewritten entire module - a lot more type-strict and complicated now