modularised and cleaned up JS code