just about got this sucker refactored into decent structure