first working version, but still a lot of error cases to catch