some minor corrections, need more testing but the basics seems to work