Fixed a silly logic error. This function is very much still a work in progress.