substantially reorganised and commented my js