// Reconcile DEP-5 debian/copyright to licensecheck
//
// Copyright : 2024 P Blackman
// License   : BSD-2-clause
//
// Self contained routines without global variable access


unit support;
{$mode delphi}

interface

const WhiteSpace :  set of Char = [' ',Chr(9)]; // Space & Tab

type
    tFileLic =
    record
        FName : AnsiString;
        Dep5,
        Actual : String;
    end;
    tFileLicArray = array of tFileLic;

var
    MyFiles : tFileLicArray;


function FindThisFile (const FileStr : AnsiString) : Integer;
function SingleAsterisk (Str : string) : Boolean;
function OpenFile (const Name : AnsiString; out Myfile : text) : Boolean;
procedure MangleName   (var Nam : AnsiString);
procedure UnMangleName (var Nam : AnsiString);


implementation uses StrUtils, rstrings;

// locate a file from d/copyright, find its index in the source file array
function FindThisFile (const FileStr : AnsiString) : Integer;
var F : Integer;
    Found : Boolean;
begin
    Found := false;
    F := 0;

    while not found and (F < Length (MyFiles)) do
    begin
        if MyFiles [F].FName = FileStr then
            found := true
        else
            F := F+1;
    end;

    if not found then
    begin
        writeln ('** ' + rsSfp + ' ', FileStr); // Superfluous file pattern
        F := -1;
    end;

    result := F;
end;

// True if string has a single asterisk
function SingleAsterisk (Str : string) : Boolean;
var I, Count : Integer;
begin
    Count := 0;

    for I := 1 to length (Str) do
        if Str [I] = '*' then
            inc (Count);

    result := Count=1;
end;

function OpenFile (const Name : AnsiString; out Myfile : text) : Boolean;
begin
    result := true;
    try
        AssignFile (Myfile, Name);
        Reset (Myfile);
    except
        result := false;
    end;
end;

procedure MangleName (var Nam : AnsiString);
begin
    Nam := ReplaceStr (Nam, ' ', '\1'); // maybe spaces in filenames (segments then treated as separate files!)
    Nam := ReplaceStr (Nam, ',', '\2'); // commas are problems too
    Nam := ReplaceStr (Nam, '£', '\3');
    Nam := ReplaceStr (Nam, '*', '\4'); // wildcards
    Nam := ReplaceStr (Nam, '?', '\5'); // wildcard
end;

procedure UnMangleName (var Nam : AnsiString);
begin
    Nam := ReplaceStr (Nam, '\1', ' ');
    Nam := ReplaceStr (Nam, '\2', ',');
    Nam := ReplaceStr (Nam, '\3', '£');
    Nam := ReplaceStr (Nam, '\4', '*');
    Nam := ReplaceStr (Nam, '\5', '?');
end;

end.
