final version with newest matlab code