Disclaimer: I am not a lawyer, and you should go see an intellectual property lawyer who knows enough about software licensing. If you go see a stupid one, he or she will tell you "don't do it just to be on the safe side," which anyone can say.
See Clean room design. If the software behaves almost exactly the same, you shouldn't have read the source code.