cleaned up code, a bit few more LOC but hopefully more understandable