Looks like you are trying to code something like Cheops. Its an opensource tool and has been around for quite sometime. The first thing i'd recommend you to do would be to understand how Cheops works...