More or less working version. Needs some cleanup