This could use a little refactoring maybe, but I'm leaving it as is for now for simplicity.