Completely rewritten code from groundup
No testing done yet