Fixed some bugs - currently needs to be optimized in generating database