Split up monolithic code. Added prepared statements etc.