major code factorization and improve speed for alignment