added searchlength parameter and cleaned up code