Added logging and database handling. More modulization and safety checking
Merged changes