Working version of Yuuichi Akagawa's code