Refactored to smlibs and a few fixes