#!/usr/bin/perl

$file = shift;
$titleorg = shift;
unless($file){
    $file = "1.jpg";
} 
unless($titleorg){
    $titleorg = "やんまーに";
} 

&readjpeg($file,$titleorg);

exit(0);

sub readjpeg(){
    my($file) = shift;
    my($titleorg) = shift;

    open(JPG,"<$file");
    open(OJPG,">$file.jpg");

    while (read(JPG,$c,2)){
	$exif = 0;
	$exifwrite = 0;
	
	@res = unpack "C*",$c;

#	printf ("%02X%02X\n",$res[0],$res[1]);

	## JPEG head 
	if ($res[0]==0xff && $res[1]==0xd8) {
	    printf OJPG "%s",$c;
	    next;
	}

	## APP0 の場合は EXIF DATAを記入
	if ($res[0]==0xff && $res[1]==0xe0) {
	    $exifwrite = 1;
	}

	## SOS の場合は終了
	if ($res[0]==0xff && $res[1]==0xda) {
	    printf OJPG "%s",$c;
	    last;
	}

	## EXIF head
	if ($res[0]==0xff && $res[1]==0xe1) {
	    $exif = 1;
	    printf "EXIF DATA OVERWRITED \n";
	}

	## marker write
	if ($exif==0){
	    printf OJPG "%s",$c;
	}

	## size read
	read(JPG,$c,2);
	if ($exif==0){
	    printf OJPG "%s",$c;
	}
	@res = unpack "C*",$c;
	$size = $res[0]*256+$res[1];
	
	read(JPG,$c,$size-2);
	if ($exif==0){
	    printf OJPG "%s",$c;
	}
	@res = unpack "C*",$c;

	if ($exifwrite==1){
	    &writeexif($titleorg);
	}

    }

    while (read(JPG,$c,2)){
	printf OJPG "%s",$c;
    }

    close(JPG);
    close(OJPG);
}


    
sub writeexif(){
    my $marker,$size;

    $titleorg = shift;
    unless ($titleorg){
	$titleorg = "ヤマタノオロチ";
    }

    $encoded = `echo $titleorg | /usr/bin/nkf -w16L0 `;
    @res = unpack "C*",$encoded;
    for ($i=0; $i< $#res ;++$i){
	$tmptit .= sprintf "%02X",$res[$i];
    }
    $title = "";
    $title .= $tmptit."00";
    $len = length($title)/2 - 2 ;
    
    $s = sprintf("%08X",$len);
    $s =~ m/([0-F]{2})([0-F]{2})([0-F]{2})([0-F]{2})/;
    $strsize = $4.$3.$2.$1;

    $size  = sprintf("%04X",48-14+$len);


    $marker     = "FFE1";
    $exifheader = "457869660000";
    $tiffheader = "49492A0008000000";
    $no         = "0100";
    $tag        = "9B9C";
    $type       = "0100";
    $offset     = "1A000000";    
    $sub        = "0000";
    $subtype    = "0000";

    $str  = "";
    $str .= $marker;
    $str .= $size;
    $str .= $exifheader;
    $str .= $tiffheader;
    $str .= $no;
    $str .= $tag;
    $str .= $type;
    $str .= $strsize;
    $str .= $offset;
    $str .= $sub;
    $str .= $subtype;
    $str .= $title;

    $marker = pack("H*",$str);
    printf OJPG "%s",$marker;
    
}
