working version of global algo