Refactor and add bad data error checking