program a3;

uses windows,sysutils;

type TPBM_raw=array of boolean;
     PPBM_raw=^TPBM_raw;

function loadPBM(const fileName:string; out size:TSize): TPBM_raw;
const DIGIT=['0'..'9'];
      WHITESPACE=[' ',#13,#10,#9];
      BLOCKSIZE=1;

  function readNumber(const str:string;var pos:integer):integer;
  var start:integer;
  begin
    while (pos<length(str))and
         not  (str[pos] in DIGIT) do inc(pos);
    start:=pos;
    while (pos<length(str))and
         (str[pos] in DIGIT) do inc(pos);
    result:=strtoint(copy(str,start,pos-start));
  end;
var loadedFile:file;
    fileContent:string;
    i:integer;

    strEnd,strPos:pchar;
begin
  AssignFile(loadedFile,fileName);
  reset(loadedFile,BLOCKSIZE);
  SetLength(fileContent,fileSize(loadedFile)*BLOCKSIZE);
  BlockRead(loadedFile,fileContent[1],length(filecontent));
  CloseFile(loadedFile);
  //Ist es ein P1 datei
  if copy(fileContent,1,2)<>'P1' then
    raise Exception('Error: no PBM file: '+fileName);
  //Größe?
  i:=3;
  size.cx:=readNumber(fileContent,i);
  size.cy:=readNumber(fileContent,i);
  SetLength(result,size.cx*size.cy);
  ZeroMemory(result,size.cx*size.cy);
  //pixel
  strEnd:=@fileContent[length(fileContent)];
  strPos:=@fileContent[i];
  i:=0;
  while (strPos<strEnd) and (i<length(Result))  do begin
    case strPos^ of
      '0': inc(i);
      '1': begin
             Result[i]:=true;
             inc(i);
           end;
    end;
    inc(strPos);
  end;
end;

var i:integer;
    pbm_size:TSize;
    pbm_data: array of TPBM_raw;

    pbm_decode:array of cardinal;
    folie: PPBM_raw;
    x,y:integer;
    output:textfile;
begin
  //load Files
  SetLength(pbm_data,ParamCount);
  for i:=1 to ParamCount do
    pbm_data[i-1]:=loadPBM(ParamStr(i),pbm_size);

  //Entschlüsseln
  SetLength(pbm_decode,pbm_size.cx*pbm_size.cy div 4);
  ZeroMemory(pbm_decode,length(pbm_decode));
  for i:=0 to high(pbm_data) do
    for y:=0 to pbm_size.cy div 2-1 do
      for x:=0 to pbm_size.cx div 2-1 do
        if pbm_data[i][(x+y*pbm_size.cx)*2] then
          inc(pbm_decode[x+y*pbm_size.cx div 2]);
  for i:=0 to high(pbm_decode) do
    pbm_decode[i]:=cardinal(pbm_decode[i]>(length(pbm_data) div 2));
  folie:=@pbm_decode;
  for i:=0 to high(pbm_data) do begin
    AssignFile(output,paramStr(i+1)+'dec.pbm');
    Rewrite(output);
    writeln(output,'P1');
    writeln(output,inttostr(pbm_size.cx div 2)+' '+inttostr(pbm_size.cy div 2));
    for y:=0 to pbm_size.cy div 2-1 do begin
      for x:=0 to pbm_size.cx div 2-1 do
        if pbm_data[i][(x+y*pbm_size.cx)*2] = folie^[x+y*pbm_size.cx div 2] then
          write(output,'0')
         else
          write(output,'1');
      write(output,#13#10);
    end;
    CloseFile(output);


  end;
end.
