Adapted logic from s3ckup