The bulk of the work, need to had some more error handling and test it but it seems to be working