Cleaned up sql querys.
Bug fixes.
Merge remote-tracking branch 'topi/master'