/*
user defined function
insert lines from a text file into another text file at user defined position

parameters: path + file name of destination file
            path + file name of source file
            line number:  0 = first line
                         <0 = append at end of file
                         >line count of target file = append at end of file

return value: number of inserted lines
              negative value = error occurred
              
don't need string table entry
don't need global variable
don't need #define

*/

//prototype NUMBER my_insertfileintofile(STRING, STRING, STRING, STRING, NUMBER);
function my_insertfileintofile(sPathDest, sNameDest, sPathSource, sNameSource, nPosition)
  LIST   listID1, listID2;
  NUMBER nResult1, nResult2, nLineCount1, nLineCount2, nCount, nMode;
  STRING svString;
  
begin
  if ((sPathDest = "") || (sNameDest = "") || (sPathSource = "") || (sNameSource = ""))
  then
    return -1;
  endif;  
  
  listID1 = ListCreate(STRINGLIST);
  listID2 = ListCreate(STRINGLIST);
  if ((listID1 = LIST_NULL) || (listID2 = LIST_NULL))
  then
    ListDestroy(listID1);
    ListDestroy(listID2);
    return -2;
  endif;      
  
  //suspend possibly write protection
  nResult1 = SetFileInfo(sPathDest^sNameDest, FILE_ATTRIBUTE, FILE_ATTR_NORMAL, "");
  if (nResult1 < 0)
  then
    ListDestroy(listID1);
    ListDestroy(listID2);
    return -3;
  endif;  
  
  //read files
  nResult1 = ListReadFromFile(listID1, sPathDest^sNameDest);
  nResult2 = ListReadFromFile(listID2, sPathSource^sNameSource);
  if ((nResult1 < 0) || (nResult2 < 0))
  then
    ListDestroy(listID1);
    ListDestroy(listID2);
    return -4;
  endif;

  //count number of lines
  nLineCount1 = ListCount(listID1);
  nLineCount2 = ListCount(listID2);
  
  if (nLineCount2 = 0)
  then
    ListDestroy(listID1);
    ListDestroy(listID2);
    return 0;
  endif;
  
  //go to insert position and set insert method
  if ((nPosition < 0) || (nPosition >= nLineCount1))
  then
    ListSetIndex(listID1, LISTLAST);
    nMode = AFTER;
  else
    ListSetIndex(listID1, nPosition);
    nMode = BEFORE;
  endif;
  
  ListSetIndex(listID2, LISTFIRST);
  nCount = 0;
  
  while (nLineCount2 > nCount)
    //read string
    nResult2 = ListCurrentString(listID2, svString);
    //insert string
    nResult1 = ListAddString(listID1, svString, nMode);
    if ((nResult1 < 0) || (nResult2 < 0))
    then
      ListDestroy(listID1);
      ListDestroy(listID2);
      return -5;
    endif;
    ListSetIndex(listID1, LISTNEXT);
    ListSetIndex(listID2, LISTNEXT);
    nCount = nCount +1;
  endwhile;
  
  //write to file
  nResult1 = ListWriteToFile(listID1, sPathDest^sNameDest);
  if (nResult1 < 0)
  then
    ListDestroy(listID1);
    ListDestroy(listID2);
    return -6;
  endif;
  
  ListDestroy(listID1);
  ListDestroy(listID2);
  return nCount;
  
end;
