fixed bugs, made the thing more robust