* Vigenere
* Like simple substitution, but with a different letter based on a key
* A little more secure, and used in the US Civil War

parameter cText, sKey, lDecrypt

do case
case parameters() =0
    wait window 'Must specify something to put into cipher, and a key' nowait
    return ''
case parameters() =1
    wait window 'Must specify a key' nowait
    return ''
case parameters() =2
    lDecrypt =.f.
otherwise
    *
endcase   

cResult =''
cPlain =''
nlPlain =len(cText)
nlKey =len(sKey)

if '.TXT' $ upper(cText)
    if file(cText)
        *lKeyBoard =.f.
        cFile =cText
        wait window (iif(lDecrypt,'DeCrypting ','EnCrypting ') +cFile,1)
        nHandle =fopen(cFile)
        nLength =fseek(nHandle,0,2)         && Number of byes
        nFileTop =fseek(nHandle,0)             && Move pointer to BOF
        if nLength <= 0                     && Is file empty?
            =Ww('This file is empty!',3)
            if fclose(nHandle) =.f.
                =Ww(cFile +' could not be closed',3)
            endif
            return .f.
        else
            cText =fread(nHandle, nLength)
        endif
        if fclose(nHandle) =.f.
            =Ww(cFile +' could not be closed',3)
        endif
        lFile =.t.
    else
        wait window cText +' does not exist' nowait
    endif
else
    nLength =len(cText)
    lFile =.f.
endif

for nX =1 to nLength
    nK =nX -int(nX/ (nlKey +.001)) *nlKey
    cPlain =substr( cText, nX, 1)
    cKey =substr(sKey, nK, 1)
    cResult =cResult +Caesar(cPlain, asc(cKey), lDecrypt)
    * ? cPlain, substr(sKey,nK,1), nX, nK, cResult
endfor

if lFile =.t.
    erase &cFile
    if file(cFile)
        =ww('did not erase ' +cFile,3)
    endif
    nHandle =fcreate(cFile)
    nLength2 =fwrite(nHandle, cResult)
    lClosed =fclose(nHandle)
    if nLength2 <> nLength or lClosed =.f.
        =Ww('Something wrong happened',3)
    endif
    =Beeps('u2')
else
    return cResult
endif