Refact and minor bug correction